From ef38f5a88a9c6f8e7f4ac13b07dafe1a08188696 Mon Sep 17 00:00:00 2001 From: AndrewKahr <22359829+AndrewKahr@users.noreply.github.com> Date: Fri, 3 Mar 2023 16:25:40 -0800 Subject: [PATCH] Code cleanup (#511) * Enable noImplicitAny Add types to all implicit any variables Bump target to ES2020 for recent language features (optional chaining) Code cleanup Add debug configuration for vscode Remove autorun flag from jest to remove warning Bump packages to fix dependency version mismatch warning Changed @arkweid/lefthook to @evilmartians/lefthook as @arkweid/lefthook has been deprecated in favor of @evilmartians/lefthook Added concurrency groups to integrity check and build workflows. New commits to branches will cancel superseded runs on the same branch/pr Update imports to not use require syntax Use node packages (ie node:fs rather than fs) AndroidVersionCode is now a string rather than a number as it gets converted to a string when passed out of the system Reduce timeout for windows builds Remove 2020.1.17f1 from windows builds due to repeated license activation errors Update naming scheme of workflows for consistency Update build names so target platform and unity version aren't cut off by github actions UI * Add exclude to test matrix for 2022.2 on android until Unity bug is fixed --------- Co-authored-by: AndrewKahr --- .github/workflows/build-tests-mac.yml | 84 + ...build-tests.yml => build-tests-ubuntu.yml} | 22 +- ...uild-tests.yml => build-tests-windows.yml} | 38 +- .github/workflows/integrity-check.yml | 4 + .github/workflows/mac-build-tests.yml | 106 - .vscode/launch.json | 25 + dist/index.js | 152113 +-------------- dist/index.js.map | 2 +- dist/licenses.txt | 860 +- dist/sourcemap-register.js | 2 +- dist/xhr-sync-worker.js | 60 - jest.config.js | 1 - package.json | 14 +- src/index.ts | 9 +- src/integrity.test.ts | 2 +- src/model/action.test.ts | 4 +- src/model/action.ts | 22 +- src/model/android-versioning.test.ts | 10 +- src/model/android-versioning.ts | 14 +- src/model/build-parameters.test.ts | 8 +- src/model/build-parameters.ts | 23 +- src/model/cache.ts | 2 +- src/model/cli/cli-functions-repository.ts | 2 +- src/model/cli/cli.ts | 23 +- .../cloud-runner/cloud-runner-options.ts | 83 +- src/model/cloud-runner/cloud-runner.ts | 3 +- .../providers/aws/aws-base-stack.ts | 2 +- .../aws/aws-cloud-formation-templates.ts | 8 +- .../providers/aws/aws-task-runner.ts | 17 +- .../services/garbage-collection-service.ts | 12 +- .../providers/aws/services/task-service.ts | 8 +- .../cloud-runner/providers/docker/index.ts | 5 +- .../k8s/kubernetes-job-spec-factory.ts | 8 +- .../providers/k8s/kubernetes-secret.ts | 2 +- .../providers/k8s/kubernetes-storage.ts | 2 +- .../providers/provider-interface.ts | 4 +- .../cloud-runner/remote-client/caching.ts | 20 +- src/model/cloud-runner/remote-client/index.ts | 6 +- .../remote-client/remote-client-logger.ts | 2 +- .../services/cloud-runner-custom-hooks.ts | 26 +- .../services/cloud-runner-custom-steps.ts | 13 +- .../services/cloud-runner-folders.ts | 2 +- .../services/cloud-runner-query-override.ts | 12 +- .../cloud-runner/services/custom-step.ts | 4 +- .../services/follow-log-stream-service.ts | 2 +- .../cloud-runner/services/lfs-hashing.ts | 8 +- .../services/shared-workspace-locking.ts | 2 +- .../services/task-parameter-serializer.ts | 28 +- .../tests/cloud-runner-async-workflow.test.ts | 3 +- ...loud-runner-environment-serializer.test.ts | 3 +- ...cloud-runner-remote-client-caching.test.ts | 4 +- ...cloud-runner-run-once-custom-hooks.test.ts | 3 +- .../cloud-runner-run-twice-caching.test.ts | 5 +- .../cloud-runner-run-twice-retaining.test.ts | 7 +- .../cloud-runner-s3-prebuilt-steps.test.ts | 3 +- .../cloud-runner-sync-environment.test.ts | 3 +- .../tests/shared-workspace-locking.test.ts | 9 +- .../workflows/build-automation-workflow.ts | 64 +- .../workflows/workflow-interface.ts | 2 +- src/model/docker.ts | 31 +- src/model/github.ts | 16 +- src/model/image-environment-factory.ts | 14 +- src/model/image-tag.test.ts | 28 +- src/model/image-tag.ts | 31 +- src/model/index.test.ts | 24 +- src/model/input-readers/action-yaml.ts | 4 +- .../input-readers/generic-input-reader.ts | 2 +- src/model/input-readers/git-repo.ts | 4 +- .../input-readers/test-license-reader.ts | 6 +- src/model/input.test.ts | 4 +- src/model/input.ts | 127 +- src/model/mac-builder.ts | 2 +- src/model/output.ts | 10 +- src/model/platform-setup.ts | 2 +- src/model/platform-setup/setup-android.ts | 4 +- src/model/platform-setup/setup-mac.ts | 4 +- src/model/platform-setup/setup-windows.ts | 6 +- .../platform-validation/validate-windows.ts | 10 +- src/model/platform.ts | 4 +- src/model/shared-types.ts | 6 + src/model/system.ts | 16 +- src/model/unity-versioning.ts | 10 +- src/model/versioning.test.ts | 24 +- src/model/versioning.ts | 91 +- tsconfig.json | 4 +- yarn.lock | 538 +- 86 files changed, 9861 insertions(+), 144996 deletions(-) create mode 100644 .github/workflows/build-tests-mac.yml rename .github/workflows/{build-tests.yml => build-tests-ubuntu.yml} (92%) rename .github/workflows/{windows-build-tests.yml => build-tests-windows.yml} (60%) delete mode 100644 .github/workflows/mac-build-tests.yml create mode 100644 .vscode/launch.json delete mode 100644 dist/xhr-sync-worker.js create mode 100644 src/model/shared-types.ts diff --git a/.github/workflows/build-tests-mac.yml b/.github/workflows/build-tests-mac.yml new file mode 100644 index 0000000..0068bea --- /dev/null +++ b/.github/workflows/build-tests-mac.yml @@ -0,0 +1,84 @@ +name: Builds - MacOS + +on: + workflow_dispatch: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + buildForAllPlatformsWindows: + name: ${{ matrix.targetPlatform }} on ${{ matrix.unityVersion }} + runs-on: macos-latest + strategy: + fail-fast: false + matrix: + projectPath: + - test-project + unityVersion: + - 2019.4.40f1 # Minimum version for IL2CPP + - 2020.1.17f1 + - 2020.2.7f1 + - 2020.3.44f1 + - 2021.1.28f1 + - 2021.2.19f1 + - 2021.3.18f1 + - 2022.1.24f1 + - 2022.2.6f1 + targetPlatform: + - StandaloneOSX # Build a MacOS executable + + steps: + ########################### + # Checkout # + ########################### + - uses: actions/checkout@v3 + with: + lfs: true + + ########################### + # Cache # + ########################### + - uses: actions/cache@v3 + with: + path: ${{ matrix.projectPath }}/Library + key: Library-${{ matrix.projectPath }}-macos-${{ matrix.targetPlatform }} + restore-keys: | + Library-${{ matrix.projectPath }}-macos- + Library- + + ########################### + # Set Scripting Backend # + ########################### + - name: Set Scripting Backend To il2cpp + run: | + mv -f "./test-project/ProjectSettings/ProjectSettingsIl2cpp.asset" "./test-project/ProjectSettings/ProjectSettings.asset" + + ########################### + # Build # + ########################### + - uses: ./ + env: + UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} + UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + with: + projectPath: ${{ matrix.projectPath }} + unityVersion: ${{ matrix.unityVersion }} + targetPlatform: ${{ matrix.targetPlatform }} + customParameters: -profile SomeProfile -someBoolean -someValue exampleValue + # We use dirty build because we are replacing the default project settings file above + allowDirtyBuild: true + + ########################### + # Upload # + ########################### + - uses: actions/upload-artifact@v3 + with: + name: Build MacOS (${{ matrix.unityVersion }}) + path: build + retention-days: 14 diff --git a/.github/workflows/build-tests.yml b/.github/workflows/build-tests-ubuntu.yml similarity index 92% rename from .github/workflows/build-tests.yml rename to .github/workflows/build-tests-ubuntu.yml index 52b894d..af59a75 100644 --- a/.github/workflows/build-tests.yml +++ b/.github/workflows/build-tests-ubuntu.yml @@ -1,12 +1,18 @@ -name: Builds +name: Builds - Ubuntu on: workflow_dispatch: - push: { branches: [main] } + push: + branches: + - main pull_request: paths-ignore: - '.github/**' +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + env: UNITY_LICENSE: "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nm0Db8UK+ktnOLJBtHybkfetpcKo=o/pUbSQAukz7+ZYAWhnA0AJbIlyyCPL7bKVEM2lVqbrXt7cyey+umkCXamuOgsWPVUKBMkXtMH8L\n5etLmD0getWIhTGhzOnDCk+gtIPfL4jMo9tkEuOCROQAXCci23VFscKcrkB+3X6h4wEOtA2APhOY\nB+wvC794o8/82ffjP79aVAi57rp3Wmzx+9pe9yMwoJuljAy2sc2tIMgdQGWVmOGBpQm3JqsidyzI\nJWG2kjnc7pDXK9pwYzXoKiqUqqrut90d+kQqRyv7MSZXR50HFqD/LI69h68b7P8Bjo3bPXOhNXGR\n9YCoemH6EkfCJxp2gIjzjWW+l2Hj2EsFQi8YXw==" +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: buildForAllPlatformsWindows: - name: Build for ${{ matrix.targetPlatform }} on version ${{ matrix.unityVersion }} + name: ${{ matrix.targetPlatform }} on ${{ matrix.unityVersion }} runs-on: windows-2019 strategy: fail-fast: false @@ -89,7 +67,7 @@ jobs: uses: ./ id: build-1 continue-on-error: true - timeout-minutes: 60 + timeout-minutes: 30 env: UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} @@ -111,7 +89,7 @@ jobs: uses: ./ id: build-2 continue-on-error: true - timeout-minutes: 60 + timeout-minutes: 30 if: steps.build-1.outcome == 'failure' env: UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} @@ -133,7 +111,7 @@ jobs: - name: Build Retry 2 uses: ./ id: build-3 - timeout-minutes: 60 + timeout-minutes: 30 if: ${{ steps.build-1.outcome == 'failure' && steps.build-2.outcome == 'failure' }} env: UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} diff --git a/.github/workflows/integrity-check.yml b/.github/workflows/integrity-check.yml index 8b9dd0e..4d64fb8 100644 --- a/.github/workflows/integrity-check.yml +++ b/.github/workflows/integrity-check.yml @@ -7,6 +7,10 @@ on: env: CODECOV_TOKEN: '2f2eb890-30e2-4724-83eb-7633832cf0de' +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: tests: name: Tests diff --git a/.github/workflows/mac-build-tests.yml b/.github/workflows/mac-build-tests.yml deleted file mode 100644 index 05d5c43..0000000 --- a/.github/workflows/mac-build-tests.yml +++ /dev/null @@ -1,106 +0,0 @@ -name: Mac Builds - -on: - workflow_dispatch: - push: - branches: - - main - -env: - UNITY_LICENSE: - "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \nm0Db8UK+ktnOLJBtHybkfetpcKo=o/pUbSQAukz7+ZYAWhnA0AJbIlyyCPL7bKVEM2lVqbrXt7cyey+umkCXamuOgsWPVUKBMkXtMH8L\n5etLmD0getWIhTGhzOnDCk+gtIPfL4jMo9tkEuOCROQAXCci23VFscKcrkB+3X6h4wEOtA2APhOY\nB+wvC794o8/82ffjP79aVAi57rp3Wmzx+9pe9yMwoJuljAy2sc2tIMgdQGWVmOGBpQm3JqsidyzI\nJWG2kjnc7pDXK9pwYzXoKiqUqqrut90d+kQqRyv7MSZXR50HFqD/LI69h68b7P8Bjo3bPXOhNXGR\n9YCoemH6EkfCJxp2gIjzjWW+l2Hj2EsFQi8YXw==" - -jobs: - buildForAllPlatformsWindows: - name: Build for ${{ matrix.targetPlatform }} on version ${{ matrix.unityVersion }} - runs-on: macos-latest - strategy: - fail-fast: false - matrix: - projectPath: - - test-project - unityVersion: - - 2019.4.40f1 # Minimum version for IL2CPP - - 2020.1.17f1 - - 2020.2.7f1 - - 2020.3.44f1 - - 2021.1.28f1 - - 2021.2.19f1 - - 2021.3.18f1 - - 2022.1.24f1 - - 2022.2.6f1 - targetPlatform: - - StandaloneOSX # Build a MacOS executable - - steps: - ########################### - # Checkout # - ########################### - - uses: actions/checkout@v3 - with: - lfs: true - - ########################### - # Cache # - ########################### - - uses: actions/cache@v3 - with: - path: ${{ matrix.projectPath }}/Library - key: Library-${{ matrix.projectPath }}-macos-${{ matrix.targetPlatform }} - restore-keys: | - Library-${{ matrix.projectPath }}-macos- - Library- - - ########################### - # Set Scripting Backend # - ########################### - - name: Set Scripting Backend To il2cpp - run: | - mv -f "./test-project/ProjectSettings/ProjectSettingsIl2cpp.asset" "./test-project/ProjectSettings/ProjectSettings.asset" - - ########################### - # Build # - ########################### - - uses: ./ - env: - UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} - UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} - UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} - with: - projectPath: ${{ matrix.projectPath }} - unityVersion: ${{ matrix.unityVersion }} - targetPlatform: ${{ matrix.targetPlatform }} - customParameters: -profile SomeProfile -someBoolean -someValue exampleValue - # We use dirty build because we are replacing the default project settings file above - allowDirtyBuild: true - - ########################### - # Upload # - ########################### - - uses: actions/upload-artifact@v3 - with: - name: Build MacOS (${{ matrix.unityVersion }}) - path: build - retention-days: 14 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..9c7be0a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,25 @@ +{ + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Debug Jest Test", + "program": "${workspaceRoot}/node_modules/jest/bin/jest.js", + "args": [ + "--collectCoverage=false", + "--colors", + "--config", + "${workspaceRoot}/jest.config.js", + "--runInBand", + "--runTestsByPath", + "${relativeFile}", + "--testPathPattern=${fileDirname}", + "--testTimeout=10000000" + ], + "outputCapture": "std", + "internalConsoleOptions": "openOnSessionStart", + "envFile": "${workspaceRoot}/.env", + "skipFiles": ["${workspaceRoot}/../../node_modules/**/*", "/**/*"] + } + ] +} diff --git a/dist/index.js b/dist/index.js index 09bcfe5..24a3505 100644 --- a/dist/index.js +++ b/dist/index.js @@ -25,15 +25,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -43,39 +34,37 @@ const model_1 = __nccwpck_require__(41359); const cli_1 = __nccwpck_require__(55651); const mac_builder_1 = __importDefault(__nccwpck_require__(39364)); const platform_setup_1 = __importDefault(__nccwpck_require__(64423)); -function runMain() { - return __awaiter(this, void 0, void 0, function* () { - try { - if (cli_1.Cli.InitCliMode()) { - yield cli_1.Cli.RunCli(); - return; - } - model_1.Action.checkCompatibility(); - model_1.Cache.verify(); - const { workspace, actionFolder } = model_1.Action; - const buildParameters = yield model_1.BuildParameters.create(); - const baseImage = new model_1.ImageTag(buildParameters); - if (buildParameters.cloudRunnerCluster !== 'local') { - yield model_1.CloudRunner.run(buildParameters, baseImage.toString()); +async function runMain() { + try { + if (cli_1.Cli.InitCliMode()) { + await cli_1.Cli.RunCli(); + return; + } + model_1.Action.checkCompatibility(); + model_1.Cache.verify(); + const { workspace, actionFolder } = model_1.Action; + const buildParameters = await model_1.BuildParameters.create(); + const baseImage = new model_1.ImageTag(buildParameters); + if (buildParameters.cloudRunnerCluster === 'local') { + core.info('Building locally'); + await platform_setup_1.default.setup(buildParameters, actionFolder); + if (process.platform === 'darwin') { + mac_builder_1.default.run(actionFolder); } else { - core.info('Building locally'); - yield platform_setup_1.default.setup(buildParameters, actionFolder); - if (process.platform === 'darwin') { - mac_builder_1.default.run(actionFolder); - } - else { - yield model_1.Docker.run(baseImage, Object.assign({ workspace, actionFolder }, buildParameters)); - } + await model_1.Docker.run(baseImage.toString(), { workspace, actionFolder, ...buildParameters }); } - // Set output - yield model_1.Output.setBuildVersion(buildParameters.buildVersion); - yield model_1.Output.setAndroidVersionCode(buildParameters.androidVersionCode); } - catch (error) { - core.setFailed(error.message); + else { + await model_1.CloudRunner.run(buildParameters, baseImage.toString()); } - }); + // Set output + await model_1.Output.setBuildVersion(buildParameters.buildVersion); + await model_1.Output.setAndroidVersionCode(buildParameters.androidVersionCode); + } + catch (error) { + core.setFailed(error.message); + } } runMain(); @@ -91,7 +80,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); class Action { static get supportedPlatforms() { return ['linux', 'win32', 'darwin']; @@ -100,16 +89,19 @@ class Action { return process.env.RUNNER_WORKSPACE === undefined; } static get isRunningFromSource() { - return path_1.default.basename(__dirname) === 'model'; + return node_path_1.default.basename(__dirname) === 'model'; } static get canonicalName() { + if (Action.isRunningFromSource) { + return node_path_1.default.basename(node_path_1.default.dirname(node_path_1.default.join(node_path_1.default.dirname(__filename), '/..'))); + } return 'unity-builder'; } static get rootFolder() { if (Action.isRunningFromSource) { - return path_1.default.dirname(path_1.default.dirname(path_1.default.dirname(__filename))); + return node_path_1.default.dirname(node_path_1.default.dirname(node_path_1.default.dirname(__filename))); } - return path_1.default.dirname(path_1.default.dirname(__filename)); + return node_path_1.default.dirname(node_path_1.default.dirname(__filename)); } static get actionFolder() { return `${Action.rootFolder}/dist`; @@ -158,7 +150,7 @@ const core = __importStar(__nccwpck_require__(42186)); const semver = __importStar(__nccwpck_require__(11383)); class AndroidVersioning { static determineVersionCode(version, inputVersionCode) { - if (!inputVersionCode) { + if (inputVersionCode === '') { return AndroidVersioning.versionToVersionCode(version); } return inputVersionCode; @@ -166,12 +158,12 @@ class AndroidVersioning { static versionToVersionCode(version) { if (version === 'none') { core.info(`Versioning strategy is set to ${version}, so android version code should not be applied.`); - return 0; + return '0'; } const parsedVersion = semver.parse(version); if (!parsedVersion) { core.warning(`Could not parse "${version}" to semver, defaulting android version code to 1`); - return 1; + return '1'; } // The greatest value Google Plays allows is 2100000000. // Allow for 3 patch digits, 3 minor digits and 3 major digits. @@ -180,7 +172,7 @@ class AndroidVersioning { throw new Error(`Generated versionCode ${versionCode} is dangerously close to the maximum allowed number 2100000000. Consider a different versioning scheme to be able to continue updating your application.`); } core.info(`Using android versionCode ${versionCode}`); - return versionCode; + return versionCode.toString(); } static determineSdkManagerParameters(targetSdkVersion) { const parsedVersion = Number.parseInt(targetSdkVersion.slice(-2), 10); @@ -197,15 +189,6 @@ exports["default"] = AndroidVersioning; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -224,106 +207,102 @@ const cli_1 = __nccwpck_require__(55651); const github_1 = __importDefault(__nccwpck_require__(83654)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); class BuildParameters { - static create() { - return __awaiter(this, void 0, void 0, function* () { - const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidExportType); - const editorVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); - const buildVersion = yield versioning_1.default.determineBuildVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); - const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); - const androidSdkManagerParameters = android_versioning_1.default.determineSdkManagerParameters(input_1.default.androidTargetSdkVersion); - const androidSymbolExportType = input_1.default.androidSymbolType; - if (platform_1.default.isAndroid(input_1.default.targetPlatform)) { - switch (androidSymbolExportType) { - case 'none': - case 'public': - case 'debugging': - break; - default: - throw new Error(`Invalid androidSymbolType: ${input_1.default.androidSymbolType}. Must be one of: none, public, debugging`); - } + static async create() { + const buildFile = this.parseBuildFile(input_1.default.buildName, input_1.default.targetPlatform, input_1.default.androidExportType); + const editorVersion = unity_versioning_1.default.determineUnityVersion(input_1.default.projectPath, input_1.default.unityVersion); + const buildVersion = await versioning_1.default.determineBuildVersion(input_1.default.versioningStrategy, input_1.default.specifiedVersion); + const androidVersionCode = android_versioning_1.default.determineVersionCode(buildVersion, input_1.default.androidVersionCode); + const androidSdkManagerParameters = android_versioning_1.default.determineSdkManagerParameters(input_1.default.androidTargetSdkVersion); + const androidSymbolExportType = input_1.default.androidSymbolType; + if (platform_1.default.isAndroid(input_1.default.targetPlatform)) { + switch (androidSymbolExportType) { + case 'none': + case 'public': + case 'debugging': + break; + default: + throw new Error(`Invalid androidSymbolType: ${input_1.default.androidSymbolType}. Must be one of: none, public, debugging`); } - // Todo - Don't use process.env directly, that's what the input model class is for. - // --- - let unitySerial = ''; - if (input_1.default.unityLicensingServer === '') { - if (!process.env.UNITY_SERIAL && github_1.default.githubInputEnabled) { - // No serial was present, so it is a personal license that we need to convert - if (!process.env.UNITY_LICENSE) { - throw new Error(`Missing Unity License File and no Serial was found. If this + } + let unitySerial = ''; + if (input_1.default.unityLicensingServer === '') { + if (!input_1.default.unitySerial && github_1.default.githubInputEnabled) { + // No serial was present, so it is a personal license that we need to convert + if (!input_1.default.unityLicense) { + throw new Error(`Missing Unity License File and no Serial was found. If this is a personal license, make sure to follow the activation steps and set the UNITY_LICENSE GitHub secret or enter a Unity serial number inside the UNITY_SERIAL GitHub secret.`); - } - unitySerial = this.getSerialFromLicenseFile(process.env.UNITY_LICENSE); - } - else { - unitySerial = process.env.UNITY_SERIAL; } + unitySerial = this.getSerialFromLicenseFile(input_1.default.unityLicense); } - return { - editorVersion, - customImage: input_1.default.customImage, - unitySerial, - unityLicensingServer: input_1.default.unityLicensingServer, - runnerTempPath: process.env.RUNNER_TEMP, - targetPlatform: input_1.default.targetPlatform, - projectPath: input_1.default.projectPath, - buildName: input_1.default.buildName, - buildPath: `${input_1.default.buildsPath}/${input_1.default.targetPlatform}`, - buildFile, - buildMethod: input_1.default.buildMethod, - buildVersion, - androidVersionCode, - androidKeystoreName: input_1.default.androidKeystoreName, - androidKeystoreBase64: input_1.default.androidKeystoreBase64, - androidKeystorePass: input_1.default.androidKeystorePass, - androidKeyaliasName: input_1.default.androidKeyaliasName, - androidKeyaliasPass: input_1.default.androidKeyaliasPass, - androidTargetSdkVersion: input_1.default.androidTargetSdkVersion, - androidSdkManagerParameters, - androidExportType: input_1.default.androidExportType, - androidSymbolType: androidSymbolExportType, - customParameters: input_1.default.customParameters, - sshAgent: input_1.default.sshAgent, - gitPrivateToken: input_1.default.gitPrivateToken || (yield github_cli_1.GithubCliReader.GetGitHubAuthToken()), - chownFilesTo: input_1.default.chownFilesTo, - cloudRunnerCluster: cloud_runner_options_1.default.cloudRunnerCluster, - cloudRunnerBuilderPlatform: cloud_runner_options_1.default.cloudRunnerBuilderPlatform, - awsBaseStackName: cloud_runner_options_1.default.awsBaseStackName, - kubeConfig: cloud_runner_options_1.default.kubeConfig, - cloudRunnerMemory: cloud_runner_options_1.default.cloudRunnerMemory, - cloudRunnerCpu: cloud_runner_options_1.default.cloudRunnerCpu, - kubeVolumeSize: cloud_runner_options_1.default.kubeVolumeSize, - kubeVolume: cloud_runner_options_1.default.kubeVolume, - postBuildSteps: cloud_runner_options_1.default.postBuildSteps, - preBuildSteps: cloud_runner_options_1.default.preBuildSteps, - customJob: cloud_runner_options_1.default.customJob, - runNumber: input_1.default.runNumber, - branch: input_1.default.branch.replace('/head', '') || (yield git_repo_1.GitRepoReader.GetBranch()), - cloudRunnerBranch: cloud_runner_options_1.default.cloudRunnerBranch.split('/').reverse()[0], - cloudRunnerDebug: cloud_runner_options_1.default.cloudRunnerDebug, - githubRepo: input_1.default.githubRepo || (yield git_repo_1.GitRepoReader.GetRemote()) || 'game-ci/unity-builder', - isCliMode: cli_1.Cli.isCliMode, - awsStackName: cloud_runner_options_1.default.awsBaseStackName, - gitSha: input_1.default.gitSha, - logId: nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 9)(), - buildGuid: cloud_runner_guid_1.default.generateGuid(input_1.default.runNumber, input_1.default.targetPlatform), - customJobHooks: cloud_runner_options_1.default.customJobHooks(), - readInputOverrideCommand: cloud_runner_options_1.default.readInputOverrideCommand(), - readInputFromOverrideList: cloud_runner_options_1.default.readInputFromOverrideList(), - kubeStorageClass: cloud_runner_options_1.default.kubeStorageClass, - cacheKey: cloud_runner_options_1.default.cacheKey, - retainWorkspace: cloud_runner_options_1.default.retainWorkspaces, - useSharedLargePackages: cloud_runner_options_1.default.useSharedLargePackages, - useLz4Compression: cloud_runner_options_1.default.useLz4Compression, - maxRetainedWorkspaces: cloud_runner_options_1.default.maxRetainedWorkspaces, - constantGarbageCollection: cloud_runner_options_1.default.constantGarbageCollection, - garbageCollectionMaxAge: cloud_runner_options_1.default.garbageCollectionMaxAge, - githubChecks: cloud_runner_options_1.default.githubChecks, - cacheUnityInstallationOnMac: input_1.default.cacheUnityInstallationOnMac, - unityHubVersionOnMac: input_1.default.unityHubVersionOnMac, - }; - }); + else { + unitySerial = input_1.default.unitySerial; + } + } + return { + editorVersion, + customImage: input_1.default.customImage, + unitySerial, + unityLicensingServer: input_1.default.unityLicensingServer, + runnerTempPath: input_1.default.runnerTempPath, + targetPlatform: input_1.default.targetPlatform, + projectPath: input_1.default.projectPath, + buildName: input_1.default.buildName, + buildPath: `${input_1.default.buildsPath}/${input_1.default.targetPlatform}`, + buildFile, + buildMethod: input_1.default.buildMethod, + buildVersion, + androidVersionCode, + androidKeystoreName: input_1.default.androidKeystoreName, + androidKeystoreBase64: input_1.default.androidKeystoreBase64, + androidKeystorePass: input_1.default.androidKeystorePass, + androidKeyaliasName: input_1.default.androidKeyaliasName, + androidKeyaliasPass: input_1.default.androidKeyaliasPass, + androidTargetSdkVersion: input_1.default.androidTargetSdkVersion, + androidSdkManagerParameters, + androidExportType: input_1.default.androidExportType, + androidSymbolType: androidSymbolExportType, + customParameters: input_1.default.customParameters, + sshAgent: input_1.default.sshAgent, + gitPrivateToken: input_1.default.gitPrivateToken || (await github_cli_1.GithubCliReader.GetGitHubAuthToken()), + chownFilesTo: input_1.default.chownFilesTo, + cloudRunnerCluster: cloud_runner_options_1.default.cloudRunnerCluster, + cloudRunnerBuilderPlatform: cloud_runner_options_1.default.cloudRunnerBuilderPlatform, + awsBaseStackName: cloud_runner_options_1.default.awsBaseStackName, + kubeConfig: cloud_runner_options_1.default.kubeConfig, + cloudRunnerMemory: cloud_runner_options_1.default.cloudRunnerMemory, + cloudRunnerCpu: cloud_runner_options_1.default.cloudRunnerCpu, + kubeVolumeSize: cloud_runner_options_1.default.kubeVolumeSize, + kubeVolume: cloud_runner_options_1.default.kubeVolume, + postBuildSteps: cloud_runner_options_1.default.postBuildSteps, + preBuildSteps: cloud_runner_options_1.default.preBuildSteps, + customJob: cloud_runner_options_1.default.customJob, + runNumber: input_1.default.runNumber, + branch: input_1.default.branch.replace('/head', '') || (await git_repo_1.GitRepoReader.GetBranch()), + cloudRunnerBranch: cloud_runner_options_1.default.cloudRunnerBranch.split('/').reverse()[0], + cloudRunnerDebug: cloud_runner_options_1.default.cloudRunnerDebug, + githubRepo: input_1.default.githubRepo || (await git_repo_1.GitRepoReader.GetRemote()) || 'game-ci/unity-builder', + isCliMode: cli_1.Cli.isCliMode, + awsStackName: cloud_runner_options_1.default.awsBaseStackName, + gitSha: input_1.default.gitSha, + logId: nanoid_1.customAlphabet(cloud_runner_constants_1.default.alphabet, 9)(), + buildGuid: cloud_runner_guid_1.default.generateGuid(input_1.default.runNumber, input_1.default.targetPlatform), + customJobHooks: cloud_runner_options_1.default.customJobHooks(), + readInputOverrideCommand: cloud_runner_options_1.default.readInputOverrideCommand(), + readInputFromOverrideList: cloud_runner_options_1.default.readInputFromOverrideList(), + kubeStorageClass: cloud_runner_options_1.default.kubeStorageClass, + cacheKey: cloud_runner_options_1.default.cacheKey, + retainWorkspace: cloud_runner_options_1.default.retainWorkspaces, + useSharedLargePackages: cloud_runner_options_1.default.useSharedLargePackages, + useLz4Compression: cloud_runner_options_1.default.useLz4Compression, + maxRetainedWorkspaces: cloud_runner_options_1.default.maxRetainedWorkspaces, + constantGarbageCollection: cloud_runner_options_1.default.constantGarbageCollection, + garbageCollectionMaxAge: cloud_runner_options_1.default.garbageCollectionMaxAge, + githubChecks: cloud_runner_options_1.default.githubChecks, + cacheUnityInstallationOnMac: input_1.default.cacheUnityInstallationOnMac, + unityHubVersionOnMac: input_1.default.unityHubVersionOnMac, + }; } static parseBuildFile(filename, platform, androidExportType) { if (platform_1.default.isWindows(platform)) { @@ -389,12 +368,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const action_1 = __importDefault(__nccwpck_require__(89088)); const project_1 = __importDefault(__nccwpck_require__(88666)); class Cache { static verify() { - if (!fs_1.default.existsSync(project_1.default.libraryFolder)) { + if (!node_fs_1.default.existsSync(project_1.default.libraryFolder)) { this.notifyAboutCachingPossibility(); } } @@ -491,15 +470,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -556,33 +526,32 @@ class Cli { Cli.options = program.opts(); return Cli.isCliMode; } - static RunCli() { - return __awaiter(this, void 0, void 0, function* () { - github_1.default.githubInputEnabled = false; - if (Cli.options['populateOverride'] === `true`) { - yield cloud_runner_query_override_1.default.PopulateQueryOverrideInput(); - } - if (Cli.options['logInput']) { - Cli.logInput(); - } - const results = cli_functions_repository_1.CliFunctionsRepository.GetCliFunctions(Cli.options.mode); - cloud_runner_logger_1.default.log(`Entrypoint: ${results.key}`); - Cli.options.versioning = 'None'; - const buildParameter = task_parameter_serializer_1.TaskParameterSerializer.readBuildParameterFromEnvironment(); - cloud_runner_logger_1.default.log(`Build Params: + static async RunCli() { + github_1.default.githubInputEnabled = false; + if (Cli.options['populateOverride'] === `true`) { + await cloud_runner_query_override_1.default.PopulateQueryOverrideInput(); + } + if (Cli.options['logInput']) { + Cli.logInput(); + } + const results = cli_functions_repository_1.CliFunctionsRepository.GetCliFunctions(Cli.options?.mode); + cloud_runner_logger_1.default.log(`Entrypoint: ${results.key}`); + Cli.options.versioning = 'None'; + const buildParameter = task_parameter_serializer_1.TaskParameterSerializer.readBuildParameterFromEnvironment(); + cloud_runner_logger_1.default.log(`Build Params: ${JSON.stringify(buildParameter, undefined, 4)} `); - __1.CloudRunner.buildParameters = buildParameter; - __1.CloudRunner.lockedWorkspace = process.env.LOCKED_WORKSPACE; - return yield results.target[results.propertyKey](Cli.options); - }); + __1.CloudRunner.buildParameters = buildParameter; + __1.CloudRunner.lockedWorkspace = process.env.LOCKED_WORKSPACE; + return await results.target[results.propertyKey](Cli.options); } static logInput() { core.info(`\n`); core.info(`INPUT:`); const properties = cloud_runner_options_reader_1.default.GetProperties(); for (const element of properties) { - if (__1.Input[element] !== undefined && + if (element in __1.Input && + __1.Input[element] !== undefined && __1.Input[element] !== '' && typeof __1.Input[element] !== `function` && element !== 'length' && @@ -593,79 +562,63 @@ class Cli { } core.info(`\n`); } - static CLIBuild() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - const baseImage = new __1.ImageTag(buildParameter); - return yield __1.CloudRunner.run(buildParameter, baseImage.toString()); - }); + static async CLIBuild() { + const buildParameter = await __1.BuildParameters.create(); + const baseImage = new __1.ImageTag(buildParameter); + return await __1.CloudRunner.run(buildParameter, baseImage.toString()); } - static asyncronousWorkflow() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - const baseImage = new __1.ImageTag(buildParameter); - return yield __1.CloudRunner.run(buildParameter, baseImage.toString()); - }); + static async asyncronousWorkflow() { + const buildParameter = await __1.BuildParameters.create(); + const baseImage = new __1.ImageTag(buildParameter); + return await __1.CloudRunner.run(buildParameter, baseImage.toString()); } - static checksUpdate() { - return __awaiter(this, void 0, void 0, function* () { - const input = JSON.parse(process.env.CHECKS_UPDATE || ``); - core.info(`Checks Update ${process.env.CHECKS_UPDATE}`); - if (input.mode === `create`) { - throw new Error(`Not supported: only use update`); - } - else if (input.mode === `update`) { - yield github_1.default.updateGitHubCheckRequest(input.data); - } - }); + static async checksUpdate() { + const input = JSON.parse(process.env.CHECKS_UPDATE || ``); + core.info(`Checks Update ${process.env.CHECKS_UPDATE}`); + if (input.mode === `create`) { + throw new Error(`Not supported: only use update`); + } + else if (input.mode === `update`) { + await github_1.default.updateGitHubCheckRequest(input.data); + } } - static GarbageCollect() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - yield __1.CloudRunner.setup(buildParameter); - return yield __1.CloudRunner.Provider.garbageCollect(``, false, 0, false, false); - }); + static async GarbageCollect() { + const buildParameter = await __1.BuildParameters.create(); + await __1.CloudRunner.setup(buildParameter); + return await __1.CloudRunner.Provider.garbageCollect(``, false, 0, false, false); } - static ListResources() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - yield __1.CloudRunner.setup(buildParameter); - const result = yield __1.CloudRunner.Provider.listResources(); - cloud_runner_logger_1.default.log(JSON.stringify(result, undefined, 4)); - return result.map((x) => x.Name); - }); + static async ListResources() { + const buildParameter = await __1.BuildParameters.create(); + await __1.CloudRunner.setup(buildParameter); + const result = await __1.CloudRunner.Provider.listResources(); + cloud_runner_logger_1.default.log(JSON.stringify(result, undefined, 4)); + return result.map((x) => x.Name); } - static ListWorfklow() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - yield __1.CloudRunner.setup(buildParameter); - return (yield __1.CloudRunner.Provider.listWorkflow()).map((x) => x.Name); - }); + static async ListWorfklow() { + const buildParameter = await __1.BuildParameters.create(); + await __1.CloudRunner.setup(buildParameter); + return (await __1.CloudRunner.Provider.listWorkflow()).map((x) => x.Name); } - static Watch() { - return __awaiter(this, void 0, void 0, function* () { - const buildParameter = yield __1.BuildParameters.create(); - yield __1.CloudRunner.setup(buildParameter); - return yield __1.CloudRunner.Provider.watchWorkflow(); - }); + static async Watch() { + const buildParameter = await __1.BuildParameters.create(); + await __1.CloudRunner.setup(buildParameter); + return await __1.CloudRunner.Provider.watchWorkflow(); } - static PostCLIBuild() { - return __awaiter(this, void 0, void 0, function* () { - core.info(`Running POST build tasks`); - yield caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(`${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull}/Library`), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute), `lib-${__1.CloudRunner.buildParameters.buildGuid}`); - yield caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(`${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull}/build`), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.projectBuildFolderAbsolute), `build-${__1.CloudRunner.buildParameters.buildGuid}`); - if (!__1.CloudRunner.buildParameters.retainWorkspace) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}`); - } - yield remote_client_1.RemoteClient.runCustomHookFiles(`after-build`); - const parameters = yield __1.BuildParameters.create(); - __1.CloudRunner.setup(parameters); - if (parameters.constantGarbageCollection) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`find /${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder)}/ -name '*.*' -mmin +${parameters.garbageCollectionMaxAge * 60} -delete`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`find ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForAllFull)} -name '*.*' -mmin +${parameters.garbageCollectionMaxAge * 60} -delete`); - } - return new Promise((result) => result(``)); - }); + static async PostCLIBuild() { + core.info(`Running POST build tasks`); + await caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(`${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull}/Library`), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute), `lib-${__1.CloudRunner.buildParameters.buildGuid}`); + await caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(`${cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull}/build`), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.projectBuildFolderAbsolute), `build-${__1.CloudRunner.buildParameters.buildGuid}`); + if (!__1.CloudRunner.buildParameters.retainWorkspace) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}`); + } + await remote_client_1.RemoteClient.runCustomHookFiles(`after-build`); + const parameters = await __1.BuildParameters.create(); + __1.CloudRunner.setup(parameters); + if (parameters.constantGarbageCollection) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`find /${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder)}/ -name '*.*' -mmin +${parameters.garbageCollectionMaxAge * 60} -delete`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`find ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForAllFull)} -name '*.*' -mmin +${parameters.garbageCollectionMaxAge * 60} -delete`); + } + return new Promise((result) => result(``)); } } __decorate([ @@ -705,6 +658,25 @@ exports.Cli = Cli; "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -712,7 +684,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); const cli_1 = __nccwpck_require__(55651); const cloud_runner_query_override_1 = __importDefault(__nccwpck_require__(31011)); const github_1 = __importDefault(__nccwpck_require__(83654)); -const core = __nccwpck_require__(42186); +const core = __importStar(__nccwpck_require__(42186)); class CloudRunnerOptions { // ### ### ### // Input Handling @@ -738,7 +710,6 @@ class CloudRunnerOptions { if (alternativeQuery !== query && process.env[alternativeQuery] !== undefined) { return process.env[alternativeQuery]; } - return; } static ToEnvVarFormat(input) { if (input.toUpperCase() === input) { @@ -760,13 +731,13 @@ class CloudRunnerOptions { // GitHub parameters // ### ### ### static get githubChecks() { - return CloudRunnerOptions.getInput('githubChecks') || false; + return CloudRunnerOptions.getInput('githubChecks') === 'true' || false; } static get githubOwner() { - return CloudRunnerOptions.getInput('githubOwner') || CloudRunnerOptions.githubRepo.split(`/`)[0] || false; + return CloudRunnerOptions.getInput('githubOwner') || CloudRunnerOptions.githubRepo?.split(`/`)[0] || ''; } static get githubRepoName() { - return CloudRunnerOptions.getInput('githubRepoName') || CloudRunnerOptions.githubRepo.split(`/`)[1] || false; + return CloudRunnerOptions.getInput('githubRepoName') || CloudRunnerOptions.githubRepo?.split(`/`)[1] || ''; } // ### ### ### // Git syncronization parameters @@ -828,12 +799,10 @@ class CloudRunnerOptions { // Custom commands from files parameters // ### ### ### static get customStepFiles() { - var _a; - return ((_a = CloudRunnerOptions.getInput('customStepFiles')) === null || _a === void 0 ? void 0 : _a.split(`,`)) || []; + return CloudRunnerOptions.getInput('customStepFiles')?.split(`,`) || []; } static get customHookFiles() { - var _a; - return ((_a = CloudRunnerOptions.getInput('customHookFiles')) === null || _a === void 0 ? void 0 : _a.split(`,`)) || []; + return CloudRunnerOptions.getInput('customHookFiles')?.split(`,`) || []; } // ### ### ### // Custom commands from yaml parameters @@ -894,7 +863,9 @@ class CloudRunnerOptions { // Utility Parameters // ### ### ### static get cloudRunnerDebug() { - return CloudRunnerOptions.getInput(`cloudRunnerTests`) || CloudRunnerOptions.getInput(`cloudRunnerDebug`) || false; + return (CloudRunnerOptions.getInput(`cloudRunnerTests`) === 'true' || + CloudRunnerOptions.getInput(`cloudRunnerDebug`) === 'true' || + false); } static get cloudRunnerDebugTree() { return CloudRunnerOptions.getInput(`cloudRunnerDebugTree`) || false; @@ -906,7 +877,7 @@ class CloudRunnerOptions { if (CloudRunnerOptions.asyncCloudRunner) { return false; } - return CloudRunnerOptions.getInput(`watchToEnd`) || true; + return CloudRunnerOptions.getInput(`watchToEnd`) === 'true' || true; } static get asyncCloudRunner() { return (CloudRunnerOptions.getInput('asyncCloudRunner') || `false`) === `true` || false; @@ -927,7 +898,7 @@ class CloudRunnerOptions { // Retained Workspace // ### ### ### static get retainWorkspaces() { - return CloudRunnerOptions.getInput(`retainWorkspaces`) || false; + return CloudRunnerOptions.getInput(`retainWorkspaces`) === 'true' || false; } static get maxRetainedWorkspaces() { return Number(CloudRunnerOptions.getInput(`maxRetainedWorkspaces`)) || 3; @@ -936,7 +907,7 @@ class CloudRunnerOptions { // Garbage Collection // ### ### ### static get constantGarbageCollection() { - return CloudRunnerOptions.getInput(`constantGarbageCollection`) || true; + return CloudRunnerOptions.getInput(`constantGarbageCollection`) === 'true' || true; } static get garbageCollectionMaxAge() { return Number(CloudRunnerOptions.getInput(`garbageCollectionMaxAge`)) || 24; @@ -1005,15 +976,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -1074,58 +1036,56 @@ class CloudRunner { break; } } - static run(buildParameters, baseImage) { - return __awaiter(this, void 0, void 0, function* () { - CloudRunner.setup(buildParameters); - try { - CloudRunner.githubCheckId = yield github_1.default.createGitHubCheck(CloudRunner.buildParameters.buildGuid); - if (buildParameters.retainWorkspace) { - CloudRunner.lockedWorkspace = `${CloudRunner.retainedWorkspacePrefix}-${CloudRunner.buildParameters.buildGuid}`; - const result = yield shared_workspace_locking_1.default.GetOrCreateLockedWorkspace(CloudRunner.lockedWorkspace, CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters); - if (result) { - cloud_runner_logger_1.default.logLine(`Using retained workspace ${CloudRunner.lockedWorkspace}`); - CloudRunner.cloudRunnerEnvironmentVariables = [ - ...CloudRunner.cloudRunnerEnvironmentVariables, - { name: `LOCKED_WORKSPACE`, value: CloudRunner.lockedWorkspace }, - ]; - } - else { - cloud_runner_logger_1.default.log(`Max retained workspaces reached ${buildParameters.maxRetainedWorkspaces}`); - buildParameters.retainWorkspace = false; - CloudRunner.lockedWorkspace = undefined; - } + static async run(buildParameters, baseImage) { + CloudRunner.setup(buildParameters); + try { + CloudRunner.githubCheckId = await github_1.default.createGitHubCheck(CloudRunner.buildParameters.buildGuid); + if (buildParameters.retainWorkspace) { + CloudRunner.lockedWorkspace = `${CloudRunner.retainedWorkspacePrefix}-${CloudRunner.buildParameters.buildGuid}`; + const result = await shared_workspace_locking_1.default.GetOrCreateLockedWorkspace(CloudRunner.lockedWorkspace, CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters); + if (result) { + cloud_runner_logger_1.default.logLine(`Using retained workspace ${CloudRunner.lockedWorkspace}`); + CloudRunner.cloudRunnerEnvironmentVariables = [ + ...CloudRunner.cloudRunnerEnvironmentVariables, + { name: `LOCKED_WORKSPACE`, value: CloudRunner.lockedWorkspace }, + ]; } - if (!CloudRunner.buildParameters.isCliMode) - core.startGroup('Setup shared cloud runner resources'); - yield CloudRunner.Provider.setupWorkflow(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); - if (!CloudRunner.buildParameters.isCliMode) - core.endGroup(); - yield github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters.buildGuid); - const output = yield new workflow_composition_root_1.WorkflowCompositionRoot().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, CloudRunner.cloudRunnerEnvironmentVariables, CloudRunner.defaultSecrets)); - if (!CloudRunner.buildParameters.isCliMode) - core.startGroup('Cleanup shared cloud runner resources'); - yield CloudRunner.Provider.cleanupWorkflow(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); - cloud_runner_logger_1.default.log(`Cleanup complete`); - if (!CloudRunner.buildParameters.isCliMode) - core.endGroup(); - yield github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, `success`, `success`, `completed`); - if (CloudRunner.buildParameters.retainWorkspace) { - yield shared_workspace_locking_1.default.ReleaseWorkspace(CloudRunner.lockedWorkspace || ``, CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters); + else { + cloud_runner_logger_1.default.log(`Max retained workspaces reached ${buildParameters.maxRetainedWorkspaces}`); + buildParameters.retainWorkspace = false; CloudRunner.lockedWorkspace = undefined; } - if (buildParameters.constantGarbageCollection) { - CloudRunner.Provider.garbageCollect(``, true, buildParameters.garbageCollectionMaxAge, true, true); - } - return output; } - catch (error) { - yield github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, error, `failure`, `completed`); - if (!CloudRunner.buildParameters.isCliMode) - core.endGroup(); - yield cloud_runner_error_1.CloudRunnerError.handleException(error, CloudRunner.buildParameters, CloudRunner.defaultSecrets); - throw error; + if (!CloudRunner.buildParameters.isCliMode) + core.startGroup('Setup shared cloud runner resources'); + await CloudRunner.Provider.setupWorkflow(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); + if (!CloudRunner.buildParameters.isCliMode) + core.endGroup(); + await github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters.buildGuid); + const output = await new workflow_composition_root_1.WorkflowCompositionRoot().run(new cloud_runner_step_state_1.CloudRunnerStepState(baseImage, CloudRunner.cloudRunnerEnvironmentVariables, CloudRunner.defaultSecrets)); + if (!CloudRunner.buildParameters.isCliMode) + core.startGroup('Cleanup shared cloud runner resources'); + await CloudRunner.Provider.cleanupWorkflow(CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters, CloudRunner.buildParameters.branch, CloudRunner.defaultSecrets); + cloud_runner_logger_1.default.log(`Cleanup complete`); + if (!CloudRunner.buildParameters.isCliMode) + core.endGroup(); + await github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, `success`, `success`, `completed`); + if (CloudRunner.buildParameters.retainWorkspace) { + await shared_workspace_locking_1.default.ReleaseWorkspace(CloudRunner.lockedWorkspace || ``, CloudRunner.buildParameters.buildGuid, CloudRunner.buildParameters); + CloudRunner.lockedWorkspace = undefined; } - }); + if (buildParameters.constantGarbageCollection) { + CloudRunner.Provider.garbageCollect(``, true, buildParameters.garbageCollectionMaxAge, true, true); + } + return output; + } + catch (error) { + await github_1.default.updateGitHubCheck(CloudRunner.buildParameters.buildGuid, error, `failure`, `completed`); + if (!CloudRunner.buildParameters.isCliMode) + core.endGroup(); + await cloud_runner_error_1.CloudRunnerError.handleException(error, CloudRunner.buildParameters, CloudRunner.defaultSecrets); + throw error; + } } } CloudRunner.retainedWorkspacePrefix = `retained-workspace`; @@ -1158,15 +1118,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -1176,14 +1127,12 @@ const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const core = __importStar(__nccwpck_require__(42186)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class CloudRunnerError { - static handleException(error, buildParameters, secrets) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.error(JSON.stringify(error, undefined, 4)); - core.setFailed('Cloud Runner failed'); - if (cloud_runner_1.default.Provider !== undefined) { - yield cloud_runner_1.default.Provider.cleanupWorkflow(buildParameters.buildGuid, buildParameters, buildParameters.branch, secrets); - } - }); + static async handleException(error, buildParameters, secrets) { + cloud_runner_logger_1.default.error(JSON.stringify(error, undefined, 4)); + core.setFailed('Cloud Runner failed'); + if (cloud_runner_1.default.Provider !== undefined) { + await cloud_runner_1.default.Provider.cleanupWorkflow(buildParameters.buildGuid, buildParameters, buildParameters.branch, secrets); + } } } exports.CloudRunnerError = CloudRunnerError; @@ -1215,15 +1164,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -1232,102 +1172,99 @@ exports.AWSBaseStack = void 0; const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const core = __importStar(__nccwpck_require__(42186)); const base_stack_formation_1 = __nccwpck_require__(29643); -const crypto = __nccwpck_require__(6113); +const node_crypto_1 = __importDefault(__nccwpck_require__(6005)); class AWSBaseStack { constructor(baseStackName) { this.baseStackName = baseStackName; } - setupBaseStack(CF) { - var _a, _b, _c, _d, _e; - return __awaiter(this, void 0, void 0, function* () { - const baseStackName = this.baseStackName; - const baseStack = base_stack_formation_1.BaseStackFormation.formation; - // Cloud Formation Input - const describeStackInput = { - StackName: baseStackName, - }; - const parametersWithoutHash = [ - { ParameterKey: 'EnvironmentName', ParameterValue: baseStackName }, - ]; - const parametersHash = crypto - .createHash('md5') - .update(baseStack + JSON.stringify(parametersWithoutHash)) - .digest('hex'); - const parameters = [ - ...parametersWithoutHash, - ...[{ ParameterKey: 'Version', ParameterValue: parametersHash }], - ]; - const updateInput = { - StackName: baseStackName, - TemplateBody: baseStack, - Parameters: parameters, - Capabilities: ['CAPABILITY_IAM'], - }; - const createStackInput = { - StackName: baseStackName, - TemplateBody: baseStack, - Parameters: parameters, - Capabilities: ['CAPABILITY_IAM'], - }; - const stacks = yield CF.listStacks({ - StackStatusFilter: ['UPDATE_COMPLETE', 'CREATE_COMPLETE', 'ROLLBACK_COMPLETE'], - }).promise(); - const stackNames = ((_a = stacks.StackSummaries) === null || _a === void 0 ? void 0 : _a.map((x) => x.StackName)) || []; - const stackExists = stackNames.includes(baseStackName) || false; - const describeStack = () => __awaiter(this, void 0, void 0, function* () { - return yield CF.describeStacks(describeStackInput).promise(); - }); - try { - if (!stackExists) { - cloud_runner_logger_1.default.log(`${baseStackName} stack does not exist (${JSON.stringify(stackNames)})`); - yield CF.createStack(createStackInput).promise(); - cloud_runner_logger_1.default.log(`created stack (version: ${parametersHash})`); + async setupBaseStack(CF) { + const baseStackName = this.baseStackName; + const baseStack = base_stack_formation_1.BaseStackFormation.formation; + // Cloud Formation Input + const describeStackInput = { + StackName: baseStackName, + }; + const parametersWithoutHash = [ + { ParameterKey: 'EnvironmentName', ParameterValue: baseStackName }, + ]; + const parametersHash = node_crypto_1.default + .createHash('md5') + .update(baseStack + JSON.stringify(parametersWithoutHash)) + .digest('hex'); + const parameters = [ + ...parametersWithoutHash, + ...[{ ParameterKey: 'Version', ParameterValue: parametersHash }], + ]; + const updateInput = { + StackName: baseStackName, + TemplateBody: baseStack, + Parameters: parameters, + Capabilities: ['CAPABILITY_IAM'], + }; + const createStackInput = { + StackName: baseStackName, + TemplateBody: baseStack, + Parameters: parameters, + Capabilities: ['CAPABILITY_IAM'], + }; + const stacks = await CF.listStacks({ + StackStatusFilter: ['UPDATE_COMPLETE', 'CREATE_COMPLETE', 'ROLLBACK_COMPLETE'], + }).promise(); + const stackNames = stacks.StackSummaries?.map((x) => x.StackName) || []; + const stackExists = stackNames.includes(baseStackName) || false; + const describeStack = async () => { + return await CF.describeStacks(describeStackInput).promise(); + }; + try { + if (!stackExists) { + cloud_runner_logger_1.default.log(`${baseStackName} stack does not exist (${JSON.stringify(stackNames)})`); + await CF.createStack(createStackInput).promise(); + cloud_runner_logger_1.default.log(`created stack (version: ${parametersHash})`); + } + const CFState = await describeStack(); + let stack = CFState.Stacks?.[0]; + if (!stack) { + throw new Error(`Base stack doesn't exist, even after creation, stackExists check: ${stackExists}`); + } + const stackVersion = stack.Parameters?.find((x) => x.ParameterKey === 'Version')?.ParameterValue; + if (stack.StackStatus === 'CREATE_IN_PROGRESS') { + await CF.waitFor('stackCreateComplete', describeStackInput).promise(); + } + if (stackExists) { + cloud_runner_logger_1.default.log(`Base stack exists (version: ${stackVersion}, local version: ${parametersHash})`); + if (parametersHash !== stackVersion) { + cloud_runner_logger_1.default.log(`Attempting update of base stack`); + try { + await CF.updateStack(updateInput).promise(); + } + catch (error) { + if (error['message'].includes('No updates are to be performed')) { + cloud_runner_logger_1.default.log(`No updates are to be performed`); + } + else { + cloud_runner_logger_1.default.log(`Update Failed (Stack name: ${baseStackName})`); + cloud_runner_logger_1.default.log(error['message']); + } + cloud_runner_logger_1.default.log(`Continuing...`); + } } - const CFState = yield describeStack(); - let stack = (_b = CFState.Stacks) === null || _b === void 0 ? void 0 : _b[0]; + else { + cloud_runner_logger_1.default.log(`No update required`); + } + stack = (await describeStack()).Stacks?.[0]; if (!stack) { - throw new Error(`Base stack doesn't exist, even after creation, stackExists check: ${stackExists}`); + throw new Error(`Base stack doesn't exist, even after updating and creation, stackExists check: ${stackExists}`); } - const stackVersion = (_d = (_c = stack.Parameters) === null || _c === void 0 ? void 0 : _c.find((x) => x.ParameterKey === 'Version')) === null || _d === void 0 ? void 0 : _d.ParameterValue; - if (stack.StackStatus === 'CREATE_IN_PROGRESS') { - yield CF.waitFor('stackCreateComplete', describeStackInput).promise(); + if (stack.StackStatus === 'UPDATE_IN_PROGRESS') { + await CF.waitFor('stackUpdateComplete', describeStackInput).promise(); } - if (stackExists) { - cloud_runner_logger_1.default.log(`Base stack exists (version: ${stackVersion}, local version: ${parametersHash})`); - if (parametersHash !== stackVersion) { - cloud_runner_logger_1.default.log(`Attempting update of base stack`); - try { - yield CF.updateStack(updateInput).promise(); - } - catch (error) { - if (error['message'].includes('No updates are to be performed')) { - cloud_runner_logger_1.default.log(`No updates are to be performed`); - } - else { - cloud_runner_logger_1.default.log(`Update Failed (Stack name: ${baseStackName})`); - cloud_runner_logger_1.default.log(error['message']); - } - cloud_runner_logger_1.default.log(`Continuing...`); - } - } - else { - cloud_runner_logger_1.default.log(`No update required`); - } - stack = (_e = (yield describeStack()).Stacks) === null || _e === void 0 ? void 0 : _e[0]; - if (!stack) { - throw new Error(`Base stack doesn't exist, even after updating and creation, stackExists check: ${stackExists}`); - } - if (stack.StackStatus === 'UPDATE_IN_PROGRESS') { - yield CF.waitFor('stackUpdateComplete', describeStackInput).promise(); - } - } - cloud_runner_logger_1.default.log('base stack is now ready'); } - catch (error) { - core.error(JSON.stringify(yield describeStack(), undefined, 4)); - throw error; - } - }); + cloud_runner_logger_1.default.log('base stack is now ready'); + } + catch (error) { + core.error(JSON.stringify(await describeStack(), undefined, 4)); + throw error; + } } } exports.AWSBaseStack = AWSBaseStack; @@ -1404,15 +1341,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -1422,16 +1350,14 @@ const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const core = __importStar(__nccwpck_require__(42186)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class AWSError { - static handleStackCreationFailure(error, CF, taskDefStackName) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('aws error: '); - core.error(JSON.stringify(error, undefined, 4)); - if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { - cloud_runner_logger_1.default.log('Getting events and resources for task stack'); - const events = (yield CF.describeStackEvents({ StackName: taskDefStackName }).promise()).StackEvents; - cloud_runner_logger_1.default.log(JSON.stringify(events, undefined, 4)); - } - }); + static async handleStackCreationFailure(error, CF, taskDefStackName) { + cloud_runner_logger_1.default.log('aws error: '); + core.error(JSON.stringify(error, undefined, 4)); + if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { + cloud_runner_logger_1.default.log('Getting events and resources for task stack'); + const events = (await CF.describeStackEvents({ StackName: taskDefStackName }).promise()).StackEvents; + cloud_runner_logger_1.default.log(JSON.stringify(events, undefined, 4)); + } } } exports.AWSError = AWSError; @@ -1444,15 +1370,6 @@ exports.AWSError = AWSError; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -1469,154 +1386,152 @@ class AWSJobStack { constructor(baseStackName) { this.baseStackName = baseStackName; } - setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets) { - return __awaiter(this, void 0, void 0, function* () { - const taskDefStackName = `${this.baseStackName}-${buildGuid}`; - let taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.readTaskCloudFormationTemplate(); - const cpu = cloud_runner_1.default.buildParameters.cloudRunnerCpu || '1024'; - const memory = cloud_runner_1.default.buildParameters.cloudRunnerMemory || '3072'; - taskDefCloudFormation = taskDefCloudFormation.replace(`ContainerCpu: + async setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets) { + const taskDefStackName = `${this.baseStackName}-${buildGuid}`; + let taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.readTaskCloudFormationTemplate(); + const cpu = cloud_runner_1.default.buildParameters.cloudRunnerCpu || '1024'; + const memory = cloud_runner_1.default.buildParameters.cloudRunnerMemory || '3072'; + taskDefCloudFormation = taskDefCloudFormation.replace(`ContainerCpu: Default: 1024`, `ContainerCpu: Default: ${Number.parseInt(cpu)}`); - taskDefCloudFormation = taskDefCloudFormation.replace(`ContainerMemory: + taskDefCloudFormation = taskDefCloudFormation.replace(`ContainerMemory: Default: 2048`, `ContainerMemory: Default: ${Number.parseInt(memory)}`); - if (cloud_runner_options_1.default.watchCloudRunnerToEnd) { - taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, '# template resources logstream', task_definition_formation_1.TaskDefinitionFormation.streamLogs); + if (cloud_runner_options_1.default.watchCloudRunnerToEnd) { + taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, '# template resources logstream', task_definition_formation_1.TaskDefinitionFormation.streamLogs); + } + for (const secret of secrets) { + secret.ParameterKey = `${buildGuid.replace(/[^\dA-Za-z]/g, '')}${secret.ParameterKey.replace(/[^\dA-Za-z]/g, '')}`; + if (typeof secret.ParameterValue == 'number') { + secret.ParameterValue = `${secret.ParameterValue}`; } - for (const secret of secrets) { - secret.ParameterKey = `${buildGuid.replace(/[^\dA-Za-z]/g, '')}${secret.ParameterKey.replace(/[^\dA-Za-z]/g, '')}`; - if (typeof secret.ParameterValue == 'number') { - secret.ParameterValue = `${secret.ParameterValue}`; - } - if (!secret.ParameterValue || secret.ParameterValue === '') { - secrets = secrets.filter((x) => x !== secret); - continue; - } - taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, 'p1 - input', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getParameterTemplate(secret.ParameterKey)); - taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, '# template resources secrets', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getSecretTemplate(`${secret.ParameterKey}`)); - taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, 'p3 - container def', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getSecretDefinitionTemplate(secret.EnvironmentVariable, secret.ParameterKey)); + if (!secret.ParameterValue || secret.ParameterValue === '') { + secrets = secrets.filter((x) => x !== secret); + continue; } - const secretsMappedToCloudFormationParameters = secrets.map((x) => { - return { ParameterKey: x.ParameterKey.replace(/[^\dA-Za-z]/g, ''), ParameterValue: x.ParameterValue }; - }); - const logGroupName = `${this.baseStackName}/${taskDefStackName}`; - const parameters = [ + taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, 'p1 - input', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getParameterTemplate(secret.ParameterKey)); + taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, '# template resources secrets', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getSecretTemplate(`${secret.ParameterKey}`)); + taskDefCloudFormation = aws_cloud_formation_templates_1.AWSCloudFormationTemplates.insertAtTemplate(taskDefCloudFormation, 'p3 - container def', aws_cloud_formation_templates_1.AWSCloudFormationTemplates.getSecretDefinitionTemplate(secret.EnvironmentVariable, secret.ParameterKey)); + } + const secretsMappedToCloudFormationParameters = secrets.map((x) => { + return { ParameterKey: x.ParameterKey.replace(/[^\dA-Za-z]/g, ''), ParameterValue: x.ParameterValue }; + }); + const logGroupName = `${this.baseStackName}/${taskDefStackName}`; + const parameters = [ + { + ParameterKey: 'EnvironmentName', + ParameterValue: this.baseStackName, + }, + { + ParameterKey: 'ImageUrl', + ParameterValue: image, + }, + { + ParameterKey: 'ServiceName', + ParameterValue: taskDefStackName, + }, + { + ParameterKey: 'LogGroupName', + ParameterValue: logGroupName, + }, + { + ParameterKey: 'Command', + ParameterValue: 'echo "this template should be overwritten when running a task"', + }, + { + ParameterKey: 'EntryPoint', + ParameterValue: entrypoint.join(','), + }, + { + ParameterKey: 'WorkingDirectory', + ParameterValue: workingdir, + }, + { + ParameterKey: 'EFSMountDirectory', + ParameterValue: mountdir, + }, + ...secretsMappedToCloudFormationParameters, + ]; + cloud_runner_logger_1.default.log(`Starting AWS job with memory: ${cloud_runner_1.default.buildParameters.cloudRunnerMemory} cpu: ${cloud_runner_1.default.buildParameters.cloudRunnerCpu}`); + let previousStackExists = true; + while (previousStackExists) { + previousStackExists = false; + const stacks = await CF.listStacks().promise(); + if (!stacks.StackSummaries) { + throw new Error('Faild to get stacks'); + } + for (let index = 0; index < stacks.StackSummaries.length; index++) { + const element = stacks.StackSummaries[index]; + if (element.StackName === taskDefStackName && element.StackStatus !== 'DELETE_COMPLETE') { + previousStackExists = true; + cloud_runner_logger_1.default.log(`Previous stack still exists: ${JSON.stringify(element)}`); + await new Promise((promise) => setTimeout(promise, 5000)); + } + } + } + const createStackInput = { + StackName: taskDefStackName, + TemplateBody: taskDefCloudFormation, + Capabilities: ['CAPABILITY_IAM'], + Parameters: parameters, + }; + try { + cloud_runner_logger_1.default.log(`Creating job aws formation ${taskDefStackName}`); + await CF.createStack(createStackInput).promise(); + await CF.waitFor('stackCreateComplete', { StackName: taskDefStackName }).promise(); + } + catch (error) { + await aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); + throw error; + } + const createCleanupStackInput = { + StackName: `${taskDefStackName}-cleanup`, + TemplateBody: cleanup_cron_formation_1.CleanupCronFormation.formation, + Capabilities: ['CAPABILITY_IAM'], + Parameters: [ + { + ParameterKey: 'StackName', + ParameterValue: taskDefStackName, + }, + { + ParameterKey: 'DeleteStackName', + ParameterValue: `${taskDefStackName}-cleanup`, + }, + { + ParameterKey: 'TTL', + ParameterValue: `1080`, + }, + { + ParameterKey: 'BUILDGUID', + ParameterValue: cloud_runner_1.default.buildParameters.buildGuid, + }, { ParameterKey: 'EnvironmentName', ParameterValue: this.baseStackName, }, - { - ParameterKey: 'ImageUrl', - ParameterValue: image, - }, - { - ParameterKey: 'ServiceName', - ParameterValue: taskDefStackName, - }, - { - ParameterKey: 'LogGroupName', - ParameterValue: logGroupName, - }, - { - ParameterKey: 'Command', - ParameterValue: 'echo "this template should be overwritten when running a task"', - }, - { - ParameterKey: 'EntryPoint', - ParameterValue: entrypoint.join(','), - }, - { - ParameterKey: 'WorkingDirectory', - ParameterValue: workingdir, - }, - { - ParameterKey: 'EFSMountDirectory', - ParameterValue: mountdir, - }, - ...secretsMappedToCloudFormationParameters, - ]; - cloud_runner_logger_1.default.log(`Starting AWS job with memory: ${cloud_runner_1.default.buildParameters.cloudRunnerMemory} cpu: ${cloud_runner_1.default.buildParameters.cloudRunnerCpu}`); - let previousStackExists = true; - while (previousStackExists) { - previousStackExists = false; - const stacks = yield CF.listStacks().promise(); - if (!stacks.StackSummaries) { - throw new Error('Faild to get stacks'); - } - for (let index = 0; index < stacks.StackSummaries.length; index++) { - const element = stacks.StackSummaries[index]; - if (element.StackName === taskDefStackName && element.StackStatus !== 'DELETE_COMPLETE') { - previousStackExists = true; - cloud_runner_logger_1.default.log(`Previous stack still exists: ${JSON.stringify(element)}`); - yield new Promise((promise) => setTimeout(promise, 5000)); - } - } - } - const createStackInput = { - StackName: taskDefStackName, - TemplateBody: taskDefCloudFormation, - Capabilities: ['CAPABILITY_IAM'], - Parameters: parameters, - }; + ], + }; + if (cloud_runner_options_1.default.useCleanupCron) { try { - cloud_runner_logger_1.default.log(`Creating job aws formation ${taskDefStackName}`); - yield CF.createStack(createStackInput).promise(); - yield CF.waitFor('stackCreateComplete', { StackName: taskDefStackName }).promise(); + cloud_runner_logger_1.default.log(`Creating job cleanup formation`); + CF.createStack(createCleanupStackInput).promise(); + // await CF.waitFor('stackCreateComplete', { StackName: createCleanupStackInput.StackName }).promise(); } catch (error) { - yield aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); + await aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); throw error; } - const createCleanupStackInput = { - StackName: `${taskDefStackName}-cleanup`, - TemplateBody: cleanup_cron_formation_1.CleanupCronFormation.formation, - Capabilities: ['CAPABILITY_IAM'], - Parameters: [ - { - ParameterKey: 'StackName', - ParameterValue: taskDefStackName, - }, - { - ParameterKey: 'DeleteStackName', - ParameterValue: `${taskDefStackName}-cleanup`, - }, - { - ParameterKey: 'TTL', - ParameterValue: `1080`, - }, - { - ParameterKey: 'BUILDGUID', - ParameterValue: cloud_runner_1.default.buildParameters.buildGuid, - }, - { - ParameterKey: 'EnvironmentName', - ParameterValue: this.baseStackName, - }, - ], - }; - if (cloud_runner_options_1.default.useCleanupCron) { - try { - cloud_runner_logger_1.default.log(`Creating job cleanup formation`); - CF.createStack(createCleanupStackInput).promise(); - // await CF.waitFor('stackCreateComplete', { StackName: createCleanupStackInput.StackName }).promise(); - } - catch (error) { - yield aws_error_1.AWSError.handleStackCreationFailure(error, CF, taskDefStackName); - throw error; - } - } - const taskDefResources = (yield CF.describeStackResources({ - StackName: taskDefStackName, - }).promise()).StackResources; - const baseResources = (yield CF.describeStackResources({ StackName: this.baseStackName }).promise()).StackResources; - return { - taskDefStackName, - taskDefCloudFormation, - taskDefResources, - baseResources, - }; - }); + } + const taskDefResources = (await CF.describeStackResources({ + StackName: taskDefStackName, + }).promise()).StackResources; + const baseResources = (await CF.describeStackResources({ StackName: this.baseStackName }).promise()).StackResources; + return { + taskDefStackName, + taskDefCloudFormation, + taskDefResources, + baseResources, + }; } } exports.AWSJobStack = AWSJobStack; @@ -1648,21 +1563,12 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); -const zlib = __importStar(__nccwpck_require__(59796)); +const zlib = __importStar(__nccwpck_require__(65628)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const __1 = __nccwpck_require__(41359); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); @@ -1671,138 +1577,125 @@ const follow_log_stream_service_1 = __nccwpck_require__(64121); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const github_1 = __importDefault(__nccwpck_require__(83654)); class AWSTaskRunner { - static runTask(taskDef, environment, commands) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; - return __awaiter(this, void 0, void 0, function* () { - const cluster = ((_b = (_a = taskDef.baseResources) === null || _a === void 0 ? void 0 : _a.find((x) => x.LogicalResourceId === 'ECSCluster')) === null || _b === void 0 ? void 0 : _b.PhysicalResourceId) || ''; - const taskDefinition = ((_d = (_c = taskDef.taskDefResources) === null || _c === void 0 ? void 0 : _c.find((x) => x.LogicalResourceId === 'TaskDefinition')) === null || _d === void 0 ? void 0 : _d.PhysicalResourceId) || ''; - const SubnetOne = ((_f = (_e = taskDef.baseResources) === null || _e === void 0 ? void 0 : _e.find((x) => x.LogicalResourceId === 'PublicSubnetOne')) === null || _f === void 0 ? void 0 : _f.PhysicalResourceId) || ''; - const SubnetTwo = ((_h = (_g = taskDef.baseResources) === null || _g === void 0 ? void 0 : _g.find((x) => x.LogicalResourceId === 'PublicSubnetTwo')) === null || _h === void 0 ? void 0 : _h.PhysicalResourceId) || ''; - const ContainerSecurityGroup = ((_k = (_j = taskDef.baseResources) === null || _j === void 0 ? void 0 : _j.find((x) => x.LogicalResourceId === 'ContainerSecurityGroup')) === null || _k === void 0 ? void 0 : _k.PhysicalResourceId) || ''; - const streamName = ((_m = (_l = taskDef.taskDefResources) === null || _l === void 0 ? void 0 : _l.find((x) => x.LogicalResourceId === 'KinesisStream')) === null || _m === void 0 ? void 0 : _m.PhysicalResourceId) || ''; - const task = yield AWSTaskRunner.ECS.runTask({ - cluster, - taskDefinition, - platformVersion: '1.4.0', - overrides: { - containerOverrides: [ - { - name: taskDef.taskDefStackName, - environment, - command: ['-c', cloud_runner_custom_hooks_1.CloudRunnerCustomHooks.ApplyHooksToCommands(commands, cloud_runner_1.default.buildParameters)], - }, - ], - }, - launchType: 'FARGATE', - networkConfiguration: { - awsvpcConfiguration: { - subnets: [SubnetOne, SubnetTwo], - assignPublicIp: 'ENABLED', - securityGroups: [ContainerSecurityGroup], + static async runTask(taskDef, environment, commands) { + const cluster = taskDef.baseResources?.find((x) => x.LogicalResourceId === 'ECSCluster')?.PhysicalResourceId || ''; + const taskDefinition = taskDef.taskDefResources?.find((x) => x.LogicalResourceId === 'TaskDefinition')?.PhysicalResourceId || ''; + const SubnetOne = taskDef.baseResources?.find((x) => x.LogicalResourceId === 'PublicSubnetOne')?.PhysicalResourceId || ''; + const SubnetTwo = taskDef.baseResources?.find((x) => x.LogicalResourceId === 'PublicSubnetTwo')?.PhysicalResourceId || ''; + const ContainerSecurityGroup = taskDef.baseResources?.find((x) => x.LogicalResourceId === 'ContainerSecurityGroup')?.PhysicalResourceId || ''; + const streamName = taskDef.taskDefResources?.find((x) => x.LogicalResourceId === 'KinesisStream')?.PhysicalResourceId || ''; + const task = await AWSTaskRunner.ECS.runTask({ + cluster, + taskDefinition, + platformVersion: '1.4.0', + overrides: { + containerOverrides: [ + { + name: taskDef.taskDefStackName, + environment, + command: ['-c', cloud_runner_custom_hooks_1.CloudRunnerCustomHooks.ApplyHooksToCommands(commands, cloud_runner_1.default.buildParameters)], }, + ], + }, + launchType: 'FARGATE', + networkConfiguration: { + awsvpcConfiguration: { + subnets: [SubnetOne, SubnetTwo], + assignPublicIp: 'ENABLED', + securityGroups: [ContainerSecurityGroup], }, - }).promise(); - const taskArn = ((_o = task.tasks) === null || _o === void 0 ? void 0 : _o[0].taskArn) || ''; - cloud_runner_logger_1.default.log('Cloud runner job is starting'); - yield AWSTaskRunner.waitUntilTaskRunning(taskArn, cluster); - cloud_runner_logger_1.default.log(`Cloud runner job status is running ${(_p = (yield AWSTaskRunner.describeTasks(cluster, taskArn))) === null || _p === void 0 ? void 0 : _p.lastStatus} Watch:${cloud_runner_options_1.default.watchCloudRunnerToEnd} Async:${cloud_runner_options_1.default.asyncCloudRunner}`); - if (!cloud_runner_options_1.default.watchCloudRunnerToEnd) { - const shouldCleanup = false; - const output = ''; - cloud_runner_logger_1.default.log(`Watch Cloud Runner To End: false`); - return { output, shouldCleanup }; - } - cloud_runner_logger_1.default.log(`Streaming...`); - const { output, shouldCleanup } = yield this.streamLogsUntilTaskStops(cluster, taskArn, streamName); - yield new Promise((resolve) => resolve(5000)); - const taskData = yield AWSTaskRunner.describeTasks(cluster, taskArn); - const containerState = (_q = taskData.containers) === null || _q === void 0 ? void 0 : _q[0]; - const exitCode = (containerState === null || containerState === void 0 ? void 0 : containerState.exitCode) || undefined; - cloud_runner_logger_1.default.log(`Container State: ${JSON.stringify(containerState, undefined, 4)}`); - const wasSuccessful = exitCode === 0 || (exitCode === undefined && taskData.lastStatus === 'RUNNING'); - if (wasSuccessful) { - cloud_runner_logger_1.default.log(`Cloud runner job has finished successfully`); - return { output, shouldCleanup }; - } - else { - if (taskData.stoppedReason === 'Essential container in task exited' && exitCode === 1) { - throw new Error('Container exited with code 1'); - } - const message = `Cloud runner job exit code ${exitCode}`; - taskData.overrides = undefined; - taskData.attachments = undefined; - cloud_runner_logger_1.default.log(`${message} ${JSON.stringify(taskData, undefined, 4)}`); - throw new Error(message); - } - }); - } - static waitUntilTaskRunning(taskArn, cluster) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - try { - yield AWSTaskRunner.ECS.waitFor('tasksRunning', { tasks: [taskArn], cluster }).promise(); - } - catch (error_) { - const error = error_; - yield new Promise((resolve) => setTimeout(resolve, 3000)); - cloud_runner_logger_1.default.log(`Cloud runner job has ended ${(_a = (yield AWSTaskRunner.describeTasks(cluster, taskArn)).containers) === null || _a === void 0 ? void 0 : _a[0].lastStatus}`); - core.setFailed(error); - core.error(error); - } - }); - } - static describeTasks(clusterName, taskArn) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const tasks = yield AWSTaskRunner.ECS.describeTasks({ - cluster: clusterName, - tasks: [taskArn], - }).promise(); - if ((_a = tasks.tasks) === null || _a === void 0 ? void 0 : _a[0]) { - return (_b = tasks.tasks) === null || _b === void 0 ? void 0 : _b[0]; - } - else { - throw new Error('No task found'); - } - }); - } - static streamLogsUntilTaskStops(clusterName, taskArn, kinesisStreamName) { - return __awaiter(this, void 0, void 0, function* () { - yield new Promise((resolve) => setTimeout(resolve, 3000)); - cloud_runner_logger_1.default.log(`Streaming...`); - const stream = yield AWSTaskRunner.getLogStream(kinesisStreamName); - let iterator = yield AWSTaskRunner.getLogIterator(stream); - const logBaseUrl = `https://${__1.Input.region}.console.aws.amazon.com/cloudwatch/home?region=${__1.Input.region}#logsV2:log-groups/log-group/${cloud_runner_1.default.buildParameters.awsBaseStackName}${AWSTaskRunner.encodedUnderscore}${cloud_runner_1.default.buildParameters.awsBaseStackName}-${cloud_runner_1.default.buildParameters.buildGuid}`; - cloud_runner_logger_1.default.log(`You view the log stream on AWS Cloud Watch: ${logBaseUrl}`); - yield github_1.default.updateGitHubCheck(`You view the log stream on AWS Cloud Watch: ${logBaseUrl}`, ``); - let shouldReadLogs = true; - let shouldCleanup = true; - let timestamp = 0; - let output = ''; - while (shouldReadLogs) { - yield new Promise((resolve) => setTimeout(resolve, 1500)); - const taskData = yield AWSTaskRunner.describeTasks(clusterName, taskArn); - ({ timestamp, shouldReadLogs } = AWSTaskRunner.checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs)); - ({ iterator, shouldReadLogs, output, shouldCleanup } = yield AWSTaskRunner.handleLogStreamIteration(iterator, shouldReadLogs, output, shouldCleanup)); - } + }, + }).promise(); + const taskArn = task.tasks?.[0].taskArn || ''; + cloud_runner_logger_1.default.log('Cloud runner job is starting'); + await AWSTaskRunner.waitUntilTaskRunning(taskArn, cluster); + cloud_runner_logger_1.default.log(`Cloud runner job status is running ${(await AWSTaskRunner.describeTasks(cluster, taskArn))?.lastStatus} Watch:${cloud_runner_options_1.default.watchCloudRunnerToEnd} Async:${cloud_runner_options_1.default.asyncCloudRunner}`); + if (!cloud_runner_options_1.default.watchCloudRunnerToEnd) { + const shouldCleanup = false; + const output = ''; + cloud_runner_logger_1.default.log(`Watch Cloud Runner To End: false`); return { output, shouldCleanup }; - }); + } + cloud_runner_logger_1.default.log(`Streaming...`); + const { output, shouldCleanup } = await this.streamLogsUntilTaskStops(cluster, taskArn, streamName); + await new Promise((resolve) => resolve(5000)); + const taskData = await AWSTaskRunner.describeTasks(cluster, taskArn); + const containerState = taskData.containers?.[0]; + const exitCode = containerState?.exitCode || undefined; + cloud_runner_logger_1.default.log(`Container State: ${JSON.stringify(containerState, undefined, 4)}`); + const wasSuccessful = exitCode === 0 || (exitCode === undefined && taskData.lastStatus === 'RUNNING'); + if (wasSuccessful) { + cloud_runner_logger_1.default.log(`Cloud runner job has finished successfully`); + return { output, shouldCleanup }; + } + else { + if (taskData.stoppedReason === 'Essential container in task exited' && exitCode === 1) { + throw new Error('Container exited with code 1'); + } + const message = `Cloud runner job exit code ${exitCode}`; + taskData.overrides = undefined; + taskData.attachments = undefined; + cloud_runner_logger_1.default.log(`${message} ${JSON.stringify(taskData, undefined, 4)}`); + throw new Error(message); + } } - static handleLogStreamIteration(iterator, shouldReadLogs, output, shouldCleanup) { - return __awaiter(this, void 0, void 0, function* () { - const records = yield AWSTaskRunner.Kinesis.getRecords({ - ShardIterator: iterator, - }).promise(); - iterator = records.NextShardIterator || ''; - ({ shouldReadLogs, output, shouldCleanup } = AWSTaskRunner.logRecords(records, iterator, shouldReadLogs, output, shouldCleanup)); - return { iterator, shouldReadLogs, output, shouldCleanup }; - }); + static async waitUntilTaskRunning(taskArn, cluster) { + try { + await AWSTaskRunner.ECS.waitFor('tasksRunning', { tasks: [taskArn], cluster }).promise(); + } + catch (error_) { + const error = error_; + await new Promise((resolve) => setTimeout(resolve, 3000)); + cloud_runner_logger_1.default.log(`Cloud runner job has ended ${(await AWSTaskRunner.describeTasks(cluster, taskArn)).containers?.[0].lastStatus}`); + core.setFailed(error); + core.error(error); + } + } + static async describeTasks(clusterName, taskArn) { + const tasks = await AWSTaskRunner.ECS.describeTasks({ + cluster: clusterName, + tasks: [taskArn], + }).promise(); + if (tasks.tasks?.[0]) { + return tasks.tasks?.[0]; + } + else { + throw new Error('No task found'); + } + } + static async streamLogsUntilTaskStops(clusterName, taskArn, kinesisStreamName) { + await new Promise((resolve) => setTimeout(resolve, 3000)); + cloud_runner_logger_1.default.log(`Streaming...`); + const stream = await AWSTaskRunner.getLogStream(kinesisStreamName); + let iterator = await AWSTaskRunner.getLogIterator(stream); + const logBaseUrl = `https://${__1.Input.region}.console.aws.amazon.com/cloudwatch/home?region=${__1.Input.region}#logsV2:log-groups/log-group/${cloud_runner_1.default.buildParameters.awsBaseStackName}${AWSTaskRunner.encodedUnderscore}${cloud_runner_1.default.buildParameters.awsBaseStackName}-${cloud_runner_1.default.buildParameters.buildGuid}`; + cloud_runner_logger_1.default.log(`You view the log stream on AWS Cloud Watch: ${logBaseUrl}`); + await github_1.default.updateGitHubCheck(`You view the log stream on AWS Cloud Watch: ${logBaseUrl}`, ``); + let shouldReadLogs = true; + let shouldCleanup = true; + let timestamp = 0; + let output = ''; + while (shouldReadLogs) { + await new Promise((resolve) => setTimeout(resolve, 1500)); + const taskData = await AWSTaskRunner.describeTasks(clusterName, taskArn); + ({ timestamp, shouldReadLogs } = AWSTaskRunner.checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs)); + ({ iterator, shouldReadLogs, output, shouldCleanup } = await AWSTaskRunner.handleLogStreamIteration(iterator, shouldReadLogs, output, shouldCleanup)); + } + return { output, shouldCleanup }; + } + static async handleLogStreamIteration(iterator, shouldReadLogs, output, shouldCleanup) { + const records = await AWSTaskRunner.Kinesis.getRecords({ + ShardIterator: iterator, + }).promise(); + iterator = records.NextShardIterator || ''; + ({ shouldReadLogs, output, shouldCleanup } = AWSTaskRunner.logRecords(records, iterator, shouldReadLogs, output, shouldCleanup)); + return { iterator, shouldReadLogs, output, shouldCleanup }; } static checkStreamingShouldContinue(taskData, timestamp, shouldReadLogs) { - if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) === 'UNKNOWN') { + if (taskData?.lastStatus === 'UNKNOWN') { cloud_runner_logger_1.default.log('## Cloud runner job unknwon'); } - if ((taskData === null || taskData === void 0 ? void 0 : taskData.lastStatus) !== 'RUNNING') { + if (taskData?.lastStatus !== 'RUNNING') { if (timestamp === 0) { cloud_runner_logger_1.default.log('## Cloud runner job stopped, streaming end of logs'); timestamp = Date.now(); @@ -1817,33 +1710,28 @@ class AWSTaskRunner { } static logRecords(records, iterator, shouldReadLogs, output, shouldCleanup) { if (records.Records.length > 0 && iterator) { - for (let index = 0; index < records.Records.length; index++) { - const json = JSON.parse(zlib.gunzipSync(Buffer.from(records.Records[index].Data, 'base64')).toString('utf8')); + for (const record of records.Records) { + const json = JSON.parse(zlib.gunzipSync(Buffer.from(record.Data, 'base64')).toString('utf8')); if (json.messageType === 'DATA_MESSAGE') { - for (let logEventsIndex = 0; logEventsIndex < json.logEvents.length; logEventsIndex++) { - const message = json.logEvents[logEventsIndex].message; - ({ shouldReadLogs, shouldCleanup, output } = follow_log_stream_service_1.FollowLogStreamService.handleIteration(message, shouldReadLogs, shouldCleanup, output)); + for (const logEvent of json.logEvents) { + ({ shouldReadLogs, shouldCleanup, output } = follow_log_stream_service_1.FollowLogStreamService.handleIteration(logEvent.message, shouldReadLogs, shouldCleanup, output)); } } } } return { shouldReadLogs, output, shouldCleanup }; } - static getLogStream(kinesisStreamName) { - return __awaiter(this, void 0, void 0, function* () { - return yield AWSTaskRunner.Kinesis.describeStream({ - StreamName: kinesisStreamName, - }).promise(); - }); + static async getLogStream(kinesisStreamName) { + return await AWSTaskRunner.Kinesis.describeStream({ + StreamName: kinesisStreamName, + }).promise(); } - static getLogIterator(stream) { - return __awaiter(this, void 0, void 0, function* () { - return ((yield AWSTaskRunner.Kinesis.getShardIterator({ - ShardIteratorType: 'TRIM_HORIZON', - StreamName: stream.StreamDescription.StreamName, - ShardId: stream.StreamDescription.Shards[0].ShardId, - }).promise()).ShardIterator || ''); - }); + static async getLogIterator(stream) { + return ((await AWSTaskRunner.Kinesis.getShardIterator({ + ShardIteratorType: 'TRIM_HORIZON', + StreamName: stream.StreamDescription.StreamName, + ShardId: stream.StreamDescription.Shards[0].ShardId, + }).promise()).ShardIterator || ''); } } AWSTaskRunner.encodedUnderscore = `$252F`; @@ -2620,15 +2508,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -2646,41 +2525,33 @@ class AWSBuildEnvironment { constructor(buildParameters) { this.baseStackName = buildParameters.awsBaseStackName; } - listResources() { - return __awaiter(this, void 0, void 0, function* () { - yield task_service_1.TaskService.getCloudFormationJobStacks(); - yield task_service_1.TaskService.getLogGroups(); - yield task_service_1.TaskService.getTasks(); - return []; - }); + async listResources() { + await task_service_1.TaskService.getCloudFormationJobStacks(); + await task_service_1.TaskService.getLogGroups(); + await task_service_1.TaskService.getTasks(); + return []; } listWorkflow() { throw new Error('Method not implemented.'); } - watchWorkflow() { - return __awaiter(this, void 0, void 0, function* () { - return yield task_service_1.TaskService.watch(); - }); + async watchWorkflow() { + return await task_service_1.TaskService.watch(); } - listOtherResources() { - return __awaiter(this, void 0, void 0, function* () { - yield task_service_1.TaskService.getLogGroups(); - return ''; - }); + async listOtherResources() { + await task_service_1.TaskService.getLogGroups(); + return ''; } - garbageCollect(filter, previewOnly, + async garbageCollect(filter, previewOnly, // eslint-disable-next-line no-unused-vars olderThan, // eslint-disable-next-line no-unused-vars fullCache, // eslint-disable-next-line no-unused-vars baseDependencies) { - return __awaiter(this, void 0, void 0, function* () { - yield garbage_collection_service_1.GarbageCollectionService.cleanup(!previewOnly); - return ``; - }); + await garbage_collection_service_1.GarbageCollectionService.cleanup(!previewOnly); + return ``; } - cleanupWorkflow( + async cleanupWorkflow( // eslint-disable-next-line no-unused-vars buildGuid, // eslint-disable-next-line no-unused-vars @@ -2688,10 +2559,8 @@ class AWSBuildEnvironment { // eslint-disable-next-line no-unused-vars branchName, // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { }); - } - setupWorkflow( + defaultSecretsArray) { } + async setupWorkflow( // eslint-disable-next-line no-unused-vars buildGuid, // eslint-disable-next-line no-unused-vars @@ -2699,60 +2568,54 @@ class AWSBuildEnvironment { // eslint-disable-next-line no-unused-vars branchName, // eslint-disable-next-line no-unused-vars - defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { }); + defaultSecretsArray) { } + async runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { + process.env.AWS_REGION = __1.Input.region; + const ECS = new SDK.ECS(); + const CF = new SDK.CloudFormation(); + aws_task_runner_1.default.ECS = ECS; + aws_task_runner_1.default.Kinesis = new SDK.Kinesis(); + cloud_runner_logger_1.default.log(`AWS Region: ${CF.config.region}`); + const entrypoint = ['/bin/sh']; + const startTimeMs = Date.now(); + await new aws_base_stack_1.AWSBaseStack(this.baseStackName).setupBaseStack(CF); + const taskDef = await new aws_job_stack_1.AWSJobStack(this.baseStackName).setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets); + let postRunTaskTimeMs; + try { + const postSetupStacksTimeMs = Date.now(); + cloud_runner_logger_1.default.log(`Setup job time: ${Math.floor((postSetupStacksTimeMs - startTimeMs) / 1000)}s`); + const { output, shouldCleanup } = await aws_task_runner_1.default.runTask(taskDef, environment, commands); + postRunTaskTimeMs = Date.now(); + cloud_runner_logger_1.default.log(`Run job time: ${Math.floor((postRunTaskTimeMs - postSetupStacksTimeMs) / 1000)}s`); + if (shouldCleanup) { + await this.cleanupResources(CF, taskDef); + } + const postCleanupTimeMs = Date.now(); + if (postRunTaskTimeMs !== undefined) + cloud_runner_logger_1.default.log(`Cleanup job time: ${Math.floor((postCleanupTimeMs - postRunTaskTimeMs) / 1000)}s`); + return output; + } + catch (error) { + cloud_runner_logger_1.default.log(`error running task ${error}`); + await this.cleanupResources(CF, taskDef); + throw error; + } } - runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = __1.Input.region; - const ECS = new SDK.ECS(); - const CF = new SDK.CloudFormation(); - aws_task_runner_1.default.ECS = ECS; - aws_task_runner_1.default.Kinesis = new SDK.Kinesis(); - cloud_runner_logger_1.default.log(`AWS Region: ${CF.config.region}`); - const entrypoint = ['/bin/sh']; - const startTimeMs = Date.now(); - yield new aws_base_stack_1.AWSBaseStack(this.baseStackName).setupBaseStack(CF); - const taskDef = yield new aws_job_stack_1.AWSJobStack(this.baseStackName).setupCloudFormations(CF, buildGuid, image, entrypoint, commands, mountdir, workingdir, secrets); - let postRunTaskTimeMs; - try { - const postSetupStacksTimeMs = Date.now(); - cloud_runner_logger_1.default.log(`Setup job time: ${Math.floor((postSetupStacksTimeMs - startTimeMs) / 1000)}s`); - const { output, shouldCleanup } = yield aws_task_runner_1.default.runTask(taskDef, environment, commands); - postRunTaskTimeMs = Date.now(); - cloud_runner_logger_1.default.log(`Run job time: ${Math.floor((postRunTaskTimeMs - postSetupStacksTimeMs) / 1000)}s`); - if (shouldCleanup) { - yield this.cleanupResources(CF, taskDef); - } - const postCleanupTimeMs = Date.now(); - if (postRunTaskTimeMs !== undefined) - cloud_runner_logger_1.default.log(`Cleanup job time: ${Math.floor((postCleanupTimeMs - postRunTaskTimeMs) / 1000)}s`); - return output; - } - catch (error) { - cloud_runner_logger_1.default.log(`error running task ${error}`); - yield this.cleanupResources(CF, taskDef); - throw error; - } - }); - } - cleanupResources(CF, taskDef) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('Cleanup starting'); - yield CF.deleteStack({ - StackName: taskDef.taskDefStackName, + async cleanupResources(CF, taskDef) { + cloud_runner_logger_1.default.log('Cleanup starting'); + await CF.deleteStack({ + StackName: taskDef.taskDefStackName, + }).promise(); + if (cloud_runner_options_1.default.useCleanupCron) { + await CF.deleteStack({ + StackName: `${taskDef.taskDefStackName}-cleanup`, }).promise(); - if (cloud_runner_options_1.default.useCleanupCron) { - yield CF.deleteStack({ - StackName: `${taskDef.taskDefStackName}-cleanup`, - }).promise(); - } - yield CF.waitFor('stackDeleteComplete', { - StackName: taskDef.taskDefStackName, - }).promise(); - cloud_runner_logger_1.default.log(`Deleted Stack: ${taskDef.taskDefStackName}`); - cloud_runner_logger_1.default.log('Cleanup complete'); - }); + } + await CF.waitFor('stackDeleteComplete', { + StackName: taskDef.taskDefStackName, + }).promise(); + cloud_runner_logger_1.default.log(`Deleted Stack: ${taskDef.taskDefStackName}`); + cloud_runner_logger_1.default.log('Cleanup complete'); } } exports["default"] = AWSBuildEnvironment; @@ -2765,15 +2628,6 @@ exports["default"] = AWSBuildEnvironment; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -2788,52 +2642,49 @@ class GarbageCollectionService { const ageDate = new Date(date.getTime() - Date.now()); return ageDate.getDay() > 0; } - static cleanup(deleteResources = false, OneDayOlderOnly = false) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = input_1.default.region; - const CF = new aws_sdk_1.default.CloudFormation(); - const ecs = new aws_sdk_1.default.ECS(); - const cwl = new aws_sdk_1.default.CloudWatchLogs(); - const taskDefinitionsInUse = new Array(); - const tasks = yield task_service_1.TaskService.getTasks(); - for (const task of tasks) { - const { taskElement, element } = task; - taskDefinitionsInUse.push(taskElement.taskDefinitionArn); - if (deleteResources && (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(taskElement.CreatedAt))) { - cloud_runner_logger_1.default.log(`Stopping task ${(_a = taskElement.containers) === null || _a === void 0 ? void 0 : _a[0].name}`); - yield ecs.stopTask({ task: taskElement.taskArn || '', cluster: element }).promise(); - } + static async cleanup(deleteResources = false, OneDayOlderOnly = false) { + process.env.AWS_REGION = input_1.default.region; + const CF = new aws_sdk_1.default.CloudFormation(); + const ecs = new aws_sdk_1.default.ECS(); + const cwl = new aws_sdk_1.default.CloudWatchLogs(); + const taskDefinitionsInUse = new Array(); + const tasks = await task_service_1.TaskService.getTasks(); + for (const task of tasks) { + const { taskElement, element } = task; + taskDefinitionsInUse.push(taskElement.taskDefinitionArn); + if (deleteResources && (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(taskElement.createdAt))) { + cloud_runner_logger_1.default.log(`Stopping task ${taskElement.containers?.[0].name}`); + await ecs.stopTask({ task: taskElement.taskArn || '', cluster: element }).promise(); } - const jobStacks = yield task_service_1.TaskService.getCloudFormationJobStacks(); - for (const element of jobStacks) { - if ((_b = (yield CF.describeStackResources({ StackName: element.StackName }).promise()).StackResources) === null || _b === void 0 ? void 0 : _b.some((x) => x.ResourceType === 'AWS::ECS::TaskDefinition' && taskDefinitionsInUse.includes(x.PhysicalResourceId))) { - cloud_runner_logger_1.default.log(`Skipping ${element.StackName} - active task was running not deleting`); + } + const jobStacks = await task_service_1.TaskService.getCloudFormationJobStacks(); + for (const element of jobStacks) { + if ((await CF.describeStackResources({ StackName: element.StackName }).promise()).StackResources?.some((x) => x.ResourceType === 'AWS::ECS::TaskDefinition' && taskDefinitionsInUse.includes(x.PhysicalResourceId))) { + cloud_runner_logger_1.default.log(`Skipping ${element.StackName} - active task was running not deleting`); + return; + } + if (deleteResources && (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(element.CreationTime))) { + if (element.StackName === 'game-ci' || element.TemplateDescription === 'Game-CI base stack') { + cloud_runner_logger_1.default.log(`Skipping ${element.StackName} ignore list`); return; } - if (deleteResources && (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(element.CreationTime))) { - if (element.StackName === 'game-ci' || element.TemplateDescription === 'Game-CI base stack') { - cloud_runner_logger_1.default.log(`Skipping ${element.StackName} ignore list`); - return; - } - cloud_runner_logger_1.default.log(`Deleting ${element.logGroupName}`); - const deleteStackInput = { StackName: element.StackName }; - yield CF.deleteStack(deleteStackInput).promise(); - } + cloud_runner_logger_1.default.log(`Deleting ${element.StackName}`); + const deleteStackInput = { StackName: element.StackName }; + await CF.deleteStack(deleteStackInput).promise(); } - const logGroups = yield task_service_1.TaskService.getLogGroups(); - for (const element of logGroups) { - if (deleteResources && - (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(new Date(element.createdAt)))) { - cloud_runner_logger_1.default.log(`Deleting ${element.logGroupName}`); - yield cwl.deleteLogGroup({ logGroupName: element.logGroupName || '' }).promise(); - } + } + const logGroups = await task_service_1.TaskService.getLogGroups(); + for (const element of logGroups) { + if (deleteResources && + (!OneDayOlderOnly || GarbageCollectionService.isOlderThan1day(new Date(element.creationTime)))) { + cloud_runner_logger_1.default.log(`Deleting ${element.logGroupName}`); + await cwl.deleteLogGroup({ logGroupName: element.logGroupName || '' }).promise(); } - const locks = yield task_service_1.TaskService.getLocks(); - for (const element of locks) { - cloud_runner_logger_1.default.log(`Lock: ${element.Key}`); - } - }); + } + const locks = await task_service_1.TaskService.getLocks(); + for (const element of locks) { + cloud_runner_logger_1.default.log(`Lock: ${element.Key}`); + } } } exports.GarbageCollectionService = GarbageCollectionService; @@ -2846,15 +2697,6 @@ exports.GarbageCollectionService = GarbageCollectionService; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -2867,142 +2709,128 @@ const base_stack_formation_1 = __nccwpck_require__(29643); const aws_task_runner_1 = __importDefault(__nccwpck_require__(15518)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class TaskService { - static watch() { - return __awaiter(this, void 0, void 0, function* () { - // eslint-disable-next-line no-unused-vars - const { output, shouldCleanup } = yield aws_task_runner_1.default.streamLogsUntilTaskStops(process.env.cluster || ``, process.env.taskArn || ``, process.env.streamName || ``); - return output; - }); + static async watch() { + // eslint-disable-next-line no-unused-vars + const { output, shouldCleanup } = await aws_task_runner_1.default.streamLogsUntilTaskStops(process.env.cluster || ``, process.env.taskArn || ``, process.env.streamName || ``); + return output; } - static getCloudFormationJobStacks() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const result = []; - cloud_runner_logger_1.default.log(``); - cloud_runner_logger_1.default.log(`List Cloud Formation Stacks`); - process.env.AWS_REGION = input_1.default.region; - const CF = new aws_sdk_1.default.CloudFormation(); - const stacks = ((_a = (yield CF.listStacks().promise()).StackSummaries) === null || _a === void 0 ? void 0 : _a.filter((_x) => _x.StackStatus !== 'DELETE_COMPLETE' && _x.TemplateDescription !== base_stack_formation_1.BaseStackFormation.baseStackDecription)) || []; - cloud_runner_logger_1.default.log(``); - cloud_runner_logger_1.default.log(`Cloud Formation Stacks ${stacks.length}`); - for (const element of stacks) { - const ageDate = new Date(Date.now() - element.CreationTime.getTime()); - cloud_runner_logger_1.default.log(`Task Stack ${element.StackName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); - result.push(element); - } - const baseStacks = ((_b = (yield CF.listStacks().promise()).StackSummaries) === null || _b === void 0 ? void 0 : _b.filter((_x) => _x.StackStatus !== 'DELETE_COMPLETE' && _x.TemplateDescription === base_stack_formation_1.BaseStackFormation.baseStackDecription)) || []; - cloud_runner_logger_1.default.log(``); - cloud_runner_logger_1.default.log(`Base Stacks ${baseStacks.length}`); - for (const element of baseStacks) { - const ageDate = new Date(Date.now() - element.CreationTime.getTime()); - cloud_runner_logger_1.default.log(`Task Stack ${element.StackName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); - result.push(element); - } - cloud_runner_logger_1.default.log(``); - return result; - }); + static async getCloudFormationJobStacks() { + const result = []; + cloud_runner_logger_1.default.log(``); + cloud_runner_logger_1.default.log(`List Cloud Formation Stacks`); + process.env.AWS_REGION = input_1.default.region; + const CF = new aws_sdk_1.default.CloudFormation(); + const stacks = (await CF.listStacks().promise()).StackSummaries?.filter((_x) => _x.StackStatus !== 'DELETE_COMPLETE' && _x.TemplateDescription !== base_stack_formation_1.BaseStackFormation.baseStackDecription) || []; + cloud_runner_logger_1.default.log(``); + cloud_runner_logger_1.default.log(`Cloud Formation Stacks ${stacks.length}`); + for (const element of stacks) { + const ageDate = new Date(Date.now() - element.CreationTime.getTime()); + cloud_runner_logger_1.default.log(`Task Stack ${element.StackName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); + result.push(element); + } + const baseStacks = (await CF.listStacks().promise()).StackSummaries?.filter((_x) => _x.StackStatus !== 'DELETE_COMPLETE' && _x.TemplateDescription === base_stack_formation_1.BaseStackFormation.baseStackDecription) || []; + cloud_runner_logger_1.default.log(``); + cloud_runner_logger_1.default.log(`Base Stacks ${baseStacks.length}`); + for (const element of baseStacks) { + const ageDate = new Date(Date.now() - element.CreationTime.getTime()); + cloud_runner_logger_1.default.log(`Task Stack ${element.StackName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); + result.push(element); + } + cloud_runner_logger_1.default.log(``); + return result; } - static getTasks() { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - cloud_runner_logger_1.default.log(``); - cloud_runner_logger_1.default.log(`List Tasks`); - process.env.AWS_REGION = input_1.default.region; - const ecs = new aws_sdk_1.default.ECS(); - const clusters = (yield ecs.listClusters().promise()).clusterArns || []; - cloud_runner_logger_1.default.log(`Task Clusters ${clusters.length}`); - for (const element of clusters) { - const input = { - cluster: element, - }; - const list = (yield ecs.listTasks(input).promise()).taskArns || []; - if (list.length > 0) { - const describeInput = { tasks: list, cluster: element }; - const describeList = (yield ecs.describeTasks(describeInput).promise()).tasks || []; - if (describeList.length === 0) { - cloud_runner_logger_1.default.log(`No Tasks`); + static async getTasks() { + const result = []; + cloud_runner_logger_1.default.log(``); + cloud_runner_logger_1.default.log(`List Tasks`); + process.env.AWS_REGION = input_1.default.region; + const ecs = new aws_sdk_1.default.ECS(); + const clusters = (await ecs.listClusters().promise()).clusterArns || []; + cloud_runner_logger_1.default.log(`Task Clusters ${clusters.length}`); + for (const element of clusters) { + const input = { + cluster: element, + }; + const list = (await ecs.listTasks(input).promise()).taskArns || []; + if (list.length > 0) { + const describeInput = { tasks: list, cluster: element }; + const describeList = (await ecs.describeTasks(describeInput).promise()).tasks || []; + if (describeList.length === 0) { + cloud_runner_logger_1.default.log(`No Tasks`); + continue; + } + cloud_runner_logger_1.default.log(`Tasks ${describeList.length}`); + for (const taskElement of describeList) { + if (taskElement === undefined) { continue; } - cloud_runner_logger_1.default.log(`Tasks ${describeList.length}`); - for (const taskElement of describeList) { - if (taskElement === undefined) { - continue; - } - taskElement.overrides = {}; - taskElement.attachments = []; - if (taskElement.createdAt === undefined) { - cloud_runner_logger_1.default.log(`Skipping ${taskElement.taskDefinitionArn} no createdAt date`); - continue; - } - result.push({ taskElement, element }); + taskElement.overrides = {}; + taskElement.attachments = []; + if (taskElement.createdAt === undefined) { + cloud_runner_logger_1.default.log(`Skipping ${taskElement.taskDefinitionArn} no createdAt date`); + continue; } + result.push({ taskElement, element }); } } - cloud_runner_logger_1.default.log(``); - return result; - }); + } + cloud_runner_logger_1.default.log(``); + return result; } - static awsDescribeJob(job) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = input_1.default.region; - const CF = new aws_sdk_1.default.CloudFormation(); - const stack = ((_a = (yield CF.listStacks().promise()).StackSummaries) === null || _a === void 0 ? void 0 : _a.find((_x) => _x.StackName === job)) || undefined; - const stackInfo = (yield CF.describeStackResources({ StackName: job }).promise()) || undefined; - const stackInfo2 = (yield CF.describeStacks({ StackName: job }).promise()) || undefined; - if (stack === undefined) { - throw new Error('stack not defined'); - } - const ageDate = new Date(Date.now() - stack.CreationTime.getTime()); - const message = ` + static async awsDescribeJob(job) { + process.env.AWS_REGION = input_1.default.region; + const CF = new aws_sdk_1.default.CloudFormation(); + const stack = (await CF.listStacks().promise()).StackSummaries?.find((_x) => _x.StackName === job) || undefined; + const stackInfo = (await CF.describeStackResources({ StackName: job }).promise()) || undefined; + const stackInfo2 = (await CF.describeStacks({ StackName: job }).promise()) || undefined; + if (stack === undefined) { + throw new Error('stack not defined'); + } + const ageDate = new Date(Date.now() - stack.CreationTime.getTime()); + const message = ` Task Stack ${stack.StackName} Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()} ${JSON.stringify(stack, undefined, 4)} ${JSON.stringify(stackInfo, undefined, 4)} ${JSON.stringify(stackInfo2, undefined, 4)} `; - cloud_runner_logger_1.default.log(message); - return message; - }); + cloud_runner_logger_1.default.log(message); + return message; } - static getLogGroups() { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - process.env.AWS_REGION = input_1.default.region; - const ecs = new aws_sdk_1.default.CloudWatchLogs(); - let logStreamInput = { - /* logGroupNamePrefix: 'game-ci' */ - }; - let logGroupsDescribe = yield ecs.describeLogGroups(logStreamInput).promise(); - const logGroups = logGroupsDescribe.logGroups || []; - while (logGroupsDescribe.nextToken) { - logStreamInput = { /* logGroupNamePrefix: 'game-ci',*/ nextToken: logGroupsDescribe.nextToken }; - logGroupsDescribe = yield ecs.describeLogGroups(logStreamInput).promise(); - logGroups.push(...((logGroupsDescribe === null || logGroupsDescribe === void 0 ? void 0 : logGroupsDescribe.logGroups) || [])); + static async getLogGroups() { + const result = []; + process.env.AWS_REGION = input_1.default.region; + const ecs = new aws_sdk_1.default.CloudWatchLogs(); + let logStreamInput = { + /* logGroupNamePrefix: 'game-ci' */ + }; + let logGroupsDescribe = await ecs.describeLogGroups(logStreamInput).promise(); + const logGroups = logGroupsDescribe.logGroups || []; + while (logGroupsDescribe.nextToken) { + logStreamInput = { /* logGroupNamePrefix: 'game-ci',*/ nextToken: logGroupsDescribe.nextToken }; + logGroupsDescribe = await ecs.describeLogGroups(logStreamInput).promise(); + logGroups.push(...(logGroupsDescribe?.logGroups || [])); + } + cloud_runner_logger_1.default.log(`Log Groups ${logGroups.length}`); + for (const element of logGroups) { + if (element.creationTime === undefined) { + cloud_runner_logger_1.default.log(`Skipping ${element.logGroupName} no createdAt date`); + continue; } - cloud_runner_logger_1.default.log(`Log Groups ${logGroups.length}`); - for (const element of logGroups) { - if (element.creationTime === undefined) { - cloud_runner_logger_1.default.log(`Skipping ${element.logGroupName} no createdAt date`); - continue; - } - const ageDate = new Date(Date.now() - element.creationTime); - cloud_runner_logger_1.default.log(`Task Stack ${element.logGroupName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); - result.push(element); - } - return result; - }); + const ageDate = new Date(Date.now() - element.creationTime); + cloud_runner_logger_1.default.log(`Task Stack ${element.logGroupName} - Age D${Math.floor(ageDate.getHours() / 24)} H${ageDate.getHours()} M${ageDate.getMinutes()}`); + result.push(element); + } + return result; } - static getLocks() { - return __awaiter(this, void 0, void 0, function* () { - process.env.AWS_REGION = input_1.default.region; - const s3 = new aws_sdk_1.default.S3(); - const listRequest = { - Bucket: cloud_runner_1.default.buildParameters.awsBaseStackName, - }; - const results = yield s3.listObjects(listRequest).promise(); - return results.Contents || []; - }); + static async getLocks() { + process.env.AWS_REGION = input_1.default.region; + const s3 = new aws_sdk_1.default.S3(); + const listRequest = { + Bucket: cloud_runner_1.default.buildParameters.awsBaseStackName, + }; + const results = await s3.listObjects(listRequest).promise(); + return results.Contents || []; } } exports.TaskService = TaskService; @@ -3015,34 +2843,6 @@ exports.TaskService = TaskService; "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -3053,7 +2853,7 @@ const __1 = __nccwpck_require__(41359); const fs_1 = __nccwpck_require__(57147); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const cloud_runner_system_1 = __nccwpck_require__(99393); -const fs = __importStar(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); class LocalDockerCloudRunner { listResources() { return new Promise((resolve) => resolve([])); @@ -3077,18 +2877,16 @@ class LocalDockerCloudRunner { baseDependencies) { return new Promise((result) => result(``)); } - cleanupWorkflow(buildGuid, buildParameters, + async cleanupWorkflow(buildGuid, buildParameters, // eslint-disable-next-line no-unused-vars branchName, // eslint-disable-next-line no-unused-vars defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { - const { workspace } = __1.Action; - if (fs.existsSync(`${workspace}/cloud-runner-cache/cache/build/build-${buildParameters.buildGuid}.tar${cloud_runner_1.default.buildParameters.useLz4Compression ? '.lz4' : ''}`)) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${workspace}/cloud-runner-cache/cache/build/`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${workspace}/cloud-runner-cache/cache/build/build-${buildParameters.buildGuid}.tar${cloud_runner_1.default.buildParameters.useLz4Compression ? '.lz4' : ''}`); - } - }); + const { workspace } = __1.Action; + if (node_fs_1.default.existsSync(`${workspace}/cloud-runner-cache/cache/build/build-${buildParameters.buildGuid}.tar${cloud_runner_1.default.buildParameters.useLz4Compression ? '.lz4' : ''}`)) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${workspace}/cloud-runner-cache/cache/build/`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${workspace}/cloud-runner-cache/cache/build/build-${buildParameters.buildGuid}.tar${cloud_runner_1.default.buildParameters.useLz4Compression ? '.lz4' : ''}`); + } } setupWorkflow(buildGuid, buildParameters, // eslint-disable-next-line no-unused-vars @@ -3097,34 +2895,33 @@ class LocalDockerCloudRunner { defaultSecretsArray) { this.buildParameters = buildParameters; } - runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(buildGuid); - cloud_runner_logger_1.default.log(commands); - const { workspace, actionFolder } = __1.Action; - const content = []; - for (const x of secrets) { - content.push({ name: x.EnvironmentVariable, value: x.ParameterValue }); + async runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { + cloud_runner_logger_1.default.log(buildGuid); + cloud_runner_logger_1.default.log(commands); + const { workspace, actionFolder } = __1.Action; + const content = []; + for (const x of secrets) { + content.push({ name: x.EnvironmentVariable, value: x.ParameterValue }); + } + for (const x of environment) { + content.push({ name: x.name, value: x.value }); + } + // if (this.buildParameters?.cloudRunnerIntegrationTests) { + // core.info(JSON.stringify(content, undefined, 4)); + // core.info(JSON.stringify(secrets, undefined, 4)); + // core.info(JSON.stringify(environment, undefined, 4)); + // } + // eslint-disable-next-line unicorn/no-for-loop + for (let index = 0; index < content.length; index++) { + if (content[index] === undefined) { + delete content[index]; } - for (const x of environment) { - content.push({ name: x.name, value: x.value }); - } - // if (this.buildParameters?.cloudRunnerIntegrationTests) { - // core.info(JSON.stringify(content, undefined, 4)); - // core.info(JSON.stringify(secrets, undefined, 4)); - // core.info(JSON.stringify(environment, undefined, 4)); - // } - // eslint-disable-next-line unicorn/no-for-loop - for (let index = 0; index < content.length; index++) { - if (content[index] === undefined) { - delete content[index]; - } - } - let myOutput = ''; - const sharedFolder = `/data/`; - // core.info(JSON.stringify({ workspace, actionFolder, ...this.buildParameters, ...content }, undefined, 4)); - const entrypointFilePath = `start.sh`; - const fileContents = `#!/bin/bash + } + let myOutput = ''; + const sharedFolder = `/data/`; + // core.info(JSON.stringify({ workspace, actionFolder, ...this.buildParameters, ...content }, undefined, 4)); + const entrypointFilePath = `start.sh`; + const fileContents = `#!/bin/bash set -e mkdir -p /github/workspace/cloud-runner-cache @@ -3133,27 +2930,26 @@ cp -a /github/workspace/cloud-runner-cache/. ${sharedFolder} ${commands} cp -a ${sharedFolder}. /github/workspace/cloud-runner-cache/ `; - fs_1.writeFileSync(`${workspace}/${entrypointFilePath}`, fileContents, { - flag: 'w', - }); - if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { - cloud_runner_logger_1.default.log(`Running local-docker: \n ${fileContents}`); - } - if (fs.existsSync(`${workspace}/cloud-runner-cache`)) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${workspace}/cloud-runner-cache && du -sh ${workspace}/cloud-runner-cache`); - } - yield docker_1.default.run(image, Object.assign({ workspace, actionFolder }, this.buildParameters), false, `chmod +x /github/workspace/${entrypointFilePath} && /github/workspace/${entrypointFilePath}`, content, { - listeners: { - stdout: (data) => { - myOutput += data.toString(); - }, - stderr: (data) => { - myOutput += `[LOCAL-DOCKER-ERROR]${data.toString()}`; - }, - }, - }, true); - return myOutput; + fs_1.writeFileSync(`${workspace}/${entrypointFilePath}`, fileContents, { + flag: 'w', }); + if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { + cloud_runner_logger_1.default.log(`Running local-docker: \n ${fileContents}`); + } + if (node_fs_1.default.existsSync(`${workspace}/cloud-runner-cache`)) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`ls ${workspace}/cloud-runner-cache && du -sh ${workspace}/cloud-runner-cache`); + } + await docker_1.default.run(image, { workspace, actionFolder, ...this.buildParameters }, false, `chmod +x /github/workspace/${entrypointFilePath} && /github/workspace/${entrypointFilePath}`, content, { + listeners: { + stdout: (data) => { + myOutput += data.toString(); + }, + stderr: (data) => { + myOutput += `[LOCAL-DOCKER-ERROR]${data.toString()}`; + }, + }, + }, true); + return myOutput; } } exports["default"] = LocalDockerCloudRunner; @@ -3185,15 +2981,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -3227,31 +3014,25 @@ class Kubernetes { this.namespace = 'default'; cloud_runner_logger_1.default.log('Loaded default Kubernetes configuration for this environment'); } - listResources() { - return __awaiter(this, void 0, void 0, function* () { - const pods = yield this.kubeClient.listNamespacedPod(this.namespace); - const serviceAccounts = yield this.kubeClient.listNamespacedServiceAccount(this.namespace); - const secrets = yield this.kubeClient.listNamespacedSecret(this.namespace); - const jobs = yield this.kubeClientBatch.listNamespacedJob(this.namespace); - return [ - ...pods.body.items.map((x) => { - var _a; - return { Name: ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name) || `` }; - }), - ...serviceAccounts.body.items.map((x) => { - var _a; - return { Name: ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name) || `` }; - }), - ...secrets.body.items.map((x) => { - var _a; - return { Name: ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name) || `` }; - }), - ...jobs.body.items.map((x) => { - var _a; - return { Name: ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name) || `` }; - }), - ]; - }); + async listResources() { + const pods = await this.kubeClient.listNamespacedPod(this.namespace); + const serviceAccounts = await this.kubeClient.listNamespacedServiceAccount(this.namespace); + const secrets = await this.kubeClient.listNamespacedSecret(this.namespace); + const jobs = await this.kubeClientBatch.listNamespacedJob(this.namespace); + return [ + ...pods.body.items.map((x) => { + return { Name: x.metadata?.name || `` }; + }), + ...serviceAccounts.body.items.map((x) => { + return { Name: x.metadata?.name || `` }; + }), + ...secrets.body.items.map((x) => { + return { Name: x.metadata?.name || `` }; + }), + ...jobs.body.items.map((x) => { + return { Name: x.metadata?.name || `` }; + }), + ]; } listWorkflow() { throw new Error('Method not implemented.'); @@ -3272,172 +3053,158 @@ class Kubernetes { baseDependencies) { return new Promise((result) => result(``)); } - setupWorkflow(buildGuid, buildParameters, + async setupWorkflow(buildGuid, buildParameters, // eslint-disable-next-line no-unused-vars branchName, // eslint-disable-next-line no-unused-vars defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { - try { - this.buildParameters = buildParameters; - const id = buildParameters.retainWorkspace ? cloud_runner_1.default.lockedWorkspace : buildParameters.buildGuid; - this.pvcName = `unity-builder-pvc-${id}`; - this.cleanupCronJobName = `unity-builder-cronjob-${id}`; - this.serviceAccountName = `service-account-${buildParameters.buildGuid}`; - yield kubernetes_storage_1.default.createPersistentVolumeClaim(buildParameters, this.pvcName, this.kubeClient, this.namespace); - yield kubernetes_service_account_1.default.createServiceAccount(this.serviceAccountName, this.namespace, this.kubeClient); - } - catch (error) { - throw error; - } - }); + try { + this.buildParameters = buildParameters; + const id = buildParameters.retainWorkspace ? cloud_runner_1.default.lockedWorkspace : buildParameters.buildGuid; + this.pvcName = `unity-builder-pvc-${id}`; + this.cleanupCronJobName = `unity-builder-cronjob-${id}`; + this.serviceAccountName = `service-account-${buildParameters.buildGuid}`; + await kubernetes_storage_1.default.createPersistentVolumeClaim(buildParameters, this.pvcName, this.kubeClient, this.namespace); + await kubernetes_service_account_1.default.createServiceAccount(this.serviceAccountName, this.namespace, this.kubeClient); + } + catch (error) { + throw error; + } } - runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log('Cloud Runner K8s workflow!'); - // Setup - this.buildGuid = buildGuid; - this.secretName = `build-credentials-${this.buildGuid}`; - this.jobName = `unity-builder-job-${this.buildGuid}`; - this.containerName = `main`; - yield kubernetes_secret_1.default.createSecret(secrets, this.secretName, this.namespace, this.kubeClient); - yield this.createNamespacedJob(commands, image, mountdir, workingdir, environment, secrets); - this.setPodNameAndContainerName(yield Kubernetes.findPodFromJob(this.kubeClient, this.jobName, this.namespace)); - cloud_runner_logger_1.default.log('Watching pod until running'); - yield kubernetes_task_runner_1.default.watchUntilPodRunning(this.kubeClient, this.podName, this.namespace); - let output = ''; - // eslint-disable-next-line no-constant-condition - while (true) { - try { - cloud_runner_logger_1.default.log('Pod running, streaming logs'); - output = yield kubernetes_task_runner_1.default.runTask(this.kubeConfig, this.kubeClient, this.jobName, this.podName, 'main', this.namespace); - const running = yield kubernetes_pods_1.default.IsPodRunning(this.podName, this.namespace, this.kubeClient); - if (!running) { - cloud_runner_logger_1.default.log(`Pod not found, assumed ended!`); - break; - } - else { - cloud_runner_logger_1.default.log('Pod still running, recovering stream...'); - } - yield this.cleanupTaskResources(); - } - catch (error) { - let errorParsed; - try { - errorParsed = JSON.parse(error); - } - catch (_c) { - errorParsed = error; - } - const reason = errorParsed.reason || ((_b = (_a = errorParsed.response) === null || _a === void 0 ? void 0 : _a.body) === null || _b === void 0 ? void 0 : _b.reason) || ``; - const errorMessage = errorParsed.message || reason; - const continueStreaming = errorMessage.includes(`dial timeout, backstop`) || - errorMessage.includes(`HttpError: HTTP request failed`) || - errorMessage.includes(`an error occurred when try to find container`) || - errorMessage.includes(`not found`) || - errorMessage.includes(`Not Found`); - if (continueStreaming) { - cloud_runner_logger_1.default.log('Log Stream Container Not Found'); - yield new Promise((resolve) => resolve(5000)); - continue; - } - else { - cloud_runner_logger_1.default.log(`error running k8s workflow ${error}`); - throw error; - } - } - } - return output; - } - catch (error) { - cloud_runner_logger_1.default.log('Running job failed'); - core.error(JSON.stringify(error, undefined, 4)); - yield this.cleanupTaskResources(); - throw error; - } - }); - } - createNamespacedJob(commands, image, mountdir, workingdir, environment, secrets) { - return __awaiter(this, void 0, void 0, function* () { - for (let index = 0; index < 3; index++) { + async runTaskInWorkflow(buildGuid, image, commands, mountdir, workingdir, environment, secrets) { + try { + cloud_runner_logger_1.default.log('Cloud Runner K8s workflow!'); + // Setup + this.buildGuid = buildGuid; + this.secretName = `build-credentials-${this.buildGuid}`; + this.jobName = `unity-builder-job-${this.buildGuid}`; + this.containerName = `main`; + await kubernetes_secret_1.default.createSecret(secrets, this.secretName, this.namespace, this.kubeClient); + await this.createNamespacedJob(commands, image, mountdir, workingdir, environment, secrets); + this.setPodNameAndContainerName(await Kubernetes.findPodFromJob(this.kubeClient, this.jobName, this.namespace)); + cloud_runner_logger_1.default.log('Watching pod until running'); + await kubernetes_task_runner_1.default.watchUntilPodRunning(this.kubeClient, this.podName, this.namespace); + let output = ''; + // eslint-disable-next-line no-constant-condition + while (true) { try { - const jobSpec = kubernetes_job_spec_factory_1.default.getJobSpec(commands, image, mountdir, workingdir, environment, secrets, this.buildGuid, this.buildParameters, this.secretName, this.pvcName, this.jobName, k8s); - yield new Promise((promise) => setTimeout(promise, 15000)); - yield this.kubeClientBatch.createNamespacedJob(this.namespace, jobSpec); - cloud_runner_logger_1.default.log(`Build job created`); - yield new Promise((promise) => setTimeout(promise, 5000)); - cloud_runner_logger_1.default.log('Job created'); - return; + cloud_runner_logger_1.default.log('Pod running, streaming logs'); + output = await kubernetes_task_runner_1.default.runTask(this.kubeConfig, this.kubeClient, this.jobName, this.podName, 'main', this.namespace); + const running = await kubernetes_pods_1.default.IsPodRunning(this.podName, this.namespace, this.kubeClient); + if (!running) { + cloud_runner_logger_1.default.log(`Pod not found, assumed ended!`); + break; + } + else { + cloud_runner_logger_1.default.log('Pod still running, recovering stream...'); + } + await this.cleanupTaskResources(); } catch (error) { - cloud_runner_logger_1.default.log(`Error occured creating job: ${error}`); - throw error; + let errorParsed; + try { + errorParsed = JSON.parse(error); + } + catch { + errorParsed = error; + } + const reason = errorParsed.reason || errorParsed.response?.body?.reason || ``; + const errorMessage = errorParsed.message || reason; + const continueStreaming = errorMessage.includes(`dial timeout, backstop`) || + errorMessage.includes(`HttpError: HTTP request failed`) || + errorMessage.includes(`an error occurred when try to find container`) || + errorMessage.includes(`not found`) || + errorMessage.includes(`Not Found`); + if (continueStreaming) { + cloud_runner_logger_1.default.log('Log Stream Container Not Found'); + await new Promise((resolve) => resolve(5000)); + continue; + } + else { + cloud_runner_logger_1.default.log(`error running k8s workflow ${error}`); + throw error; + } } } - }); + return output; + } + catch (error) { + cloud_runner_logger_1.default.log('Running job failed'); + core.error(JSON.stringify(error, undefined, 4)); + await this.cleanupTaskResources(); + throw error; + } + } + async createNamespacedJob(commands, image, mountdir, workingdir, environment, secrets) { + for (let index = 0; index < 3; index++) { + try { + const jobSpec = kubernetes_job_spec_factory_1.default.getJobSpec(commands, image, mountdir, workingdir, environment, secrets, this.buildGuid, this.buildParameters, this.secretName, this.pvcName, this.jobName, k8s); + await new Promise((promise) => setTimeout(promise, 15000)); + await this.kubeClientBatch.createNamespacedJob(this.namespace, jobSpec); + cloud_runner_logger_1.default.log(`Build job created`); + await new Promise((promise) => setTimeout(promise, 5000)); + cloud_runner_logger_1.default.log('Job created'); + return; + } + catch (error) { + cloud_runner_logger_1.default.log(`Error occured creating job: ${error}`); + throw error; + } + } } setPodNameAndContainerName(pod) { - var _a, _b, _c; - this.podName = ((_a = pod.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; - this.containerName = ((_c = (_b = pod.status) === null || _b === void 0 ? void 0 : _b.containerStatuses) === null || _c === void 0 ? void 0 : _c[0].name) || ''; + this.podName = pod.metadata?.name || ''; + this.containerName = pod.status?.containerStatuses?.[0].name || ''; } - cleanupTaskResources() { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log('cleaning up'); - try { - yield this.kubeClientBatch.deleteNamespacedJob(this.jobName, this.namespace); - yield this.kubeClient.deleteNamespacedPod(this.podName, this.namespace); + async cleanupTaskResources() { + cloud_runner_logger_1.default.log('cleaning up'); + try { + await this.kubeClientBatch.deleteNamespacedJob(this.jobName, this.namespace); + await this.kubeClient.deleteNamespacedPod(this.podName, this.namespace); + } + catch (error) { + cloud_runner_logger_1.default.log(`Failed to cleanup`); + if (error.response.body.reason !== `NotFound`) { + cloud_runner_logger_1.default.log(`Wasn't a not found error: ${error.response.body.reason}`); + throw error; } - catch (error) { - cloud_runner_logger_1.default.log(`Failed to cleanup`); - if (error.response.body.reason !== `NotFound`) { - cloud_runner_logger_1.default.log(`Wasn't a not found error: ${error.response.body.reason}`); - throw error; - } - } - try { - yield this.kubeClient.deleteNamespacedSecret(this.secretName, this.namespace); - } - catch (error) { - cloud_runner_logger_1.default.log(`Failed to cleanup secret`); - cloud_runner_logger_1.default.log(error.response.body.reason); - } - cloud_runner_logger_1.default.log('cleaned up Secret, Job and Pod'); - cloud_runner_logger_1.default.log('cleaning up finished'); - }); + } + try { + await this.kubeClient.deleteNamespacedSecret(this.secretName, this.namespace); + } + catch (error) { + cloud_runner_logger_1.default.log(`Failed to cleanup secret`); + cloud_runner_logger_1.default.log(error.response.body.reason); + } + cloud_runner_logger_1.default.log('cleaned up Secret, Job and Pod'); + cloud_runner_logger_1.default.log('cleaning up finished'); } - cleanupWorkflow(buildGuid, buildParameters, + async cleanupWorkflow(buildGuid, buildParameters, // eslint-disable-next-line no-unused-vars branchName, // eslint-disable-next-line no-unused-vars defaultSecretsArray) { - return __awaiter(this, void 0, void 0, function* () { - if (buildParameters.retainWorkspace) { - return; - } - cloud_runner_logger_1.default.log(`deleting PVC`); - try { - yield this.kubeClient.deleteNamespacedPersistentVolumeClaim(this.pvcName, this.namespace); - yield this.kubeClient.deleteNamespacedServiceAccount(this.serviceAccountName, this.namespace); - cloud_runner_logger_1.default.log('cleaned up PVC and Service Account'); - } - catch (error) { - cloud_runner_logger_1.default.log(`Cleanup failed ${JSON.stringify(error, undefined, 4)}`); - throw error; - } - }); + if (buildParameters.retainWorkspace) { + return; + } + cloud_runner_logger_1.default.log(`deleting PVC`); + try { + await this.kubeClient.deleteNamespacedPersistentVolumeClaim(this.pvcName, this.namespace); + await this.kubeClient.deleteNamespacedServiceAccount(this.serviceAccountName, this.namespace); + cloud_runner_logger_1.default.log('cleaned up PVC and Service Account'); + } + catch (error) { + cloud_runner_logger_1.default.log(`Cleanup failed ${JSON.stringify(error, undefined, 4)}`); + throw error; + } } - static findPodFromJob(kubeClient, jobName, namespace) { - return __awaiter(this, void 0, void 0, function* () { - const namespacedPods = yield kubeClient.listNamespacedPod(namespace); - const pod = namespacedPods.body.items.find((x) => { var _a, _b; return ((_b = (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b['job-name']) === jobName; }); - if (pod === undefined) { - throw new Error("pod with job-name label doesn't exist"); - } - return pod; - }); + static async findPodFromJob(kubeClient, jobName, namespace) { + const namespacedPods = await kubeClient.listNamespacedPod(namespace); + const pod = namespacedPods.body.items.find((x) => x.metadata?.labels?.['job-name'] === jobName); + if (pod === undefined) { + throw new Error("pod with job-name label doesn't exist"); + } + return pod; } } exports["default"] = Kubernetes; @@ -3605,33 +3372,21 @@ exports["default"] = KubernetesJobSpecFactory; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); class KubernetesPods { - static IsPodRunning(podName, namespace, kubeClient) { - var _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - const pods = (yield kubeClient.listNamespacedPod(namespace)).body.items.filter((x) => { var _a; return podName === ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name); }); - const running = pods.length > 0 && (((_a = pods[0].status) === null || _a === void 0 ? void 0 : _a.phase) === `Running` || ((_b = pods[0].status) === null || _b === void 0 ? void 0 : _b.phase) === `Pending`); - const phase = ((_d = (_c = pods[0]) === null || _c === void 0 ? void 0 : _c.status) === null || _d === void 0 ? void 0 : _d.phase) || 'undefined status'; - cloud_runner_logger_1.default.log(`Getting pod status: ${phase}`); - if (phase === `Failed`) { - throw new Error(`K8s pod failed`); - } - return running; - }); + static async IsPodRunning(podName, namespace, kubeClient) { + const pods = (await kubeClient.listNamespacedPod(namespace)).body.items.filter((x) => podName === x.metadata?.name); + const running = pods.length > 0 && (pods[0].status?.phase === `Running` || pods[0].status?.phase === `Pending`); + const phase = pods[0]?.status?.phase || 'undefined status'; + cloud_runner_logger_1.default.log(`Getting pod status: ${phase}`); + if (phase === `Failed`) { + throw new Error(`K8s pod failed`); + } + return running; } } exports["default"] = KubernetesPods; @@ -3663,53 +3418,41 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const k8s = __importStar(__nccwpck_require__(89679)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); -const base64 = __nccwpck_require__(85848); +const base64 = __importStar(__nccwpck_require__(85848)); class KubernetesSecret { - static createSecret(secrets, secretName, namespace, kubeClient) { - return __awaiter(this, void 0, void 0, function* () { - try { - const secret = new k8s.V1Secret(); - secret.apiVersion = 'v1'; - secret.kind = 'Secret'; - secret.type = 'Opaque'; - secret.metadata = { - name: secretName, - }; - secret.data = {}; - for (const buildSecret of secrets) { - secret.data[buildSecret.ParameterKey] = base64.encode(buildSecret.ParameterValue); - } - cloud_runner_logger_1.default.log(`Creating secret: ${secretName}`); - const existingSecrets = yield kubeClient.listNamespacedSecret(namespace); - const mappedSecrets = existingSecrets.body.items.map((x) => { - var _a; - return ((_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name) || `no name`; - }); - cloud_runner_logger_1.default.log(`ExistsAlready: ${mappedSecrets.includes(secretName)} SecretsCount: ${mappedSecrets.length}`); - yield new Promise((promise) => setTimeout(promise, 15000)); - yield kubeClient.createNamespacedSecret(namespace, secret); - cloud_runner_logger_1.default.log('Created secret'); + static async createSecret(secrets, secretName, namespace, kubeClient) { + try { + const secret = new k8s.V1Secret(); + secret.apiVersion = 'v1'; + secret.kind = 'Secret'; + secret.type = 'Opaque'; + secret.metadata = { + name: secretName, + }; + secret.data = {}; + for (const buildSecret of secrets) { + secret.data[buildSecret.ParameterKey] = base64.encode(buildSecret.ParameterValue); } - catch (error) { - cloud_runner_logger_1.default.log(`Created secret failed ${error}`); - throw new Error(`Failed to create kubernetes secret`); - } - }); + cloud_runner_logger_1.default.log(`Creating secret: ${secretName}`); + const existingSecrets = await kubeClient.listNamespacedSecret(namespace); + const mappedSecrets = existingSecrets.body.items.map((x) => { + return x.metadata?.name || `no name`; + }); + cloud_runner_logger_1.default.log(`ExistsAlready: ${mappedSecrets.includes(secretName)} SecretsCount: ${mappedSecrets.length}`); + await new Promise((promise) => setTimeout(promise, 15000)); + await kubeClient.createNamespacedSecret(namespace, secret); + cloud_runner_logger_1.default.log('Created secret'); + } + catch (error) { + cloud_runner_logger_1.default.log(`Created secret failed ${error}`); + throw new Error(`Failed to create kubernetes secret`); + } } } exports["default"] = KubernetesSecret; @@ -3741,29 +3484,18 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); const k8s = __importStar(__nccwpck_require__(89679)); class KubernetesServiceAccount { - static createServiceAccount(serviceAccountName, namespace, kubeClient) { - return __awaiter(this, void 0, void 0, function* () { - const serviceAccount = new k8s.V1ServiceAccount(); - serviceAccount.apiVersion = 'v1'; - serviceAccount.kind = 'ServiceAccount'; - serviceAccount.metadata = { - name: serviceAccountName, - }; - serviceAccount.automountServiceAccountToken = false; - return kubeClient.createNamespacedServiceAccount(namespace, serviceAccount); - }); + static async createServiceAccount(serviceAccountName, namespace, kubeClient) { + const serviceAccount = new k8s.V1ServiceAccount(); + serviceAccount.apiVersion = 'v1'; + serviceAccount.kind = 'ServiceAccount'; + serviceAccount.metadata = { + name: serviceAccountName, + }; + serviceAccount.automountServiceAccountToken = false; + return kubeClient.createNamespacedServiceAccount(namespace, serviceAccount); } } exports["default"] = KubernetesServiceAccount; @@ -3795,15 +3527,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -3814,92 +3537,80 @@ const k8s = __importStar(__nccwpck_require__(89679)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const github_1 = __importDefault(__nccwpck_require__(83654)); class KubernetesStorage { - static createPersistentVolumeClaim(buildParameters, pvcName, kubeClient, namespace) { - return __awaiter(this, void 0, void 0, function* () { - if (buildParameters.kubeVolume !== ``) { - cloud_runner_logger_1.default.log(`Kube Volume was input was set ${buildParameters.kubeVolume} overriding ${pvcName}`); - pvcName = buildParameters.kubeVolume; - return; + static async createPersistentVolumeClaim(buildParameters, pvcName, kubeClient, namespace) { + if (buildParameters.kubeVolume !== ``) { + cloud_runner_logger_1.default.log(`Kube Volume was input was set ${buildParameters.kubeVolume} overriding ${pvcName}`); + pvcName = buildParameters.kubeVolume; + return; + } + const allPvc = (await kubeClient.listNamespacedPersistentVolumeClaim(namespace)).body.items; + const pvcList = allPvc.map((x) => x.metadata?.name); + cloud_runner_logger_1.default.log(`Current PVCs in namespace ${namespace}`); + cloud_runner_logger_1.default.log(JSON.stringify(pvcList, undefined, 4)); + if (pvcList.includes(pvcName)) { + cloud_runner_logger_1.default.log(`pvc ${pvcName} already exists`); + if (github_1.default.githubInputEnabled) { + core.setOutput('volume', pvcName); } - const allPvc = (yield kubeClient.listNamespacedPersistentVolumeClaim(namespace)).body.items; - const pvcList = allPvc.map((x) => { var _a; return (_a = x.metadata) === null || _a === void 0 ? void 0 : _a.name; }); - cloud_runner_logger_1.default.log(`Current PVCs in namespace ${namespace}`); - cloud_runner_logger_1.default.log(JSON.stringify(pvcList, undefined, 4)); - if (pvcList.includes(pvcName)) { - cloud_runner_logger_1.default.log(`pvc ${pvcName} already exists`); - if (github_1.default.githubInputEnabled) { - core.setOutput('volume', pvcName); - } - return; - } - cloud_runner_logger_1.default.log(`Creating PVC ${pvcName} (does not exist)`); - const result = yield KubernetesStorage.createPVC(pvcName, buildParameters, kubeClient, namespace); - yield KubernetesStorage.handleResult(result, kubeClient, namespace, pvcName); - }); + return; + } + cloud_runner_logger_1.default.log(`Creating PVC ${pvcName} (does not exist)`); + const result = await KubernetesStorage.createPVC(pvcName, buildParameters, kubeClient, namespace); + await KubernetesStorage.handleResult(result, kubeClient, namespace, pvcName); } - static getPVCPhase(kubeClient, name, namespace) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - try { - return (_a = (yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body.status) === null || _a === void 0 ? void 0 : _a.phase; - } - catch (error) { - core.error('Failed to get PVC phase'); - core.error(JSON.stringify(error, undefined, 4)); - throw error; - } - }); + static async getPVCPhase(kubeClient, name, namespace) { + try { + return (await kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body.status?.phase; + } + catch (error) { + core.error('Failed to get PVC phase'); + core.error(JSON.stringify(error, undefined, 4)); + throw error; + } } - static watchUntilPVCNotPending(kubeClient, name, namespace) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`watch Until PVC Not Pending ${name} ${namespace}`); - cloud_runner_logger_1.default.log(`${yield this.getPVCPhase(kubeClient, name, namespace)}`); - yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { - return (yield this.getPVCPhase(kubeClient, name, namespace)) === 'Pending'; - }), { - timeout: 750000, - intervalBetweenAttempts: 15000, - }); - } - catch (error) { - core.error('Failed to watch PVC'); - core.error(error.toString()); - core.error(`PVC Body: ${JSON.stringify((yield kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body, undefined, 4)}`); - throw error; - } - }); + static async watchUntilPVCNotPending(kubeClient, name, namespace) { + try { + cloud_runner_logger_1.default.log(`watch Until PVC Not Pending ${name} ${namespace}`); + cloud_runner_logger_1.default.log(`${await this.getPVCPhase(kubeClient, name, namespace)}`); + await async_wait_until_1.default(async () => { + return (await this.getPVCPhase(kubeClient, name, namespace)) === 'Pending'; + }, { + timeout: 750000, + intervalBetweenAttempts: 15000, + }); + } + catch (error) { + core.error('Failed to watch PVC'); + core.error(error.toString()); + core.error(`PVC Body: ${JSON.stringify((await kubeClient.readNamespacedPersistentVolumeClaim(name, namespace)).body, undefined, 4)}`); + throw error; + } } - static createPVC(pvcName, buildParameters, kubeClient, namespace) { - return __awaiter(this, void 0, void 0, function* () { - const pvc = new k8s.V1PersistentVolumeClaim(); - pvc.apiVersion = 'v1'; - pvc.kind = 'PersistentVolumeClaim'; - pvc.metadata = { - name: pvcName, - }; - pvc.spec = { - accessModes: ['ReadWriteOnce'], - storageClassName: buildParameters.kubeStorageClass === '' ? 'standard' : buildParameters.kubeStorageClass, - resources: { - requests: { - storage: buildParameters.kubeVolumeSize, - }, + static async createPVC(pvcName, buildParameters, kubeClient, namespace) { + const pvc = new k8s.V1PersistentVolumeClaim(); + pvc.apiVersion = 'v1'; + pvc.kind = 'PersistentVolumeClaim'; + pvc.metadata = { + name: pvcName, + }; + pvc.spec = { + accessModes: ['ReadWriteOnce'], + storageClassName: buildParameters.kubeStorageClass === '' ? 'standard' : buildParameters.kubeStorageClass, + resources: { + requests: { + storage: buildParameters.kubeVolumeSize, }, - }; - const result = yield kubeClient.createNamespacedPersistentVolumeClaim(namespace, pvc); - return result; - }); + }, + }; + const result = await kubeClient.createNamespacedPersistentVolumeClaim(namespace, pvc); + return result; } - static handleResult(result, kubeClient, namespace, pvcName) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const name = ((_a = result.body.metadata) === null || _a === void 0 ? void 0 : _a.name) || ''; - cloud_runner_logger_1.default.log(`PVC ${name} created`); - yield this.watchUntilPVCNotPending(kubeClient, name, namespace); - cloud_runner_logger_1.default.log(`PVC ${name} is ready and not pending`); - core.setOutput('volume', pvcName); - }); + static async handleResult(result, kubeClient, namespace, pvcName) { + const name = result.body.metadata?.name || ''; + cloud_runner_logger_1.default.log(`PVC ${name} created`); + await this.watchUntilPVCNotPending(kubeClient, name, namespace); + cloud_runner_logger_1.default.log(`PVC ${name} is ready and not pending`); + core.setOutput('volume', pvcName); } } exports["default"] = KubernetesStorage; @@ -3931,15 +3642,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -3952,79 +3654,74 @@ const cloud_runner_statics_1 = __nccwpck_require__(90828); const async_wait_until_1 = __importDefault(__nccwpck_require__(41299)); const follow_log_stream_service_1 = __nccwpck_require__(64121); class KubernetesTaskRunner { - static runTask(kubeConfig, kubeClient, jobName, podName, containerName, namespace) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(`Streaming logs from pod: ${podName} container: ${containerName} namespace: ${namespace}`); - const stream = new stream_1.Writable(); - let output = ''; - let didStreamAnyLogs = false; - let shouldReadLogs = true; - let shouldCleanup = true; - stream._write = (chunk, encoding, next) => { - didStreamAnyLogs = true; - let message = chunk.toString().trimRight(`\n`); - message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; - ({ shouldReadLogs, shouldCleanup, output } = follow_log_stream_service_1.FollowLogStreamService.handleIteration(message, shouldReadLogs, shouldCleanup, output)); - next(); - }; - const logOptions = { - follow: true, - pretty: false, - previous: false, - }; - try { - const resultError = yield new Promise((resolve) => new client_node_1.Log(kubeConfig).log(namespace, podName, containerName, stream, resolve, logOptions)); + static async runTask(kubeConfig, kubeClient, jobName, podName, containerName, namespace) { + cloud_runner_logger_1.default.log(`Streaming logs from pod: ${podName} container: ${containerName} namespace: ${namespace}`); + const stream = new stream_1.Writable(); + let output = ''; + let didStreamAnyLogs = false; + let shouldReadLogs = true; + let shouldCleanup = true; + stream._write = (chunk, encoding, next) => { + didStreamAnyLogs = true; + let message = chunk.toString().trimRight(`\n`); + message = `[${cloud_runner_statics_1.CloudRunnerStatics.logPrefix}] ${message}`; + ({ shouldReadLogs, shouldCleanup, output } = follow_log_stream_service_1.FollowLogStreamService.handleIteration(message, shouldReadLogs, shouldCleanup, output)); + next(); + }; + const logOptions = { + follow: true, + pretty: false, + previous: false, + }; + try { + const resultError = await new Promise((resolve) => new client_node_1.Log(kubeConfig).log(namespace, podName, containerName, stream, resolve, logOptions)); + stream.destroy(); + if (resultError) { + throw resultError; + } + if (!didStreamAnyLogs) { + core.error('Failed to stream any logs, listing namespace events, check for an error with the container'); + core.error(JSON.stringify({ + events: (await kubeClient.listNamespacedEvent(namespace)).body.items + .filter((x) => { + return x.involvedObject.name === podName || x.involvedObject.name === jobName; + }) + .map((x) => { + return { + type: x.involvedObject.kind, + name: x.involvedObject.name, + message: x.message, + }; + }), + }, undefined, 4)); + throw new Error(`No logs streamed from k8s`); + } + } + catch (error) { + if (stream) { stream.destroy(); - if (resultError) { - throw resultError; - } - if (!didStreamAnyLogs) { - core.error('Failed to stream any logs, listing namespace events, check for an error with the container'); - core.error(JSON.stringify({ - events: (yield kubeClient.listNamespacedEvent(namespace)).body.items - .filter((x) => { - return x.involvedObject.name === podName || x.involvedObject.name === jobName; - }) - .map((x) => { - return { - type: x.involvedObject.kind, - name: x.involvedObject.name, - message: x.message, - }; - }), - }, undefined, 4)); - throw new Error(`No logs streamed from k8s`); - } } - catch (error) { - if (stream) { - stream.destroy(); - } - throw error; - } - cloud_runner_logger_1.default.log('end of log stream'); - return output; - }); + throw error; + } + cloud_runner_logger_1.default.log('end of log stream'); + return output; } - static watchUntilPodRunning(kubeClient, podName, namespace) { - return __awaiter(this, void 0, void 0, function* () { - let success = false; - cloud_runner_logger_1.default.log(`Watching ${podName} ${namespace}`); - yield async_wait_until_1.default(() => __awaiter(this, void 0, void 0, function* () { - var _a, _b, _c, _d, _e, _f; - const status = yield kubeClient.readNamespacedPodStatus(podName, namespace); - const phase = (_a = status === null || status === void 0 ? void 0 : status.body.status) === null || _a === void 0 ? void 0 : _a.phase; - success = phase === 'Running'; - cloud_runner_logger_1.default.log(`${(_b = status.body.status) === null || _b === void 0 ? void 0 : _b.phase} ${((_d = (_c = status.body.status) === null || _c === void 0 ? void 0 : _c.conditions) === null || _d === void 0 ? void 0 : _d[0].reason) || ''} ${((_f = (_e = status.body.status) === null || _e === void 0 ? void 0 : _e.conditions) === null || _f === void 0 ? void 0 : _f[0].message) || ''}`); - if (success || phase !== 'Pending') - return true; - return false; - }), { - timeout: 2000000, - intervalBetweenAttempts: 15000, - }); - return success; + static async watchUntilPodRunning(kubeClient, podName, namespace) { + let success = false; + cloud_runner_logger_1.default.log(`Watching ${podName} ${namespace}`); + await async_wait_until_1.default(async () => { + const status = await kubeClient.readNamespacedPodStatus(podName, namespace); + const phase = status?.body.status?.phase; + success = phase === 'Running'; + cloud_runner_logger_1.default.log(`${status.body.status?.phase} ${status.body.status?.conditions?.[0].reason || ''} ${status.body.status?.conditions?.[0].message || ''}`); + if (success || phase !== 'Pending') + return true; + return false; + }, { + timeout: 2000000, + intervalBetweenAttempts: 15000, }); + return success; } } exports["default"] = KubernetesTaskRunner; @@ -4037,15 +3734,6 @@ exports["default"] = KubernetesTaskRunner; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -4093,7 +3781,7 @@ class LocalCloudRunner { branchName, // eslint-disable-next-line no-unused-vars defaultSecretsArray) { } - runTaskInWorkflow(buildGuid, image, commands, + async runTaskInWorkflow(buildGuid, image, commands, // eslint-disable-next-line no-unused-vars mountdir, // eslint-disable-next-line no-unused-vars @@ -4102,12 +3790,10 @@ class LocalCloudRunner { environment, // eslint-disable-next-line no-unused-vars secrets) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(image); - cloud_runner_logger_1.default.log(buildGuid); - cloud_runner_logger_1.default.log(commands); - return yield cloud_runner_system_1.CloudRunnerSystem.Run(commands); - }); + cloud_runner_logger_1.default.log(image); + cloud_runner_logger_1.default.log(buildGuid); + cloud_runner_logger_1.default.log(commands); + return await cloud_runner_system_1.CloudRunnerSystem.Run(commands); } } exports["default"] = LocalCloudRunner; @@ -4120,15 +3806,6 @@ exports["default"] = LocalCloudRunner; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -4169,7 +3846,7 @@ class TestCloudRunner { branchName, // eslint-disable-next-line no-unused-vars defaultSecretsArray) { } - runTaskInWorkflow(commands, buildGuid, image, + async runTaskInWorkflow(commands, buildGuid, image, // eslint-disable-next-line no-unused-vars mountdir, // eslint-disable-next-line no-unused-vars @@ -4178,13 +3855,11 @@ class TestCloudRunner { environment, // eslint-disable-next-line no-unused-vars secrets) { - return __awaiter(this, void 0, void 0, function* () { - cloud_runner_logger_1.default.log(image); - cloud_runner_logger_1.default.log(buildGuid); - cloud_runner_logger_1.default.log(commands); - return yield new Promise((result) => { - result(commands); - }); + cloud_runner_logger_1.default.log(image); + cloud_runner_logger_1.default.log(buildGuid); + cloud_runner_logger_1.default.log(commands); + return await new Promise((result) => { + result(commands); }); } } @@ -4204,23 +3879,14 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Caching = void 0; -const console_1 = __nccwpck_require__(96206); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_console_1 = __nccwpck_require__(40027); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cloud_runner_folders_1 = __nccwpck_require__(13527); @@ -4230,138 +3896,128 @@ const remote_client_logger_1 = __nccwpck_require__(59412); const cli_1 = __nccwpck_require__(55651); const cli_functions_repository_1 = __nccwpck_require__(85301); // eslint-disable-next-line github/no-then -const fileExists = (fpath) => __awaiter(void 0, void 0, void 0, function* () { return !!(yield fs_1.default.promises.stat(fpath).catch(() => false)); }); +const fileExists = async (fpath) => !!(await node_fs_1.default.promises.stat(fpath).catch(() => false)); class Caching { - static cachePush() { - return __awaiter(this, void 0, void 0, function* () { - try { - const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); - cloud_runner_1.default.buildParameters = buildParameter; - yield Caching.PushToCache(cli_1.Cli.options['cachePushTo'], cli_1.Cli.options['cachePushFrom'], cli_1.Cli.options['artifactName'] || ''); - } - catch (error) { - cloud_runner_logger_1.default.log(`${error}`); - } - }); + static async cachePush() { + try { + const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); + cloud_runner_1.default.buildParameters = buildParameter; + await Caching.PushToCache(cli_1.Cli.options['cachePushTo'], cli_1.Cli.options['cachePushFrom'], cli_1.Cli.options['artifactName'] || ''); + } + catch (error) { + cloud_runner_logger_1.default.log(`${error}`); + } } - static cachePull() { - return __awaiter(this, void 0, void 0, function* () { - try { - const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); - cloud_runner_1.default.buildParameters = buildParameter; - yield Caching.PullFromCache(cli_1.Cli.options['cachePushFrom'], cli_1.Cli.options['cachePushTo'], cli_1.Cli.options['artifactName'] || ''); - } - catch (error) { - cloud_runner_logger_1.default.log(`${error}`); - } - }); + static async cachePull() { + try { + const buildParameter = JSON.parse(process.env.BUILD_PARAMETERS || '{}'); + cloud_runner_1.default.buildParameters = buildParameter; + await Caching.PullFromCache(cli_1.Cli.options['cachePushFrom'], cli_1.Cli.options['cachePushTo'], cli_1.Cli.options['artifactName'] || ''); + } + catch (error) { + cloud_runner_logger_1.default.log(`${error}`); + } } - static PushToCache(cacheFolder, sourceFolder, cacheArtifactName) { - return __awaiter(this, void 0, void 0, function* () { - cacheArtifactName = cacheArtifactName.replace(' ', ''); - const startPath = process.cwd(); - let compressionSuffix = ''; - if (cloud_runner_1.default.buildParameters.useLz4Compression === true) { - compressionSuffix = `.lz4`; + static async PushToCache(cacheFolder, sourceFolder, cacheArtifactName) { + cacheArtifactName = cacheArtifactName.replace(' ', ''); + const startPath = process.cwd(); + let compressionSuffix = ''; + if (cloud_runner_1.default.buildParameters.useLz4Compression === true) { + compressionSuffix = `.lz4`; + } + cloud_runner_logger_1.default.log(`Compression: ${cloud_runner_1.default.buildParameters.useLz4Compression} ${compressionSuffix}`); + try { + if (!(await fileExists(cacheFolder))) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cacheFolder}`); } - cloud_runner_logger_1.default.log(`Compression: ${cloud_runner_1.default.buildParameters.useLz4Compression} ${compressionSuffix}`); - try { - if (!(yield fileExists(cacheFolder))) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cacheFolder}`); - } - process.chdir(path_1.default.resolve(sourceFolder, '..')); - if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { - cloud_runner_logger_1.default.log(`Hashed cache folder ${yield lfs_hashing_1.LfsHashing.hashAllFiles(sourceFolder)} ${sourceFolder} ${path_1.default.basename(sourceFolder)}`); - } - const contents = yield fs_1.default.promises.readdir(path_1.default.basename(sourceFolder)); - cloud_runner_logger_1.default.log(`There is ${contents.length} files/dir in the source folder ${path_1.default.basename(sourceFolder)}`); - if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { - // await CloudRunnerSystem.Run(`tree -L 2 ./..`); - // await CloudRunnerSystem.Run(`tree -L 2`); - } - if (contents.length === 0) { - cloud_runner_logger_1.default.log(`Did not push source folder to cache because it was empty ${path_1.default.basename(sourceFolder)}`); - process.chdir(`${startPath}`); - return; - } - yield cloud_runner_system_1.CloudRunnerSystem.Run(`tar -cf ${cacheArtifactName}.tar${compressionSuffix} ${path_1.default.basename(sourceFolder)}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`du ${cacheArtifactName}.tar${compressionSuffix}`); - console_1.assert(yield fileExists(`${cacheArtifactName}.tar${compressionSuffix}`), 'cache archive exists'); - console_1.assert(yield fileExists(path_1.default.basename(sourceFolder)), 'source folder exists'); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mv ${cacheArtifactName}.tar${compressionSuffix} ${cacheFolder}`); - remote_client_logger_1.RemoteClientLogger.log(`moved cache entry ${cacheArtifactName} to ${cacheFolder}`); - console_1.assert(yield fileExists(`${path_1.default.join(cacheFolder, cacheArtifactName)}.tar${compressionSuffix}`), 'cache archive exists inside cache folder'); + process.chdir(node_path_1.default.resolve(sourceFolder, '..')); + if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { + cloud_runner_logger_1.default.log(`Hashed cache folder ${await lfs_hashing_1.LfsHashing.hashAllFiles(sourceFolder)} ${sourceFolder} ${node_path_1.default.basename(sourceFolder)}`); } - catch (error) { + const contents = await node_fs_1.default.promises.readdir(node_path_1.default.basename(sourceFolder)); + cloud_runner_logger_1.default.log(`There is ${contents.length} files/dir in the source folder ${node_path_1.default.basename(sourceFolder)}`); + if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { + // await CloudRunnerSystem.Run(`tree -L 2 ./..`); + // await CloudRunnerSystem.Run(`tree -L 2`); + } + if (contents.length === 0) { + cloud_runner_logger_1.default.log(`Did not push source folder to cache because it was empty ${node_path_1.default.basename(sourceFolder)}`); process.chdir(`${startPath}`); - throw error; + return; } + await cloud_runner_system_1.CloudRunnerSystem.Run(`tar -cf ${cacheArtifactName}.tar${compressionSuffix} ${node_path_1.default.basename(sourceFolder)}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`du ${cacheArtifactName}.tar${compressionSuffix}`); + node_console_1.assert(await fileExists(`${cacheArtifactName}.tar${compressionSuffix}`), 'cache archive exists'); + node_console_1.assert(await fileExists(node_path_1.default.basename(sourceFolder)), 'source folder exists'); + await cloud_runner_system_1.CloudRunnerSystem.Run(`mv ${cacheArtifactName}.tar${compressionSuffix} ${cacheFolder}`); + remote_client_logger_1.RemoteClientLogger.log(`moved cache entry ${cacheArtifactName} to ${cacheFolder}`); + node_console_1.assert(await fileExists(`${node_path_1.default.join(cacheFolder, cacheArtifactName)}.tar${compressionSuffix}`), 'cache archive exists inside cache folder'); + } + catch (error) { process.chdir(`${startPath}`); - }); + throw error; + } + process.chdir(`${startPath}`); } - static PullFromCache(cacheFolder, destinationFolder, cacheArtifactName = ``) { - return __awaiter(this, void 0, void 0, function* () { - cacheArtifactName = cacheArtifactName.replace(' ', ''); - let compressionSuffix = ''; - if (cloud_runner_1.default.buildParameters.useLz4Compression === true) { - compressionSuffix = `.lz4`; + static async PullFromCache(cacheFolder, destinationFolder, cacheArtifactName = ``) { + cacheArtifactName = cacheArtifactName.replace(' ', ''); + let compressionSuffix = ''; + if (cloud_runner_1.default.buildParameters.useLz4Compression === true) { + compressionSuffix = `.lz4`; + } + const startPath = process.cwd(); + remote_client_logger_1.RemoteClientLogger.log(`Caching for (lz4 ${compressionSuffix}) ${node_path_1.default.basename(destinationFolder)}`); + try { + if (!(await fileExists(cacheFolder))) { + await node_fs_1.default.promises.mkdir(cacheFolder); } - const startPath = process.cwd(); - remote_client_logger_1.RemoteClientLogger.log(`Caching for (lz4 ${compressionSuffix}) ${path_1.default.basename(destinationFolder)}`); - try { - if (!(yield fileExists(cacheFolder))) { - yield fs_1.default.promises.mkdir(cacheFolder); + if (!(await fileExists(destinationFolder))) { + await node_fs_1.default.promises.mkdir(destinationFolder); + } + const latestInBranch = await (await cloud_runner_system_1.CloudRunnerSystem.Run(`ls -t "${cacheFolder}" | grep .tar${compressionSuffix}$ | head -1`)) + .replace(/\n/g, ``) + .replace(`.tar${compressionSuffix}`, ''); + process.chdir(cacheFolder); + const cacheSelection = cacheArtifactName !== `` && (await fileExists(`${cacheArtifactName}.tar${compressionSuffix}`)) + ? cacheArtifactName + : latestInBranch; + await cloud_runner_logger_1.default.log(`cache key ${cacheArtifactName} selection ${cacheSelection}`); + if (await fileExists(`${cacheSelection}.tar${compressionSuffix}`)) { + const resultsFolder = `results${cloud_runner_1.default.buildParameters.buildGuid}`; + await cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${resultsFolder}`); + remote_client_logger_1.RemoteClientLogger.log(`cache item exists ${cacheFolder}/${cacheSelection}.tar${compressionSuffix}`); + const fullResultsFolder = node_path_1.default.join(cacheFolder, resultsFolder); + await cloud_runner_system_1.CloudRunnerSystem.Run(`tar -xf ${cacheSelection}.tar${compressionSuffix} -C ${fullResultsFolder}`); + remote_client_logger_1.RemoteClientLogger.log(`cache item extracted to ${fullResultsFolder}`); + node_console_1.assert(await fileExists(fullResultsFolder), `cache extraction results folder exists`); + const destinationParentFolder = node_path_1.default.resolve(destinationFolder, '..'); + if (await fileExists(destinationFolder)) { + await node_fs_1.default.promises.rmdir(destinationFolder, { recursive: true }); } - if (!(yield fileExists(destinationFolder))) { - yield fs_1.default.promises.mkdir(destinationFolder); - } - const latestInBranch = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`ls -t "${cacheFolder}" | grep .tar${compressionSuffix}$ | head -1`)) - .replace(/\n/g, ``) - .replace(`.tar${compressionSuffix}`, ''); - process.chdir(cacheFolder); - const cacheSelection = cacheArtifactName !== `` && (yield fileExists(`${cacheArtifactName}.tar${compressionSuffix}`)) - ? cacheArtifactName - : latestInBranch; - yield cloud_runner_logger_1.default.log(`cache key ${cacheArtifactName} selection ${cacheSelection}`); - if (yield fileExists(`${cacheSelection}.tar${compressionSuffix}`)) { - const resultsFolder = `results${cloud_runner_1.default.buildParameters.buildGuid}`; - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${resultsFolder}`); - remote_client_logger_1.RemoteClientLogger.log(`cache item exists ${cacheFolder}/${cacheSelection}.tar${compressionSuffix}`); - const fullResultsFolder = path_1.default.join(cacheFolder, resultsFolder); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`tar -xf ${cacheSelection}.tar${compressionSuffix} -C ${fullResultsFolder}`); - remote_client_logger_1.RemoteClientLogger.log(`cache item extracted to ${fullResultsFolder}`); - console_1.assert(yield fileExists(fullResultsFolder), `cache extraction results folder exists`); - const destinationParentFolder = path_1.default.resolve(destinationFolder, '..'); - if (yield fileExists(destinationFolder)) { - yield fs_1.default.promises.rmdir(destinationFolder, { recursive: true }); - } - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mv "${path_1.default.join(fullResultsFolder, path_1.default.basename(destinationFolder))}" "${destinationParentFolder}"`); - const contents = yield fs_1.default.promises.readdir(path_1.default.join(destinationParentFolder, path_1.default.basename(destinationFolder))); - cloud_runner_logger_1.default.log(`There is ${contents.length} files/dir in the cache pulled contents for ${path_1.default.basename(destinationFolder)}`); - } - else { - remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheArtifactName} doesn't exist ${destinationFolder}`); - if (cacheSelection !== ``) { - remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheArtifactName}.tar${compressionSuffix} doesn't exist ${destinationFolder}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`tree ${cacheFolder}`); - throw new Error(`Failed to get cache item, but cache hit was found: ${cacheSelection}`); - } + await cloud_runner_system_1.CloudRunnerSystem.Run(`mv "${node_path_1.default.join(fullResultsFolder, node_path_1.default.basename(destinationFolder))}" "${destinationParentFolder}"`); + const contents = await node_fs_1.default.promises.readdir(node_path_1.default.join(destinationParentFolder, node_path_1.default.basename(destinationFolder))); + cloud_runner_logger_1.default.log(`There is ${contents.length} files/dir in the cache pulled contents for ${node_path_1.default.basename(destinationFolder)}`); + } + else { + remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheArtifactName} doesn't exist ${destinationFolder}`); + if (cacheSelection !== ``) { + remote_client_logger_1.RemoteClientLogger.logWarning(`cache item ${cacheArtifactName}.tar${compressionSuffix} doesn't exist ${destinationFolder}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`tree ${cacheFolder}`); + throw new Error(`Failed to get cache item, but cache hit was found: ${cacheSelection}`); } } - catch (error) { - process.chdir(startPath); - throw error; - } + } + catch (error) { process.chdir(startPath); - }); + throw error; + } + process.chdir(startPath); } - static handleCachePurging() { - return __awaiter(this, void 0, void 0, function* () { - if (process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined) { - remote_client_logger_1.RemoteClientLogger.log(`purging ${cloud_runner_folders_1.CloudRunnerFolders.purgeRemoteCaching}`); - fs_1.default.promises.rmdir(cloud_runner_folders_1.CloudRunnerFolders.cacheFolder, { recursive: true }); - } - }); + static async handleCachePurging() { + if (process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined) { + remote_client_logger_1.RemoteClientLogger.log(`purging ${cloud_runner_folders_1.CloudRunnerFolders.purgeRemoteCaching}`); + node_fs_1.default.promises.rmdir(cloud_runner_folders_1.CloudRunnerFolders.cacheFolder, { recursive: true }); + } } } __decorate([ @@ -4386,151 +4042,130 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RemoteClient = void 0; -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const cloud_runner_folders_1 = __nccwpck_require__(13527); const caching_1 = __nccwpck_require__(32885); const lfs_hashing_1 = __nccwpck_require__(8915); const remote_client_logger_1 = __nccwpck_require__(59412); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const console_1 = __nccwpck_require__(96206); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); +const node_console_1 = __nccwpck_require__(40027); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cli_functions_repository_1 = __nccwpck_require__(85301); const cloud_runner_system_1 = __nccwpck_require__(99393); const yaml_1 = __importDefault(__nccwpck_require__(44603)); class RemoteClient { - static bootstrapRepository() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull)}`); - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)); - yield RemoteClient.cloneRepoWithoutLFSFiles(); - RemoteClient.replaceLargePackageReferencesWithSharedReferences(); - yield RemoteClient.sizeOfFolder('repo before lfs cache pull', cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)); - const lfsHashes = yield lfs_hashing_1.LfsHashing.createLFSHashFiles(); - if (fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute)) { - remote_client_logger_1.RemoteClientLogger.logWarning(`!Warning!: The Unity library was included in the git repository`); - } - yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute), `${lfsHashes.lfsGuidSum}`); - yield RemoteClient.sizeOfFolder('repo after lfs cache pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - yield RemoteClient.pullLatestLFS(); - yield RemoteClient.sizeOfFolder('repo before lfs git pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - yield caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute), `${lfsHashes.lfsGuidSum}`); - yield caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute)); - yield RemoteClient.sizeOfFolder('repo after library cache pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - yield caching_1.Caching.handleCachePurging(); + static async bootstrapRepository() { + try { + await cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.cacheFolderForCacheKeyFull)}`); + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)); + await RemoteClient.cloneRepoWithoutLFSFiles(); + RemoteClient.replaceLargePackageReferencesWithSharedReferences(); + await RemoteClient.sizeOfFolder('repo before lfs cache pull', cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)); + const lfsHashes = await lfs_hashing_1.LfsHashing.createLFSHashFiles(); + if (node_fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute)) { + remote_client_logger_1.RemoteClientLogger.logWarning(`!Warning!: The Unity library was included in the git repository`); } - catch (error) { - throw error; - } - }); + await caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute), `${lfsHashes.lfsGuidSum}`); + await RemoteClient.sizeOfFolder('repo after lfs cache pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + await RemoteClient.pullLatestLFS(); + await RemoteClient.sizeOfFolder('repo before lfs git pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + await caching_1.Caching.PushToCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute), `${lfsHashes.lfsGuidSum}`); + await caching_1.Caching.PullFromCache(cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryCacheFolderFull), cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.libraryFolderAbsolute)); + await RemoteClient.sizeOfFolder('repo after library cache pull', cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + await caching_1.Caching.handleCachePurging(); + } + catch (error) { + throw error; + } } - static sizeOfFolder(message, folder) { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { - cloud_runner_logger_1.default.log(`Size of ${message}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`du -sh ${folder}`); - } - }); + static async sizeOfFolder(message, folder) { + if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { + cloud_runner_logger_1.default.log(`Size of ${message}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`du -sh ${folder}`); + } } - static cloneRepoWithoutLFSFiles() { - return __awaiter(this, void 0, void 0, function* () { - process.chdir(`${cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - if (cloud_runner_1.default.buildParameters.retainWorkspace && - fs_1.default.existsSync(path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.git`))) { - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute} repo exists - skipping clone - retained workspace mode ${cloud_runner_1.default.buildParameters.retainWorkspace}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git fetch && git reset --hard ${cloud_runner_1.default.buildParameters.gitSha}`); - return; - } - if (fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)) { - remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute} repo exists cleaning up`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); - } - try { - remote_client_logger_1.RemoteClientLogger.log(`Initializing source repository for cloning with caching of LFS files`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global advice.detachedHead false`); - remote_client_logger_1.RemoteClientLogger.log(`Cloning the repository being built:`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process --skip"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git clone -q ${cloud_runner_folders_1.CloudRunnerFolders.targetBuildRepoUrl} ${path_1.default.basename(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs install`); - console_1.assert(fs_1.default.existsSync(`.git`), 'git folder exists'); - remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_1.default.buildParameters.branch}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.branch}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.gitSha}`); - console_1.assert(fs_1.default.existsSync(path_1.default.join(`.git`, `lfs`)), 'LFS folder should not exist before caching'); - remote_client_logger_1.RemoteClientLogger.log(`Checked out ${cloud_runner_1.default.buildParameters.branch}`); - } - catch (error) { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`tree -L 2 ${cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - throw error; - } - }); + static async cloneRepoWithoutLFSFiles() { + process.chdir(`${cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); + if (cloud_runner_1.default.buildParameters.retainWorkspace && + node_fs_1.default.existsSync(node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.git`))) { + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute} repo exists - skipping clone - retained workspace mode ${cloud_runner_1.default.buildParameters.retainWorkspace}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git fetch && git reset --hard ${cloud_runner_1.default.buildParameters.gitSha}`); + return; + } + if (node_fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)) { + remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute} repo exists cleaning up`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`rm -r ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); + } + try { + remote_client_logger_1.RemoteClientLogger.log(`Initializing source repository for cloning with caching of LFS files`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global advice.detachedHead false`); + remote_client_logger_1.RemoteClientLogger.log(`Cloning the repository being built:`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process --skip"`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git clone -q ${cloud_runner_folders_1.CloudRunnerFolders.targetBuildRepoUrl} ${node_path_1.default.basename(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute)}`); + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs install`); + node_console_1.assert(node_fs_1.default.existsSync(`.git`), 'git folder exists'); + remote_client_logger_1.RemoteClientLogger.log(`${cloud_runner_1.default.buildParameters.branch}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.branch}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git checkout ${cloud_runner_1.default.buildParameters.gitSha}`); + node_console_1.assert(node_fs_1.default.existsSync(node_path_1.default.join(`.git`, `lfs`)), 'LFS folder should not exist before caching'); + remote_client_logger_1.RemoteClientLogger.log(`Checked out ${cloud_runner_1.default.buildParameters.branch}`); + } + catch (error) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`tree -L 2 ${cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); + throw error; + } } static replaceLargePackageReferencesWithSharedReferences() { if (cloud_runner_1.default.buildParameters.useSharedLargePackages) { - const filePath = path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.projectPathAbsolute, `Packages/manifest.json`); - let manifest = fs_1.default.readFileSync(filePath, 'utf8'); + const filePath = node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.projectPathAbsolute, `Packages/manifest.json`); + let manifest = node_fs_1.default.readFileSync(filePath, 'utf8'); manifest = manifest.replace(/LargeContent/g, '../../../LargeContent'); - fs_1.default.writeFileSync(filePath, manifest); + node_fs_1.default.writeFileSync(filePath, manifest); if (cloud_runner_1.default.buildParameters.cloudRunnerDebug) { cloud_runner_logger_1.default.log(`Package Manifest`); cloud_runner_logger_1.default.log(manifest); } } } - static pullLatestLFS() { - return __awaiter(this, void 0, void 0, function* () { - process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge -- %f"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process"`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs pull`); - remote_client_logger_1.RemoteClientLogger.log(`pulled latest LFS files`); - console_1.assert(fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute)); - }); + static async pullLatestLFS() { + process.chdir(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.smudge "git-lfs smudge -- %f"`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git config --global filter.lfs.process "git-lfs filter-process"`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs pull`); + remote_client_logger_1.RemoteClientLogger.log(`pulled latest LFS files`); + node_console_1.assert(node_fs_1.default.existsSync(cloud_runner_folders_1.CloudRunnerFolders.lfsFolderAbsolute)); } - static runRemoteClientJob() { - return __awaiter(this, void 0, void 0, function* () { - // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - RemoteClient.handleRetainedWorkspace(); - // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - yield RemoteClient.bootstrapRepository(); - // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - yield RemoteClient.runCustomHookFiles(`before-build`); - // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); - }); + static async runRemoteClientJob() { + // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); + RemoteClient.handleRetainedWorkspace(); + // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); + await RemoteClient.bootstrapRepository(); + // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); + await RemoteClient.runCustomHookFiles(`before-build`); + // await CloudRunnerSystem.Run(`tree -L 2 ${CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute}`); } - static runCustomHookFiles(hookLifecycle) { - return __awaiter(this, void 0, void 0, function* () { - remote_client_logger_1.RemoteClientLogger.log(`RunCustomHookFiles: ${hookLifecycle}`); - const gameCiCustomHooksPath = path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `game-ci`, `hooks`); - const files = fs_1.default.readdirSync(gameCiCustomHooksPath); - for (const file of files) { - const fileContents = fs_1.default.readFileSync(path_1.default.join(gameCiCustomHooksPath, file), `utf8`); - const fileContentsObject = yaml_1.default.parse(fileContents.toString()); - if (fileContentsObject.hook === hookLifecycle) { - remote_client_logger_1.RemoteClientLogger.log(`Active Hook File ${file} \n \n file contents: \n ${fileContents}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(fileContentsObject.commands); - } + static async runCustomHookFiles(hookLifecycle) { + remote_client_logger_1.RemoteClientLogger.log(`RunCustomHookFiles: ${hookLifecycle}`); + const gameCiCustomHooksPath = node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `game-ci`, `hooks`); + const files = node_fs_1.default.readdirSync(gameCiCustomHooksPath); + for (const file of files) { + const fileContents = node_fs_1.default.readFileSync(node_path_1.default.join(gameCiCustomHooksPath, file), `utf8`); + const fileContentsObject = yaml_1.default.parse(fileContents.toString()); + if (fileContentsObject.hook === hookLifecycle) { + remote_client_logger_1.RemoteClientLogger.log(`Active Hook File ${file} \n \n file contents: \n ${fileContents}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(fileContentsObject.commands); } - }); + } } static handleRetainedWorkspace() { if (!cloud_runner_1.default.buildParameters.retainWorkspace) { @@ -4596,25 +4231,6 @@ exports["default"] = CloudRunnerConstants; "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -4623,9 +4239,9 @@ exports.Hook = exports.CloudRunnerCustomHooks = void 0; const __1 = __nccwpck_require__(41359); const yaml_1 = __importDefault(__nccwpck_require__(44603)); const remote_client_logger_1 = __nccwpck_require__(59412); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); -const fs = __importStar(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); // import CloudRunnerLogger from './cloud-runner-logger'; class CloudRunnerCustomHooks { // TODO also accept hooks as yaml files in the repo @@ -4645,12 +4261,7 @@ class CloudRunnerCustomHooks { const experimentHooks = customJobHooks; let output = new Array(); if (experimentHooks && experimentHooks !== '') { - try { - output = yaml_1.default.parse(experimentHooks); - } - catch (error) { - throw error; - } + output = yaml_1.default.parse(experimentHooks); } return output.filter((x) => x.step !== undefined && x.hook !== undefined && x.hook.length > 0); } @@ -4658,13 +4269,13 @@ class CloudRunnerCustomHooks { const results = []; remote_client_logger_1.RemoteClientLogger.log(`GetCustomStepFiles: ${hookLifecycle}`); try { - const gameCiCustomStepsPath = path_1.default.join(process.cwd(), `game-ci`, `hooks`); - const files = fs.readdirSync(gameCiCustomStepsPath); + const gameCiCustomStepsPath = node_path_1.default.join(process.cwd(), `game-ci`, `hooks`); + const files = node_fs_1.default.readdirSync(gameCiCustomStepsPath); for (const file of files) { if (!cloud_runner_options_1.default.customHookFiles.includes(file.replace(`.yaml`, ``))) { continue; } - const fileContents = fs.readFileSync(path_1.default.join(gameCiCustomStepsPath, file), `utf8`); + const fileContents = node_fs_1.default.readFileSync(node_path_1.default.join(gameCiCustomStepsPath, file), `utf8`); const fileContentsObject = CloudRunnerCustomHooks.ParseHooks(fileContents)[0]; if (fileContentsObject.hook.includes(hookLifecycle)) { results.push(fileContentsObject); @@ -4684,9 +4295,9 @@ class CloudRunnerCustomHooks { } object.secrets = object.secrets.map((x) => { return { - ParameterKey: x.name, - EnvironmentVariable: __1.Input.ToEnvVarFormat(x.name), - ParameterValue: x.value, + ParameterKey: x.ParameterKey, + EnvironmentVariable: __1.Input.ToEnvVarFormat(x.ParameterKey), + ParameterValue: x.ParameterValue, }; }); } @@ -4751,15 +4362,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -4770,8 +4372,8 @@ const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const core = __importStar(__nccwpck_require__(42186)); const custom_workflow_1 = __nccwpck_require__(3786); const remote_client_logger_1 = __nccwpck_require__(59412); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const fs = __importStar(__nccwpck_require__(57147)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const input_1 = __importDefault(__nccwpck_require__(91933)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); @@ -4780,14 +4382,14 @@ class CloudRunnerCustomSteps { const results = []; remote_client_logger_1.RemoteClientLogger.log(`GetCustomStepFiles: ${hookLifecycle} CustomStepFiles: ${cloud_runner_options_1.default.customStepFiles}`); try { - const gameCiCustomStepsPath = path_1.default.join(process.cwd(), `game-ci`, `steps`); - const files = fs.readdirSync(gameCiCustomStepsPath); + const gameCiCustomStepsPath = node_path_1.default.join(process.cwd(), `game-ci`, `steps`); + const files = node_fs_1.default.readdirSync(gameCiCustomStepsPath); for (const file of files) { if (!cloud_runner_options_1.default.customStepFiles.includes(file.replace(`.yaml`, ``))) { remote_client_logger_1.RemoteClientLogger.log(`Skipping CustomStepFile: ${file}`); continue; } - const fileContents = fs.readFileSync(path_1.default.join(gameCiCustomStepsPath, file), `utf8`); + const fileContents = node_fs_1.default.readFileSync(node_path_1.default.join(gameCiCustomStepsPath, file), `utf8`); const fileContentsObject = CloudRunnerCustomSteps.ParseSteps(fileContents)[0]; if (fileContentsObject.hook === hookLifecycle) { results.push(fileContentsObject); @@ -4939,7 +4541,6 @@ class CloudRunnerCustomSteps { }); } static ParseSteps(steps) { - var _a; if (steps === '') { return []; } @@ -4953,7 +4554,7 @@ class CloudRunnerCustomSteps { else { for (const secret of step.secrets) { if (secret.ParameterValue === undefined && process.env[secret.EnvironmentVariable] !== undefined) { - if ((_a = cloud_runner_1.default.buildParameters) === null || _a === void 0 ? void 0 : _a.cloudRunnerDebug) { + if (cloud_runner_1.default.buildParameters?.cloudRunnerDebug) { cloud_runner_logger_1.default.log(`Injecting custom step ${step.name} from env var ${secret.ParameterKey}`); } secret.ParameterValue = process.env[secret.ParameterKey] || ``; @@ -4969,39 +4570,35 @@ class CloudRunnerCustomSteps { } return object; } - static RunPostBuildSteps(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - let output = ``; - const steps = [ - ...CloudRunnerCustomSteps.ParseSteps(cloud_runner_1.default.buildParameters.postBuildSteps), - ...CloudRunnerCustomSteps.GetCustomStepsFromFiles(`after`), - ]; - if (steps.length > 0) { - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.startGroup('post build steps'); - output += yield custom_workflow_1.CustomWorkflow.runCustomJob(steps, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.endGroup(); - } - return output; - }); + static async RunPostBuildSteps(cloudRunnerStepState) { + let output = ``; + const steps = [ + ...CloudRunnerCustomSteps.ParseSteps(cloud_runner_1.default.buildParameters.postBuildSteps), + ...CloudRunnerCustomSteps.GetCustomStepsFromFiles(`after`), + ]; + if (steps.length > 0) { + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.startGroup('post build steps'); + output += await custom_workflow_1.CustomWorkflow.runCustomJob(steps, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.endGroup(); + } + return output; } - static RunPreBuildSteps(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - let output = ``; - const steps = [ - ...CloudRunnerCustomSteps.ParseSteps(cloud_runner_1.default.buildParameters.preBuildSteps), - ...CloudRunnerCustomSteps.GetCustomStepsFromFiles(`before`), - ]; - if (steps.length > 0) { - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.startGroup('pre build steps'); - output += yield custom_workflow_1.CustomWorkflow.runCustomJob(steps, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.endGroup(); - } - return output; - }); + static async RunPreBuildSteps(cloudRunnerStepState) { + let output = ``; + const steps = [ + ...CloudRunnerCustomSteps.ParseSteps(cloud_runner_1.default.buildParameters.preBuildSteps), + ...CloudRunnerCustomSteps.GetCustomStepsFromFiles(`before`), + ]; + if (steps.length > 0) { + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.startGroup('pre build steps'); + output += await custom_workflow_1.CustomWorkflow.runCustomJob(steps, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.endGroup(); + } + return output; } } exports.CloudRunnerCustomSteps = CloudRunnerCustomSteps; @@ -5019,7 +4616,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CloudRunnerFolders = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class CloudRunnerFolders { @@ -5029,43 +4626,43 @@ class CloudRunnerFolders { // Only the following paths that do not start a path.join with another "Full" suffixed property need to start with an absolute / static get uniqueCloudRunnerJobFolderAbsolute() { return cloud_runner_1.default.buildParameters && cloud_runner_1.default.buildParameters.retainWorkspace && cloud_runner_1.default.lockedWorkspace - ? path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, cloud_runner_1.default.lockedWorkspace) - : path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, cloud_runner_1.default.buildParameters.buildGuid); + ? node_path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, cloud_runner_1.default.lockedWorkspace) + : node_path_1.default.join(`/`, CloudRunnerFolders.buildVolumeFolder, cloud_runner_1.default.buildParameters.buildGuid); } static get cacheFolderForAllFull() { - return path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder); + return node_path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder); } static get cacheFolderForCacheKeyFull() { - return path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder, cloud_runner_1.default.buildParameters.cacheKey); + return node_path_1.default.join('/', CloudRunnerFolders.buildVolumeFolder, CloudRunnerFolders.cacheFolder, cloud_runner_1.default.buildParameters.cacheKey); } static get builderPathAbsolute() { - return path_1.default.join(cloud_runner_options_1.default.useSharedBuilder + return node_path_1.default.join(cloud_runner_options_1.default.useSharedBuilder ? `/${CloudRunnerFolders.buildVolumeFolder}` : CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute, `builder`); } static get repoPathAbsolute() { - return path_1.default.join(CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute, CloudRunnerFolders.repositoryFolder); + return node_path_1.default.join(CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute, CloudRunnerFolders.repositoryFolder); } static get projectPathAbsolute() { - return path_1.default.join(CloudRunnerFolders.repoPathAbsolute, cloud_runner_1.default.buildParameters.projectPath); + return node_path_1.default.join(CloudRunnerFolders.repoPathAbsolute, cloud_runner_1.default.buildParameters.projectPath); } static get libraryFolderAbsolute() { - return path_1.default.join(CloudRunnerFolders.projectPathAbsolute, `Library`); + return node_path_1.default.join(CloudRunnerFolders.projectPathAbsolute, `Library`); } static get projectBuildFolderAbsolute() { - return path_1.default.join(CloudRunnerFolders.repoPathAbsolute, cloud_runner_1.default.buildParameters.buildPath); + return node_path_1.default.join(CloudRunnerFolders.repoPathAbsolute, cloud_runner_1.default.buildParameters.buildPath); } static get lfsFolderAbsolute() { - return path_1.default.join(CloudRunnerFolders.repoPathAbsolute, `.git`, `lfs`); + return node_path_1.default.join(CloudRunnerFolders.repoPathAbsolute, `.git`, `lfs`); } static get purgeRemoteCaching() { return process.env.PURGE_REMOTE_BUILDER_CACHE !== undefined; } static get lfsCacheFolderFull() { - return path_1.default.join(CloudRunnerFolders.cacheFolderForCacheKeyFull, `lfs`); + return node_path_1.default.join(CloudRunnerFolders.cacheFolderForCacheKeyFull, `lfs`); } static get libraryCacheFolderFull() { - return path_1.default.join(CloudRunnerFolders.cacheFolderForCacheKeyFull, `Library`); + return node_path_1.default.join(CloudRunnerFolders.cacheFolderForCacheKeyFull, `Library`); } static get unityBuilderRepoUrl() { return `https://${cloud_runner_1.default.buildParameters.gitPrivateToken}@github.com/game-ci/unity-builder.git`; @@ -5194,15 +4791,6 @@ exports["default"] = CloudRunnerOptionsReader; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -5241,24 +4829,20 @@ class CloudRunnerQueryOverride { } } } - static queryOverride(query) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.shouldUseOverride(query)) { - throw new Error(`Should not be trying to run override query on ${query}`); - } - return yield generic_input_reader_1.GenericInputReader.Run(formatFunction(cloud_runner_options_1.default.readInputOverrideCommand(), [{ key: 0, value: query }])); - }); + static async queryOverride(query) { + if (!this.shouldUseOverride(query)) { + throw new Error(`Should not be trying to run override query on ${query}`); + } + return await generic_input_reader_1.GenericInputReader.Run(formatFunction(cloud_runner_options_1.default.readInputOverrideCommand(), [{ key: 0, value: query }])); } - static PopulateQueryOverrideInput() { - return __awaiter(this, void 0, void 0, function* () { - const queries = cloud_runner_options_1.default.readInputFromOverrideList().split(','); - CloudRunnerQueryOverride.queryOverrides = new Array(); - for (const element of queries) { - if (CloudRunnerQueryOverride.shouldUseOverride(element)) { - CloudRunnerQueryOverride.queryOverrides[element] = yield CloudRunnerQueryOverride.queryOverride(element); - } + static async PopulateQueryOverrideInput() { + const queries = cloud_runner_options_1.default.readInputFromOverrideList().split(','); + CloudRunnerQueryOverride.queryOverrides = {}; + for (const element of queries) { + if (CloudRunnerQueryOverride.shouldUseOverride(element)) { + CloudRunnerQueryOverride.queryOverrides[element] = await CloudRunnerQueryOverride.queryOverride(element); } - }); + } } } exports["default"] = CloudRunnerQueryOverride; @@ -5267,76 +4851,63 @@ exports["default"] = CloudRunnerQueryOverride; /***/ }), /***/ 99393: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CloudRunnerSystem = void 0; const child_process_1 = __nccwpck_require__(32081); const remote_client_logger_1 = __nccwpck_require__(59412); class CloudRunnerSystem { - static RunAndReadLines(command) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield CloudRunnerSystem.Run(command, false, true); - return result - .split(`\n`) - .map((x) => x.replace(`\r`, ``)) - .filter((x) => x !== ``) - .map((x) => { - const lineValues = x.split(` `); - return lineValues[lineValues.length - 1]; - }); + static async RunAndReadLines(command) { + const result = await CloudRunnerSystem.Run(command, false, true); + return result + .split(`\n`) + .map((x) => x.replace(`\r`, ``)) + .filter((x) => x !== ``) + .map((x) => { + const lineValues = x.split(` `); + return lineValues[lineValues.length - 1]; }); } - static Run(command, suppressError = false, suppressLogs = false) { - return __awaiter(this, void 0, void 0, function* () { - for (const element of command.split(`\n`)) { - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(element); - } + static async Run(command, suppressError = false, suppressLogs = false) { + for (const element of command.split(`\n`)) { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(element); } - return yield new Promise((promise, throwError) => { - let output = ''; - const child = child_process_1.exec(command, (error, stdout, stderr) => { - if (!suppressError && error) { - remote_client_logger_1.RemoteClientLogger.log(error.toString()); - throwError(error); - } - if (stderr) { - const diagnosticOutput = `${stderr.toString()}`; - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.logCliDiagnostic(diagnosticOutput); - } - output += diagnosticOutput; - } - const outputChunk = `${stdout}`; - output += outputChunk; - }); - child.on('close', (code) => { + } + return await new Promise((promise, throwError) => { + let output = ''; + const child = child_process_1.exec(command, (error, stdout, stderr) => { + if (!suppressError && error) { + remote_client_logger_1.RemoteClientLogger.log(error.toString()); + throwError(error); + } + if (stderr) { + const diagnosticOutput = `${stderr.toString()}`; if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(`[${code}]`); + remote_client_logger_1.RemoteClientLogger.logCliDiagnostic(diagnosticOutput); } - if (code !== 0 && !suppressError) { - throwError(output); + output += diagnosticOutput; + } + const outputChunk = `${stdout}`; + output += outputChunk; + }); + child.on('close', (code) => { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(`[${code}]`); + } + if (code !== 0 && !suppressError) { + throwError(output); + } + const outputLines = output.split(`\n`); + for (const element of outputLines) { + if (!suppressLogs) { + remote_client_logger_1.RemoteClientLogger.log(element); } - const outputLines = output.split(`\n`); - for (const element of outputLines) { - if (!suppressLogs) { - remote_client_logger_1.RemoteClientLogger.log(element); - } - } - promise(output); - }); + } + promise(output); }); }); } @@ -5430,67 +5001,52 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LfsHashing = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cloud_runner_folders_1 = __nccwpck_require__(13527); const cloud_runner_system_1 = __nccwpck_require__(99393); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const console_1 = __nccwpck_require__(96206); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_console_1 = __nccwpck_require__(40027); const cli_1 = __nccwpck_require__(55651); const cli_functions_repository_1 = __nccwpck_require__(85301); class LfsHashing { - static createLFSHashFiles() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs ls-files -l | cut -d ' ' -f1 | sort > .lfs-assets-guid`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`md5sum .lfs-assets-guid > .lfs-assets-guid-sum`); - console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid-sum`)); - console_1.assert(fs_1.default.existsSync(`.lfs-assets-guid`)); - const lfsHashes = { - lfsGuid: fs_1.default - .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.lfs-assets-guid`)}`, 'utf8') - .replace(/\n/g, ``), - lfsGuidSum: fs_1.default - .readFileSync(`${path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.lfs-assets-guid-sum`)}`, 'utf8') - .replace(' .lfs-assets-guid', '') - .replace(/\n/g, ``), - }; - return lfsHashes; - } - catch (error) { - throw error; - } - }); + static async createLFSHashFiles() { + try { + await cloud_runner_system_1.CloudRunnerSystem.Run(`git lfs ls-files -l | cut -d ' ' -f1 | sort > .lfs-assets-guid`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`md5sum .lfs-assets-guid > .lfs-assets-guid-sum`); + node_console_1.assert(node_fs_1.default.existsSync(`.lfs-assets-guid-sum`)); + node_console_1.assert(node_fs_1.default.existsSync(`.lfs-assets-guid`)); + const lfsHashes = { + lfsGuid: node_fs_1.default + .readFileSync(`${node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.lfs-assets-guid`)}`, 'utf8') + .replace(/\n/g, ``), + lfsGuidSum: node_fs_1.default + .readFileSync(`${node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.lfs-assets-guid-sum`)}`, 'utf8') + .replace(' .lfs-assets-guid', '') + .replace(/\n/g, ``), + }; + return lfsHashes; + } + catch (error) { + throw error; + } } - static hashAllFiles(folder) { - return __awaiter(this, void 0, void 0, function* () { - const startPath = process.cwd(); - process.chdir(folder); - const result = yield (yield cloud_runner_system_1.CloudRunnerSystem.Run(`find -type f -exec md5sum "{}" + | sort | md5sum`)) - .replace(/\n/g, '') - .split(` `)[0]; - process.chdir(startPath); - return result; - }); + static async hashAllFiles(folder) { + const startPath = process.cwd(); + process.chdir(folder); + const result = await (await cloud_runner_system_1.CloudRunnerSystem.Run(`find -type f -exec md5sum "{}" + | sort | md5sum`)) + .replace(/\n/g, '') + .split(` `)[0]; + process.chdir(startPath); + return result; } - static hash() { - return __awaiter(this, void 0, void 0, function* () { - const folder = cli_1.Cli.options['cachePushFrom']; - LfsHashing.hashAllFiles(folder); - }); + static async hash() { + const folder = cli_1.Cli.options['cachePushFrom']; + LfsHashing.hashAllFiles(folder); } } __decorate([ @@ -5506,41 +5062,13 @@ exports.LfsHashing = LfsHashing; "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SharedWorkspaceLocking = void 0; const cloud_runner_system_1 = __nccwpck_require__(99393); -const fs = __importStar(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); @@ -5551,201 +5079,171 @@ class SharedWorkspaceLocking { static get workspaceRoot() { return `${SharedWorkspaceLocking.workspaceBucketRoot}locks/`; } - static GetAllWorkspaces(buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (!(yield SharedWorkspaceLocking.DoesWorkspaceTopLevelExist(buildParametersContext))) { - return []; - } - return (yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/`)).map((x) => x.replace(`/`, ``)); - }); + static async GetAllWorkspaces(buildParametersContext) { + if (!(await SharedWorkspaceLocking.DoesWorkspaceTopLevelExist(buildParametersContext))) { + return []; + } + return (await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/`)).map((x) => x.replace(`/`, ``)); } - static DoesWorkspaceTopLevelExist(buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceBucketRoot}`); - return (yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}`)) - .map((x) => x.replace(`/`, ``)) - .includes(buildParametersContext.cacheKey); - }); + static async DoesWorkspaceTopLevelExist(buildParametersContext) { + await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceBucketRoot}`); + return (await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}`)) + .map((x) => x.replace(`/`, ``)) + .includes(buildParametersContext.cacheKey); } - static GetAllLocks(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (!(yield SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { - return []; - } - return (yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`)) - .map((x) => x.replace(`/`, ``)) - .filter((x) => x.includes(`_lock`)); - }); + static async GetAllLocks(workspace, buildParametersContext) { + if (!(await SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { + return []; + } + return (await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`)) + .map((x) => x.replace(`/`, ``)) + .filter((x) => x.includes(`_lock`)); } - static GetOrCreateLockedWorkspace(workspace, runId, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (!cloud_runner_options_1.default.retainWorkspaces) { - return; - } - try { - if (yield SharedWorkspaceLocking.DoesWorkspaceTopLevelExist(buildParametersContext)) { - const workspaces = yield SharedWorkspaceLocking.GetFreeWorkspaces(buildParametersContext); - cloud_runner_logger_1.default.log(`run agent ${runId} is trying to access a workspace, free: ${JSON.stringify(workspaces)}`); - for (const element of workspaces) { - yield new Promise((promise) => setTimeout(promise, 1000)); - const lockResult = yield SharedWorkspaceLocking.LockWorkspace(element, runId, buildParametersContext); - cloud_runner_logger_1.default.log(`run agent: ${runId} try lock workspace: ${element} result: ${lockResult}`); - if (lockResult) { - cloud_runner_1.default.lockedWorkspace = element; - return true; - } + static async GetOrCreateLockedWorkspace(workspace, runId, buildParametersContext) { + if (!cloud_runner_options_1.default.retainWorkspaces) { + return; + } + try { + if (await SharedWorkspaceLocking.DoesWorkspaceTopLevelExist(buildParametersContext)) { + const workspaces = await SharedWorkspaceLocking.GetFreeWorkspaces(buildParametersContext); + cloud_runner_logger_1.default.log(`run agent ${runId} is trying to access a workspace, free: ${JSON.stringify(workspaces)}`); + for (const element of workspaces) { + await new Promise((promise) => setTimeout(promise, 1000)); + const lockResult = await SharedWorkspaceLocking.LockWorkspace(element, runId, buildParametersContext); + cloud_runner_logger_1.default.log(`run agent: ${runId} try lock workspace: ${element} result: ${lockResult}`); + if (lockResult) { + cloud_runner_1.default.lockedWorkspace = element; + return true; } } } - catch (_a) { - return; + } + catch { + return; + } + const createResult = await SharedWorkspaceLocking.CreateWorkspace(workspace, buildParametersContext, runId); + cloud_runner_logger_1.default.log(`run agent ${runId} didn't find a free workspace so created: ${workspace} createWorkspaceSuccess: ${createResult}`); + return createResult; + } + static async DoesWorkspaceExist(workspace, buildParametersContext) { + return (await SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext)).includes(workspace); + } + static async HasWorkspaceLock(workspace, runId, buildParametersContext) { + if (!(await SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { + return false; + } + const locks = (await SharedWorkspaceLocking.GetAllLocks(workspace, buildParametersContext)) + .map((x) => { + return { + name: x, + timestamp: Number(x.split(`_`)[0]), + }; + }) + .sort((x) => x.timestamp); + const lockMatches = locks.filter((x) => x.name.includes(runId)); + const includesRunLock = lockMatches.length > 0 && locks.indexOf(lockMatches[0]) === 0; + cloud_runner_logger_1.default.log(`Checking has workspace lock, runId: ${runId}, workspace: ${workspace}, success: ${includesRunLock} \n- Num of locks created by Run Agent: ${lockMatches.length} Num of Locks: ${locks.length}, Time ordered index for Run Agent: ${locks.indexOf(lockMatches[0])} \n \n`); + return includesRunLock; + } + static async GetFreeWorkspaces(buildParametersContext) { + const result = []; + const workspaces = await SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext); + for (const element of workspaces) { + await new Promise((promise) => setTimeout(promise, 1500)); + const isLocked = await SharedWorkspaceLocking.IsWorkspaceLocked(element, buildParametersContext); + const isBelowMax = await SharedWorkspaceLocking.IsWorkspaceBelowMax(element, buildParametersContext); + if (!isLocked && isBelowMax) { + result.push(element); + cloud_runner_logger_1.default.log(`workspace ${element} is free`); } - const createResult = yield SharedWorkspaceLocking.CreateWorkspace(workspace, buildParametersContext, runId); - cloud_runner_logger_1.default.log(`run agent ${runId} didn't find a free workspace so created: ${workspace} createWorkspaceSuccess: ${createResult}`); - return createResult; - }); - } - static DoesWorkspaceExist(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - return (yield SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext)).includes(workspace); - }); - } - static HasWorkspaceLock(workspace, runId, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (!(yield SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { - return false; + else { + cloud_runner_logger_1.default.log(`workspace ${element} is NOT free ${!isLocked} ${isBelowMax}`); } - const locks = (yield SharedWorkspaceLocking.GetAllLocks(workspace, buildParametersContext)) - .map((x) => { - return { - name: x, - timestamp: Number(x.split(`_`)[0]), - }; - }) - .sort((x) => x.timestamp); - const lockMatches = locks.filter((x) => x.name.includes(runId)); - const includesRunLock = lockMatches.length > 0 && locks.indexOf(lockMatches[0]) === 0; - cloud_runner_logger_1.default.log(`Checking has workspace lock, runId: ${runId}, workspace: ${workspace}, success: ${includesRunLock} \n- Num of locks created by Run Agent: ${lockMatches.length} Num of Locks: ${locks.length}, Time ordered index for Run Agent: ${locks.indexOf(lockMatches[0])} \n \n`); - return includesRunLock; - }); + } + return result; } - static GetFreeWorkspaces(buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - const workspaces = yield SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext); - for (const element of workspaces) { - yield new Promise((promise) => setTimeout(promise, 1500)); - const isLocked = yield SharedWorkspaceLocking.IsWorkspaceLocked(element, buildParametersContext); - const isBelowMax = yield SharedWorkspaceLocking.IsWorkspaceBelowMax(element, buildParametersContext); - if (!isLocked && isBelowMax) { - result.push(element); - cloud_runner_logger_1.default.log(`workspace ${element} is free`); - } - else { - cloud_runner_logger_1.default.log(`workspace ${element} is NOT free ${!isLocked} ${isBelowMax}`); - } - } - return result; - }); + static async IsWorkspaceBelowMax(workspace, buildParametersContext) { + const workspaces = await SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext); + if (workspace === ``) { + return (workspaces.length < buildParametersContext.maxRetainedWorkspaces || + buildParametersContext.maxRetainedWorkspaces === 0); + } + const ordered = []; + for (const ws of workspaces) { + ordered.push({ + name: ws, + timestamp: await SharedWorkspaceLocking.GetWorkspaceTimestamp(ws, buildParametersContext), + }); + } + ordered.sort((x) => x.timestamp); + const matches = ordered.filter((x) => x.name.includes(workspace)); + const isWorkspaceBelowMax = matches.length > 0 && + (ordered.indexOf(matches[0]) < buildParametersContext.maxRetainedWorkspaces || + buildParametersContext.maxRetainedWorkspaces === 0); + return isWorkspaceBelowMax; } - static IsWorkspaceBelowMax(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - const workspaces = yield SharedWorkspaceLocking.GetAllWorkspaces(buildParametersContext); - if (workspace === ``) { - return (workspaces.length < buildParametersContext.maxRetainedWorkspaces || - buildParametersContext.maxRetainedWorkspaces === 0); - } - const ordered = []; - for (const ws of workspaces) { - ordered.push({ - name: ws, - timestamp: yield SharedWorkspaceLocking.GetWorkspaceTimestamp(ws, buildParametersContext), - }); - } - ordered.sort((x) => x.timestamp); - const matches = ordered.filter((x) => x.name.includes(workspace)); - const isWorkspaceBelowMax = matches.length > 0 && - (ordered.indexOf(matches[0]) < buildParametersContext.maxRetainedWorkspaces || - buildParametersContext.maxRetainedWorkspaces === 0); - return isWorkspaceBelowMax; - }); + static async GetWorkspaceTimestamp(workspace, buildParametersContext) { + if (workspace.split(`_`).length > 0) { + return Number(workspace.split(`_`)[1]); + } + if (!(await SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { + throw new Error("Workspace doesn't exist, can't call get all locks"); + } + return (await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`)) + .map((x) => x.replace(`/`, ``)) + .filter((x) => x.includes(`_workspace`)) + .map((x) => Number(x))[0]; } - static GetWorkspaceTimestamp(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (workspace.split(`_`).length > 0) { - return Number(workspace.split(`_`)[1]); - } - if (!(yield SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { - throw new Error("Workspace doesn't exist, can't call get all locks"); - } - return (yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`)) - .map((x) => x.replace(`/`, ``)) - .filter((x) => x.includes(`_workspace`)) - .map((x) => Number(x))[0]; - }); + static async IsWorkspaceLocked(workspace, buildParametersContext) { + if (!(await SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { + return false; + } + const files = await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`); + const workspaceFileDoesNotExists = files.filter((x) => { + return x.includes(`_workspace`); + }).length === 0; + const lockFilesExist = files.filter((x) => { + return x.includes(`_lock`); + }).length > 0; + return workspaceFileDoesNotExists || lockFilesExist; } - static IsWorkspaceLocked(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - if (!(yield SharedWorkspaceLocking.DoesWorkspaceExist(workspace, buildParametersContext))) { - return false; - } - const files = yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/`); - const workspaceFileDoesNotExists = files.filter((x) => { - return x.includes(`_workspace`); - }).length === 0; - const lockFilesExist = files.filter((x) => { - return x.includes(`_lock`); - }).length > 0; - return workspaceFileDoesNotExists || lockFilesExist; - }); + static async CreateWorkspace(workspace, buildParametersContext, lockId = ``) { + if (lockId !== ``) { + await SharedWorkspaceLocking.LockWorkspace(workspace, lockId, buildParametersContext); + } + const timestamp = Date.now(); + const file = `${timestamp}_workspace`; + node_fs_1.default.writeFileSync(file, ''); + await cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 cp ./${file} ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); + node_fs_1.default.rmSync(file); + const workspaces = await SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/`); + cloud_runner_logger_1.default.log(`All workspaces ${workspaces}`); + if (!(await SharedWorkspaceLocking.IsWorkspaceBelowMax(workspace, buildParametersContext))) { + cloud_runner_logger_1.default.log(`Workspace is below max ${workspaces} ${buildParametersContext.maxRetainedWorkspaces}`); + await SharedWorkspaceLocking.CleanupWorkspace(workspace, buildParametersContext); + return false; + } + return true; } - static CreateWorkspace(workspace, buildParametersContext, lockId = ``) { - return __awaiter(this, void 0, void 0, function* () { - if (lockId !== ``) { - yield SharedWorkspaceLocking.LockWorkspace(workspace, lockId, buildParametersContext); - } - const timestamp = Date.now(); - const file = `${timestamp}_workspace`; - fs.writeFileSync(file, ''); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 cp ./${file} ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); - fs.rmSync(file); - const workspaces = yield SharedWorkspaceLocking.ReadLines(`aws s3 ls ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/`); - cloud_runner_logger_1.default.log(`All workspaces ${workspaces}`); - if (!(yield SharedWorkspaceLocking.IsWorkspaceBelowMax(workspace, buildParametersContext))) { - cloud_runner_logger_1.default.log(`Workspace is below max ${workspaces} ${buildParametersContext.maxRetainedWorkspaces}`); - yield SharedWorkspaceLocking.CleanupWorkspace(workspace, buildParametersContext); - return false; - } - return true; - }); + static async LockWorkspace(workspace, runId, buildParametersContext) { + const file = `${Date.now()}_${runId}_lock`; + node_fs_1.default.writeFileSync(file, ''); + await cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 cp ./${file} ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); + node_fs_1.default.rmSync(file); + return SharedWorkspaceLocking.HasWorkspaceLock(workspace, runId, buildParametersContext); } - static LockWorkspace(workspace, runId, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - const file = `${Date.now()}_${runId}_lock`; - fs.writeFileSync(file, ''); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 cp ./${file} ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); - fs.rmSync(file); - return SharedWorkspaceLocking.HasWorkspaceLock(workspace, runId, buildParametersContext); - }); + static async ReleaseWorkspace(workspace, runId, buildParametersContext) { + const file = (await SharedWorkspaceLocking.GetAllLocks(workspace, buildParametersContext)).filter((x) => x.includes(`_${runId}_lock`)); + cloud_runner_logger_1.default.log(`Deleting lock ${workspace}/${file}`); + cloud_runner_logger_1.default.log(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`); + await cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); + return !SharedWorkspaceLocking.HasWorkspaceLock(workspace, runId, buildParametersContext); } - static ReleaseWorkspace(workspace, runId, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - const file = (yield SharedWorkspaceLocking.GetAllLocks(workspace, buildParametersContext)).filter((x) => x.includes(`_${runId}_lock`)); - cloud_runner_logger_1.default.log(`Deleting lock ${workspace}/${file}`); - cloud_runner_logger_1.default.log(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`); - yield cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace}/${file}`, false, true); - return !SharedWorkspaceLocking.HasWorkspaceLock(workspace, runId, buildParametersContext); - }); + static async CleanupWorkspace(workspace, buildParametersContext) { + await cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace} --recursive`, false, true); } - static CleanupWorkspace(workspace, buildParametersContext) { - return __awaiter(this, void 0, void 0, function* () { - yield cloud_runner_system_1.CloudRunnerSystem.Run(`aws s3 rm ${SharedWorkspaceLocking.workspaceRoot}${buildParametersContext.cacheKey}/${workspace} --recursive`, false, true); - }); - } - static ReadLines(command) { - return __awaiter(this, void 0, void 0, function* () { - return cloud_runner_system_1.CloudRunnerSystem.RunAndReadLines(command); - }); + static async ReadLines(command) { + return cloud_runner_system_1.CloudRunnerSystem.RunAndReadLines(command); } } exports.SharedWorkspaceLocking = SharedWorkspaceLocking; @@ -5818,13 +5316,14 @@ class TaskParameterSerializer { .map((x) => { x.name = TaskParameterSerializer.ToEnvVarFormat(x.name); x.value = `${x.value}`; - if (buildParameters.cloudRunnerDebug && Number(x.name) === Number.NaN) { + if (buildParameters.cloudRunnerDebug && Number.isNaN(Number(x.name))) { core.info(`[ERROR] found a number in task param serializer ${JSON.stringify(x)}`); } return x; }), (item) => item.name); return result; } + // eslint-disable-next-line no-unused-vars static uniqBy(a, key) { const seen = {}; return a.filter(function (item) { @@ -5857,7 +5356,7 @@ class TaskParameterSerializer { } static camelize(string) { return string - .replace(/^\w|[A-Z]|\b\w/g, function (word, index) { + .replace(/(^\w)|([A-Z])|(\b\w)/g, function (word, index) { return index === 0 ? word.toLowerCase() : word.toUpperCase(); }) .replace(/\s+/g, ''); @@ -5927,15 +5426,6 @@ TaskParameterSerializer.blocked = new Set(['0', 'length', 'prototype', '', 'unit "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -5945,12 +5435,11 @@ const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cloud_runner_folders_1 = __nccwpck_require__(13527); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class AsyncWorkflow { - static runAsyncWorkflow(environmentVariables, secrets) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`Cloud Runner is running async mode`); - let output = ''; - output += yield cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, `ubuntu`, `apt-get update > /dev/null + static async runAsyncWorkflow(environmentVariables, secrets) { + try { + cloud_runner_logger_1.default.log(`Cloud Runner is running async mode`); + let output = ''; + output += await cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, `ubuntu`, `apt-get update > /dev/null apt-get install -y curl tar tree npm git git-lfs jq git > /dev/null mkdir /builder printenv @@ -5965,26 +5454,25 @@ unzip awscliv2.zip ./aws/install aws --version node /builder/dist/index.js -m async-workflow`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}/`, environmentVariables, [ - ...secrets, - ...[ - { - ParameterKey: `AWS_ACCESS_KEY_ID`, - EnvironmentVariable: `AWS_ACCESS_KEY_ID`, - ParameterValue: process.env.AWS_ACCESS_KEY_ID || ``, - }, - { - ParameterKey: `AWS_SECRET_ACCESS_KEY`, - EnvironmentVariable: `AWS_SECRET_ACCESS_KEY`, - ParameterValue: process.env.AWS_SECRET_ACCESS_KEY || ``, - }, - ], - ]); - return output; - } - catch (error) { - throw error; - } - }); + ...secrets, + ...[ + { + ParameterKey: `AWS_ACCESS_KEY_ID`, + EnvironmentVariable: `AWS_ACCESS_KEY_ID`, + ParameterValue: process.env.AWS_ACCESS_KEY_ID || ``, + }, + { + ParameterKey: `AWS_SECRET_ACCESS_KEY`, + EnvironmentVariable: `AWS_SECRET_ACCESS_KEY`, + ParameterValue: process.env.AWS_SECRET_ACCESS_KEY || ``, + }, + ], + ]); + return output; + } + catch (error) { + throw error; + } } } exports.AsyncWorkflow = AsyncWorkflow; @@ -6016,15 +5504,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6034,52 +5513,38 @@ const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cloud_runner_folders_1 = __nccwpck_require__(13527); const core = __importStar(__nccwpck_require__(42186)); const cloud_runner_custom_hooks_1 = __nccwpck_require__(58873); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const cloud_runner_custom_steps_1 = __nccwpck_require__(96455); class BuildAutomationWorkflow { - run(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield BuildAutomationWorkflow.standardBuildAutomation(cloudRunnerStepState.image, cloudRunnerStepState); - } - catch (error) { - throw error; - } - }); + async run(cloudRunnerStepState) { + return await BuildAutomationWorkflow.standardBuildAutomation(cloudRunnerStepState.image, cloudRunnerStepState); } - static standardBuildAutomation(baseImage, cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - // TODO accept post and pre build steps as yaml files in the repo - try { - cloud_runner_logger_1.default.log(`Cloud Runner is running standard build automation`); - let output = ''; - output += yield cloud_runner_custom_steps_1.CloudRunnerCustomSteps.RunPreBuildSteps(cloudRunnerStepState); - cloud_runner_logger_1.default.logWithTime('Configurable pre build step(s) time'); - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.startGroup('build'); - cloud_runner_logger_1.default.log(baseImage.toString()); - cloud_runner_logger_1.default.logLine(` `); - cloud_runner_logger_1.default.logLine('Starting build automation job'); - output += yield cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, baseImage.toString(), BuildAutomationWorkflow.BuildWorkflow, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}/`, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); - if (!cloud_runner_1.default.buildParameters.isCliMode) - core.endGroup(); - cloud_runner_logger_1.default.logWithTime('Build time'); - output += yield cloud_runner_custom_steps_1.CloudRunnerCustomSteps.RunPostBuildSteps(cloudRunnerStepState); - cloud_runner_logger_1.default.logWithTime('Configurable post build step(s) time'); - cloud_runner_logger_1.default.log(`Cloud Runner finished running standard build automation`); - return output; - } - catch (error) { - throw error; - } - }); + static async standardBuildAutomation(baseImage, cloudRunnerStepState) { + // TODO accept post and pre build steps as yaml files in the repo + cloud_runner_logger_1.default.log(`Cloud Runner is running standard build automation`); + let output = ''; + output += await cloud_runner_custom_steps_1.CloudRunnerCustomSteps.RunPreBuildSteps(cloudRunnerStepState); + cloud_runner_logger_1.default.logWithTime('Configurable pre build step(s) time'); + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.startGroup('build'); + cloud_runner_logger_1.default.log(baseImage); + cloud_runner_logger_1.default.logLine(` `); + cloud_runner_logger_1.default.logLine('Starting build automation job'); + output += await cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, baseImage.toString(), BuildAutomationWorkflow.BuildWorkflow, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}/`, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); + if (!cloud_runner_1.default.buildParameters.isCliMode) + core.endGroup(); + cloud_runner_logger_1.default.logWithTime('Build time'); + output += await cloud_runner_custom_steps_1.CloudRunnerCustomSteps.RunPostBuildSteps(cloudRunnerStepState); + cloud_runner_logger_1.default.logWithTime('Configurable post build step(s) time'); + cloud_runner_logger_1.default.log(`Cloud Runner finished running standard build automation`); + return output; } static get BuildWorkflow() { const setupHooks = cloud_runner_custom_hooks_1.CloudRunnerCustomHooks.getHooks(cloud_runner_1.default.buildParameters.customJobHooks).filter((x) => x.step.includes(`setup`)); const buildHooks = cloud_runner_custom_hooks_1.CloudRunnerCustomHooks.getHooks(cloud_runner_1.default.buildParameters.customJobHooks).filter((x) => x.step.includes(`build`)); - const builderPath = cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist', `index.js`)); + const builderPath = cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist', `index.js`)); return `apt-get update > /dev/null apt-get install -y curl tar tree npm git-lfs jq git > /dev/null npm i -g n > /dev/null @@ -6099,8 +5564,8 @@ class BuildAutomationWorkflow { } static setupCommands(builderPath) { const commands = `mkdir -p ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute)} && git clone -q -b ${cloud_runner_1.default.buildParameters.cloudRunnerBranch} ${cloud_runner_folders_1.CloudRunnerFolders.unityBuilderRepoUrl} "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute)}" && chmod +x ${builderPath}`; - const retainedWorkspaceCommands = `if [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}" ] && [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.git`))}" ]; then echo "Retained Workspace Already Exists!" ; fi`; - const cloneBuilderCommands = `if [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}" ] && [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, `.git`))}" ]; then echo "Builder Already Exists!"; else ${commands}; fi`; + const retainedWorkspaceCommands = `if [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}" ] && [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.repoPathAbsolute, `.git`))}" ]; then echo "Retained Workspace Already Exists!" ; fi`; + const cloneBuilderCommands = `if [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.uniqueCloudRunnerJobFolderAbsolute)}" ] && [ -e "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, `.git`))}" ]; then echo "Builder Already Exists!"; else ${commands}; fi`; return `export GIT_DISCOVERY_ACROSS_FILESYSTEM=1 echo "downloading game-ci..." ${retainedWorkspaceCommands} @@ -6109,14 +5574,14 @@ class BuildAutomationWorkflow { node ${builderPath} -m remote-cli-pre-build`; } static BuildCommands(builderPath) { - const distFolder = path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist'); - const ubuntuPlatformsFolder = path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist', 'platforms', 'ubuntu'); + const distFolder = node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist'); + const ubuntuPlatformsFolder = node_path_1.default.join(cloud_runner_folders_1.CloudRunnerFolders.builderPathAbsolute, 'dist', 'platforms', 'ubuntu'); return `echo "game ci cloud runner initalized" mkdir -p ${`${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.projectBuildFolderAbsolute)}/build`} cd ${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(cloud_runner_folders_1.CloudRunnerFolders.projectPathAbsolute)} - cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(distFolder, 'default-build-script'))}" "/UnityBuilderAction" - cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(ubuntuPlatformsFolder, 'entrypoint.sh'))}" "/entrypoint.sh" - cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(path_1.default.join(ubuntuPlatformsFolder, 'steps'))}" "/steps" + cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(distFolder, 'default-build-script'))}" "/UnityBuilderAction" + cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(ubuntuPlatformsFolder, 'entrypoint.sh'))}" "/entrypoint.sh" + cp -r "${cloud_runner_folders_1.CloudRunnerFolders.ToLinuxFolder(node_path_1.default.join(ubuntuPlatformsFolder, 'steps'))}" "/steps" chmod -R +x "/entrypoint.sh" chmod -R +x "/steps" echo "game ci start" @@ -6141,15 +5606,6 @@ exports.BuildAutomationWorkflow = BuildAutomationWorkflow; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6160,28 +5616,24 @@ const cloud_runner_folders_1 = __nccwpck_require__(13527); const cloud_runner_custom_steps_1 = __nccwpck_require__(96455); const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); class CustomWorkflow { - static runCustomJobFromString(buildSteps, environmentVariables, secrets) { - return __awaiter(this, void 0, void 0, function* () { - return yield CustomWorkflow.runCustomJob(cloud_runner_custom_steps_1.CloudRunnerCustomSteps.ParseSteps(buildSteps), environmentVariables, secrets); - }); + static async runCustomJobFromString(buildSteps, environmentVariables, secrets) { + return await CustomWorkflow.runCustomJob(cloud_runner_custom_steps_1.CloudRunnerCustomSteps.ParseSteps(buildSteps), environmentVariables, secrets); } - static runCustomJob(buildSteps, environmentVariables, secrets) { - return __awaiter(this, void 0, void 0, function* () { - try { - cloud_runner_logger_1.default.log(`Cloud Runner is running in custom job mode`); - let output = ''; - // if (CloudRunner.buildParameters?.cloudRunnerDebug) { - // CloudRunnerLogger.log(`Custom Job Description \n${JSON.stringify(buildSteps, undefined, 4)}`); - // } - for (const step of buildSteps) { - output += yield cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, step.image, step.commands, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.projectPathAbsolute}/`, environmentVariables, [...secrets, ...step.secrets]); - } - return output; + static async runCustomJob(buildSteps, environmentVariables, secrets) { + try { + cloud_runner_logger_1.default.log(`Cloud Runner is running in custom job mode`); + let output = ''; + // if (CloudRunner.buildParameters?.cloudRunnerDebug) { + // CloudRunnerLogger.log(`Custom Job Description \n${JSON.stringify(buildSteps, undefined, 4)}`); + // } + for (const step of buildSteps) { + output += await cloud_runner_1.default.Provider.runTaskInWorkflow(cloud_runner_1.default.buildParameters.buildGuid, step.image, step.commands, `/${cloud_runner_folders_1.CloudRunnerFolders.buildVolumeFolder}`, `/${cloud_runner_folders_1.CloudRunnerFolders.projectPathAbsolute}/`, environmentVariables, [...secrets, ...step.secrets]); } - catch (error) { - throw error; - } - }); + return output; + } + catch (error) { + throw error; + } } } exports.CustomWorkflow = CustomWorkflow; @@ -6194,15 +5646,6 @@ exports.CustomWorkflow = CustomWorkflow; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6215,21 +5658,19 @@ const cloud_runner_1 = __importDefault(__nccwpck_require__(79144)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const async_workflow_1 = __nccwpck_require__(8231); class WorkflowCompositionRoot { - run(cloudRunnerStepState) { - return __awaiter(this, void 0, void 0, function* () { - try { - if (cloud_runner_options_1.default.asyncCloudRunner) { - return yield async_workflow_1.AsyncWorkflow.runAsyncWorkflow(cloudRunnerStepState.environment, cloudRunnerStepState.secrets); - } - if (cloud_runner_1.default.buildParameters.customJob !== '') { - return yield custom_workflow_1.CustomWorkflow.runCustomJobFromString(cloud_runner_1.default.buildParameters.customJob, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); - } - return yield new build_automation_workflow_1.BuildAutomationWorkflow().run(new cloud_runner_step_state_1.CloudRunnerStepState(cloudRunnerStepState.image.toString(), cloudRunnerStepState.environment, cloudRunnerStepState.secrets)); + async run(cloudRunnerStepState) { + try { + if (cloud_runner_options_1.default.asyncCloudRunner) { + return await async_workflow_1.AsyncWorkflow.runAsyncWorkflow(cloudRunnerStepState.environment, cloudRunnerStepState.secrets); } - catch (error) { - throw error; + if (cloud_runner_1.default.buildParameters.customJob !== '') { + return await custom_workflow_1.CustomWorkflow.runCustomJobFromString(cloud_runner_1.default.buildParameters.customJob, cloudRunnerStepState.environment, cloudRunnerStepState.secrets); } - }); + return await new build_automation_workflow_1.BuildAutomationWorkflow().run(new cloud_runner_step_state_1.CloudRunnerStepState(cloudRunnerStepState.image.toString(), cloudRunnerStepState.environment, cloudRunnerStepState.secrets)); + } + catch (error) { + throw error; + } } } exports.WorkflowCompositionRoot = WorkflowCompositionRoot; @@ -6242,51 +5683,42 @@ exports.WorkflowCompositionRoot = WorkflowCompositionRoot; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const exec_with_error_check_1 = __nccwpck_require__(3161); const image_environment_factory_1 = __importDefault(__nccwpck_require__(25145)); -const fs_1 = __nccwpck_require__(57147); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_fs_1 = __nccwpck_require__(87561); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); class Docker { - static run(image, parameters, silent = false, overrideCommands = '', additionalVariables = [], options = false, entrypointBash = false) { - return __awaiter(this, void 0, void 0, function* () { - let runCommand = ''; - switch (process.platform) { - case 'linux': - runCommand = this.getLinuxCommand(image, parameters, overrideCommands, additionalVariables, entrypointBash); - break; - case 'win32': - runCommand = this.getWindowsCommand(image, parameters); - } - if (options !== false) { - options.silent = silent; - yield exec_with_error_check_1.execWithErrorCheck(runCommand, undefined, options); - } - else { - yield exec_with_error_check_1.execWithErrorCheck(runCommand, undefined, { silent }); - } - }); + static async run(image, parameters, silent = false, overrideCommands = '', additionalVariables = [], + // eslint-disable-next-line unicorn/no-useless-undefined + options = undefined, entrypointBash = false) { + let runCommand = ''; + switch (process.platform) { + case 'linux': + runCommand = this.getLinuxCommand(image, parameters, overrideCommands, additionalVariables, entrypointBash); + break; + case 'win32': + runCommand = this.getWindowsCommand(image, parameters); + } + if (options) { + options.silent = silent; + await exec_with_error_check_1.execWithErrorCheck(runCommand, undefined, options); + } + else { + await exec_with_error_check_1.execWithErrorCheck(runCommand, undefined, { silent }); + } } static getLinuxCommand(image, parameters, overrideCommands = '', additionalVariables = [], entrypointBash = false) { const { workspace, actionFolder, runnerTempPath, sshAgent, gitPrivateToken } = parameters; - const githubHome = path_1.default.join(runnerTempPath, '_github_home'); - if (!fs_1.existsSync(githubHome)) - fs_1.mkdirSync(githubHome); - const githubWorkflow = path_1.default.join(runnerTempPath, '_github_workflow'); - if (!fs_1.existsSync(githubWorkflow)) - fs_1.mkdirSync(githubWorkflow); + const githubHome = node_path_1.default.join(runnerTempPath, '_github_home'); + if (!node_fs_1.existsSync(githubHome)) + node_fs_1.mkdirSync(githubHome); + const githubWorkflow = node_path_1.default.join(runnerTempPath, '_github_workflow'); + if (!node_fs_1.existsSync(githubWorkflow)) + node_fs_1.mkdirSync(githubWorkflow); const commandPrefix = image === `alpine` ? `/bin/sh` : `/bin/bash`; return `docker run \ --workdir /github/workspace \ @@ -6371,39 +5803,28 @@ exports["default"] = ValidationError; /***/ }), /***/ 3161: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.execWithErrorCheck = void 0; const exec_1 = __nccwpck_require__(71514); -function execWithErrorCheck(commandLine, arguments_, options) { - return __awaiter(this, void 0, void 0, function* () { - const result = yield exec_1.getExecOutput(commandLine, arguments_, options); - // Check for errors in the Build Results section - const match = result.stdout.match(/^#\s*Build results\s*#(.*)^Size:/ms); - if (match) { - const buildResults = match[1]; - const errorMatch = buildResults.match(/^Errors:\s*(\d+)$/m); - if (errorMatch && Number.parseInt(errorMatch[1], 10) !== 0) { - throw new Error(`There was an error building the project. Please read the logs for details.`); - } - } - else { +async function execWithErrorCheck(commandLine, arguments_, options) { + const result = await exec_1.getExecOutput(commandLine, arguments_, options); + // Check for errors in the Build Results section + const match = result.stdout.match(/^#\s*Build results\s*#(.*)^Size:/ms); + if (match) { + const buildResults = match[1]; + const errorMatch = buildResults.match(/^Errors:\s*(\d+)$/m); + if (errorMatch && Number.parseInt(errorMatch[1], 10) !== 0) { throw new Error(`There was an error building the project. Please read the logs for details.`); } - return result.exitCode; - }); + } + else { + throw new Error(`There was an error building the project. Please read the logs for details.`); + } + return result.exitCode; } exports.execWithErrorCheck = execWithErrorCheck; @@ -6434,15 +5855,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6481,120 +5893,110 @@ class GitHub { static get repo() { return cloud_runner_options_1.default.githubRepoName; } - static createGitHubCheck(summary) { - return __awaiter(this, void 0, void 0, function* () { - if (!cloud_runner_options_1.default.githubChecks) { - return ``; - } - GitHub.startedDate = new Date().toISOString(); - cloud_runner_logger_1.default.log(`POST /repos/${GitHub.owner}/${GitHub.repo}/check-runs`); - const data = { - owner: GitHub.owner, - repo: GitHub.repo, - name: GitHub.checkName, - // eslint-disable-next-line camelcase - head_sha: GitHub.sha, - status: 'queued', - // eslint-disable-next-line camelcase - external_id: cloud_runner_1.default.buildParameters.buildGuid, - // eslint-disable-next-line camelcase - started_at: GitHub.startedDate, - output: { - title: GitHub.nameReadable, - summary, - text: '', - images: [ - { - alt: 'Game-CI', - // eslint-disable-next-line camelcase - image_url: 'https://game.ci/assets/images/game-ci-brand-logo-wordmark.svg', - }, - ], - }, - }; - const result = yield GitHub.createGitHubCheckRequest(data); - return result.data.id; - }); + static async createGitHubCheck(summary) { + if (!cloud_runner_options_1.default.githubChecks) { + return ``; + } + GitHub.startedDate = new Date().toISOString(); + cloud_runner_logger_1.default.log(`POST /repos/${GitHub.owner}/${GitHub.repo}/check-runs`); + const data = { + owner: GitHub.owner, + repo: GitHub.repo, + name: GitHub.checkName, + // eslint-disable-next-line camelcase + head_sha: GitHub.sha, + status: 'queued', + // eslint-disable-next-line camelcase + external_id: cloud_runner_1.default.buildParameters.buildGuid, + // eslint-disable-next-line camelcase + started_at: GitHub.startedDate, + output: { + title: GitHub.nameReadable, + summary, + text: '', + images: [ + { + alt: 'Game-CI', + // eslint-disable-next-line camelcase + image_url: 'https://game.ci/assets/images/game-ci-brand-logo-wordmark.svg', + }, + ], + }, + }; + const result = await GitHub.createGitHubCheckRequest(data); + return result.data.id; } - static updateGitHubCheck(longDescription, summary, result = `neutral`, status = `in_progress`) { - return __awaiter(this, void 0, void 0, function* () { - if (!cloud_runner_options_1.default.githubChecks) { - return; + static async updateGitHubCheck(longDescription, summary, result = `neutral`, status = `in_progress`) { + if (!cloud_runner_options_1.default.githubChecks) { + return; + } + GitHub.longDescriptionContent += `\n${longDescription}`; + const data = { + owner: GitHub.owner, + repo: GitHub.repo, + // eslint-disable-next-line camelcase + check_run_id: GitHub.checkRunId, + name: GitHub.checkName, + // eslint-disable-next-line camelcase + head_sha: GitHub.sha, + // eslint-disable-next-line camelcase + started_at: GitHub.startedDate, + status, + output: { + title: GitHub.nameReadable, + summary, + text: GitHub.longDescriptionContent, + annotations: [], + }, + }; + if (status === `completed`) { + if (GitHub.endedDate !== undefined) { + GitHub.endedDate = new Date().toISOString(); } - GitHub.longDescriptionContent += `\n${longDescription}`; - const data = { - owner: GitHub.owner, - repo: GitHub.repo, - // eslint-disable-next-line camelcase - check_run_id: GitHub.checkRunId, - name: GitHub.checkName, - // eslint-disable-next-line camelcase - head_sha: GitHub.sha, - // eslint-disable-next-line camelcase - started_at: GitHub.startedDate, - status, - output: { - title: GitHub.nameReadable, - summary, - text: GitHub.longDescriptionContent, - annotations: [], - }, - }; - if (status === `completed`) { - if (GitHub.endedDate !== undefined) { - GitHub.endedDate = new Date().toISOString(); - } - // eslint-disable-next-line camelcase - data.completed_at = GitHub.endedDate || GitHub.startedDate; - data.conclusion = result; - } - if (yield cloud_runner_options_1.default.asyncCloudRunner) { - yield GitHub.runUpdateAsyncChecksWorkflow(data, `update`); - return; - } - yield GitHub.updateGitHubCheckRequest(data); - }); + // eslint-disable-next-line camelcase + data.completed_at = GitHub.endedDate || GitHub.startedDate; + data.conclusion = result; + } + if (await cloud_runner_options_1.default.asyncCloudRunner) { + await GitHub.runUpdateAsyncChecksWorkflow(data, `update`); + return; + } + await GitHub.updateGitHubCheckRequest(data); } - static updateGitHubCheckRequest(data) { - return __awaiter(this, void 0, void 0, function* () { - return yield GitHub.octokitDefaultToken.request(`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`, data); - }); + static async updateGitHubCheckRequest(data) { + return await GitHub.octokitDefaultToken.request(`PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}`, data); } - static createGitHubCheckRequest(data) { - return __awaiter(this, void 0, void 0, function* () { - return yield GitHub.octokitDefaultToken.request(`POST /repos/{owner}/{repo}/check-runs`, data); - }); + static async createGitHubCheckRequest(data) { + return await GitHub.octokitDefaultToken.request(`POST /repos/{owner}/{repo}/check-runs`, data); } - static runUpdateAsyncChecksWorkflow(data, mode) { - return __awaiter(this, void 0, void 0, function* () { - if (mode === `create`) { - throw new Error(`Not supported: only use update`); + static async runUpdateAsyncChecksWorkflow(data, mode) { + if (mode === `create`) { + throw new Error(`Not supported: only use update`); + } + const workflowsResult = await GitHub.octokitDefaultToken.request(`GET /repos/${GitHub.owner}/${GitHub.repo}/actions/workflows`, { + owner: GitHub.owner, + repo: GitHub.repo, + }); + const workflows = workflowsResult.data.workflows; + let selectedId = ``; + for (let index = 0; index < workflowsResult.data.total_count; index++) { + if (workflows[index].name === GitHub.asyncChecksApiWorkflowName) { + selectedId = workflows[index].id; } - const workflowsResult = yield GitHub.octokitDefaultToken.request(`GET /repos/${GitHub.owner}/${GitHub.repo}/actions/workflows`, { - owner: GitHub.owner, - repo: GitHub.repo, - }); - const workflows = workflowsResult.data.workflows; - let selectedId = ``; - for (let index = 0; index < workflowsResult.data.total_count; index++) { - if (workflows[index].name === GitHub.asyncChecksApiWorkflowName) { - selectedId = workflows[index].id; - } - } - if (selectedId === ``) { - core.info(JSON.stringify(workflows)); - throw new Error(`no workflow with name "${GitHub.asyncChecksApiWorkflowName}"`); - } - yield GitHub.octokitPAT.request(`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`, { - owner: GitHub.owner, - repo: GitHub.repo, - // eslint-disable-next-line camelcase - workflow_id: selectedId, - ref: cloud_runner_options_1.default.branch, - inputs: { - checksObject: JSON.stringify({ data, mode }), - }, - }); + } + if (selectedId === ``) { + core.info(JSON.stringify(workflows)); + throw new Error(`no workflow with name "${GitHub.asyncChecksApiWorkflowName}"`); + } + await GitHub.octokitPAT.request(`POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches`, { + owner: GitHub.owner, + repo: GitHub.repo, + // eslint-disable-next-line camelcase + workflow_id: selectedId, + ref: cloud_runner_options_1.default.branch, + inputs: { + checksObject: JSON.stringify({ data, mode }), + }, }); } } @@ -6613,8 +6015,6 @@ exports["default"] = GitHub; Object.defineProperty(exports, "__esModule", ({ value: true })); const test_license_reader_1 = __nccwpck_require__(13963); -class Parameter { -} class ImageEnvironmentFactory { static getEnvVarString(parameters, additionalVariables = []) { const environmentVariables = ImageEnvironmentFactory.getEnvironmentVariables(parameters, additionalVariables); @@ -6708,10 +6108,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); const platform_1 = __importDefault(__nccwpck_require__(9707)); -const input_1 = __importDefault(__nccwpck_require__(91933)); class ImageTag { constructor(imageProperties) { - const { editorVersion = '2019.2.11f1', targetPlatform, customImage, cloudRunnerBuilderPlatform } = imageProperties; + const { editorVersion, targetPlatform, customImage, cloudRunnerBuilderPlatform } = imageProperties; if (!ImageTag.versionPattern.test(editorVersion)) { throw new Error(`Invalid version "${editorVersion}".`); } @@ -6730,7 +6129,7 @@ class ImageTag { this.imageRollingVersion = 1; // Will automatically roll to the latest non-breaking version. } static get versionPattern() { - return /^20\d{2}\.\d\.\w{3,4}|3$/; + return /^(20\d{2}\.\d\.\w{3,4}|3)$/; } static get targetPlatformSuffixes() { return { @@ -6768,7 +6167,7 @@ class ImageTag { case platform_1.default.types.StandaloneWindows: case platform_1.default.types.StandaloneWindows64: // Can only build windows-il2cpp on a windows based system - if (input_1.default.useIL2Cpp && process.platform === 'win32') { + if (process.platform === 'win32') { // Unity versions before 2019.3 do not support il2cpp if (major >= 2020 || (major === 2019 && minor >= 3)) { return windowsIl2cpp; @@ -6781,7 +6180,7 @@ class ImageTag { return windows; case platform_1.default.types.StandaloneLinux64: { // Unity versions before 2019.3 do not support il2cpp - if ((input_1.default.useIL2Cpp && major >= 2020) || (major === 2019 && minor >= 3)) { + if (major >= 2020 || (major === 2019 && minor >= 3)) { return linuxIl2cpp; } return linux; @@ -6895,20 +6294,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ActionYamlReader = void 0; -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const yaml_1 = __importDefault(__nccwpck_require__(44603)); class ActionYamlReader { constructor() { let filename = `action.yml`; - if (!fs_1.default.existsSync(filename)) { - filename = path_1.default.join(__dirname, `..`, filename); + if (!node_fs_1.default.existsSync(filename)) { + filename = node_path_1.default.join(__dirname, `..`, filename); } - this.actionYamlParsed = yaml_1.default.parse(fs_1.default.readFileSync(filename).toString()); + this.actionYamlParsed = yaml_1.default.parse(node_fs_1.default.readFileSync(filename).toString()); } GetActionYamlValue(key) { - var _a; - return ((_a = this.actionYamlParsed.inputs[key]) === null || _a === void 0 ? void 0 : _a.description) || 'No description found in action.yml'; + return this.actionYamlParsed.inputs[key]?.description || 'No description found in action.yml'; } } exports.ActionYamlReader = ActionYamlReader; @@ -6921,15 +6319,6 @@ exports.ActionYamlReader = ActionYamlReader; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -6938,13 +6327,11 @@ exports.GenericInputReader = void 0; const cloud_runner_system_1 = __nccwpck_require__(99393); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); class GenericInputReader { - static Run(command) { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { - return ''; - } - return yield cloud_runner_system_1.CloudRunnerSystem.Run(command, false, true); - }); + static async Run(command) { + if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { + return ''; + } + return await cloud_runner_system_1.CloudRunnerSystem.Run(command, false, true); } } exports.GenericInputReader = GenericInputReader; @@ -6957,50 +6344,37 @@ exports.GenericInputReader = GenericInputReader; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GitRepoReader = void 0; -const console_1 = __nccwpck_require__(96206); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_console_1 = __nccwpck_require__(40027); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const cloud_runner_system_1 = __nccwpck_require__(99393); const cloud_runner_logger_1 = __importDefault(__nccwpck_require__(22855)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); const input_1 = __importDefault(__nccwpck_require__(91933)); class GitRepoReader { - static GetRemote() { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { - return ''; - } - console_1.assert(fs_1.default.existsSync(`.git`)); - const value = (yield cloud_runner_system_1.CloudRunnerSystem.Run(`cd ${input_1.default.projectPath} && git remote -v`, false, true)).replace(/ /g, ``); - cloud_runner_logger_1.default.log(`value ${value}`); - console_1.assert(value.includes('github.com')); - return value.split('github.com')[1].split('.git')[0].slice(1); - }); + static async GetRemote() { + if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { + return ''; + } + node_console_1.assert(node_fs_1.default.existsSync(`.git`)); + const value = (await cloud_runner_system_1.CloudRunnerSystem.Run(`cd ${input_1.default.projectPath} && git remote -v`, false, true)).replace(/ /g, ``); + cloud_runner_logger_1.default.log(`value ${value}`); + node_console_1.assert(value.includes('github.com')); + return value.split('github.com')[1].split('.git')[0].slice(1); } - static GetBranch() { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { - return ''; - } - console_1.assert(fs_1.default.existsSync(`.git`)); - return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`cd ${input_1.default.projectPath} && git branch --show-current`, false, true)) - .split('\n')[0] - .replace(/ /g, ``) - .replace('/head', ''); - }); + static async GetBranch() { + if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { + return ''; + } + node_console_1.assert(node_fs_1.default.existsSync(`.git`)); + return (await cloud_runner_system_1.CloudRunnerSystem.Run(`cd ${input_1.default.projectPath} && git branch --show-current`, false, true)) + .split('\n')[0] + .replace(/ /g, ``) + .replace('/head', ''); } } exports.GitRepoReader = GitRepoReader; @@ -7032,15 +6406,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -7050,26 +6415,24 @@ const cloud_runner_system_1 = __nccwpck_require__(99393); const core = __importStar(__nccwpck_require__(42186)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); class GithubCliReader { - static GetGitHubAuthToken() { - return __awaiter(this, void 0, void 0, function* () { - if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { + static async GetGitHubAuthToken() { + if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { + return ''; + } + try { + const authStatus = await cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status`, true, true); + if (authStatus.includes('You are not logged') || authStatus === '') { return ''; } - try { - const authStatus = yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status`, true, true); - if (authStatus.includes('You are not logged') || authStatus === '') { - return ''; - } - return (yield cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status -t`, false, true)) - .split(`Token: `)[1] - .replace(/ /g, '') - .replace(/\n/g, ''); - } - catch (error) { - core.info(error || 'Failed to get github auth token from gh cli'); - return ''; - } - }); + return (await cloud_runner_system_1.CloudRunnerSystem.Run(`gh auth status -t`, false, true)) + .split(`Token: `)[1] + .replace(/ /g, '') + .replace(/\n/g, ''); + } + catch (error) { + core.info(error || 'Failed to get github auth token from gh cli'); + return ''; + } } } exports.GithubCliReader = GithubCliReader; @@ -7087,16 +6450,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReadLicense = void 0; -const path_1 = __importDefault(__nccwpck_require__(71017)); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const yaml_1 = __importDefault(__nccwpck_require__(44603)); const cloud_runner_options_1 = __importDefault(__nccwpck_require__(96552)); function ReadLicense() { if (cloud_runner_options_1.default.cloudRunnerCluster === 'local') { return ''; } - const pipelineFile = path_1.default.join(__dirname, `.github`, `workflows`, `cloud-runner-k8s-pipeline.yml`); - return fs_1.default.existsSync(pipelineFile) ? yaml_1.default.parse(fs_1.default.readFileSync(pipelineFile, 'utf8')).env.UNITY_LICENSE : ''; + const pipelineFile = node_path_1.default.join(__dirname, `.github`, `workflows`, `cloud-runner-k8s-pipeline.yml`); + return node_fs_1.default.existsSync(pipelineFile) ? yaml_1.default.parse(node_fs_1.default.readFileSync(pipelineFile, 'utf8')).env.UNITY_LICENSE : ''; } exports.ReadLicense = ReadLicense; @@ -7108,17 +6471,36 @@ exports.ReadLicense = ReadLicense; "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); const cli_1 = __nccwpck_require__(55651); const cloud_runner_query_override_1 = __importDefault(__nccwpck_require__(31011)); const platform_1 = __importDefault(__nccwpck_require__(9707)); const github_1 = __importDefault(__nccwpck_require__(83654)); -const core = __nccwpck_require__(42186); +const core = __importStar(__nccwpck_require__(42186)); /** * Input variables specified in workflows using "with" prop. * @@ -7148,7 +6530,6 @@ class Input { if (alternativeQuery !== query && process.env[alternativeQuery] !== undefined) { return process.env[alternativeQuery]; } - return; } static get region() { return Input.getInput('region') || 'eu-west-2'; @@ -7174,9 +6555,7 @@ class Input { else if (Input.getInput(`GitSHA`)) { return Input.getInput(`GitSHA`); } - } - static get useIL2Cpp() { - return Input.getInput(`useIL2Cpp`) || true; + return ''; } static get runNumber() { return Input.getInput('GITHUB_RUN_NUMBER') || '0'; @@ -7192,16 +6571,24 @@ class Input { } static get projectPath() { const input = Input.getInput('projectPath'); - const rawProjectPath = input - ? input - : fs_1.default.existsSync(path_1.default.join('test-project', 'ProjectSettings', 'ProjectVersion.txt')) && - !fs_1.default.existsSync(path_1.default.join('ProjectSettings', 'ProjectVersion.txt')) - ? 'test-project' - : '.'; + let rawProjectPath; + if (input) { + rawProjectPath = input; + } + else if (node_fs_1.default.existsSync(node_path_1.default.join('test-project', 'ProjectSettings', 'ProjectVersion.txt')) && + !node_fs_1.default.existsSync(node_path_1.default.join('ProjectSettings', 'ProjectVersion.txt'))) { + rawProjectPath = 'test-project'; + } + else { + rawProjectPath = '.'; + } return rawProjectPath.replace(/\/$/, ''); } + static get runnerTempPath() { + return Input.getInput('RUNNER_TEMP') || ''; + } static get buildName() { - return Input.getInput('buildName') || this.targetPlatform; + return Input.getInput('buildName') || Input.targetPlatform; } static get buildsPath() { return Input.getInput('buildsPath') || 'build'; @@ -7222,7 +6609,7 @@ class Input { return Input.getInput('version') || ''; } static get androidVersionCode() { - return Input.getInput('androidVersionCode'); + return Input.getInput('androidVersionCode') || ''; } static get androidAppBundle() { core.warning('androidAppBundle is deprecated, please use androidExportType instead'); @@ -7265,7 +6652,7 @@ class Input { return Input.getInput('sshAgent') || ''; } static get gitPrivateToken() { - return core.getInput('gitPrivateToken') || false; + return Input.getInput('gitPrivateToken'); } static get chownFilesTo() { return Input.getInput('chownFilesTo') || ''; @@ -7282,6 +6669,12 @@ class Input { const input = Input.getInput('unityHubVersionOnMac') || ''; return input !== '' ? input : ''; } + static get unitySerial() { + return Input.getInput('UNITY_SERIAL'); + } + static get unityLicense() { + return Input.getInput('UNITY_LICENSE'); + } static ToEnvVarFormat(input) { if (input.toUpperCase() === input) { return input; @@ -7299,27 +6692,16 @@ exports["default"] = Input; /***/ }), /***/ 39364: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); const exec_with_error_check_1 = __nccwpck_require__(3161); class MacBuilder { - static run(actionFolder, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - yield exec_with_error_check_1.execWithErrorCheck('bash', [`${actionFolder}/platforms/mac/entrypoint.sh`], { - silent, - }); + static async run(actionFolder, silent = false) { + await exec_with_error_check_1.execWithErrorCheck('bash', [`${actionFolder}/platforms/mac/entrypoint.sh`], { + silent, }); } } @@ -7333,27 +6715,33 @@ exports["default"] = MacBuilder; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __nccwpck_require__(42186); +const core = __importStar(__nccwpck_require__(42186)); class Output { - static setBuildVersion(buildVersion) { - return __awaiter(this, void 0, void 0, function* () { - yield core.setOutput('buildVersion', buildVersion); - }); + static async setBuildVersion(buildVersion) { + core.setOutput('buildVersion', buildVersion); } - static setAndroidVersionCode(androidVersionCode) { - return __awaiter(this, void 0, void 0, function* () { - yield core.setOutput('androidVersionCode', androidVersionCode); - }); + static async setAndroidVersionCode(androidVersionCode) { + core.setOutput('androidVersionCode', androidVersionCode); } } exports["default"] = Output; @@ -7385,49 +6773,38 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); const core = __importStar(__nccwpck_require__(42186)); const platform_setup_1 = __nccwpck_require__(2014); const validate_windows_1 = __importDefault(__nccwpck_require__(41563)); class PlatformSetup { - static setup(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - PlatformSetup.SetupShared(buildParameters, actionFolder); - switch (process.platform) { - case 'win32': - validate_windows_1.default.validate(buildParameters); - platform_setup_1.SetupWindows.setup(buildParameters); - break; - case 'darwin': - yield platform_setup_1.SetupMac.setup(buildParameters, actionFolder); - break; - // Add other baseOS's here - } - }); + static async setup(buildParameters, actionFolder) { + PlatformSetup.SetupShared(buildParameters, actionFolder); + switch (process.platform) { + case 'win32': + validate_windows_1.default.validate(buildParameters); + platform_setup_1.SetupWindows.setup(buildParameters); + break; + case 'darwin': + await platform_setup_1.SetupMac.setup(buildParameters, actionFolder); + break; + // Add other baseOS's here + } } static SetupShared(buildParameters, actionFolder) { const servicesConfigPath = `${actionFolder}/unity-config/services-config.json`; const servicesConfigPathTemplate = `${servicesConfigPath}.template`; - if (!fs_1.default.existsSync(servicesConfigPathTemplate)) { + if (!node_fs_1.default.existsSync(servicesConfigPathTemplate)) { core.error(`Missing services config ${servicesConfigPathTemplate}`); return; } - let servicesConfig = fs_1.default.readFileSync(servicesConfigPathTemplate).toString(); + let servicesConfig = node_fs_1.default.readFileSync(servicesConfigPathTemplate).toString(); servicesConfig = servicesConfig.replace('%URL%', buildParameters.unityLicensingServer); - fs_1.default.writeFileSync(servicesConfigPath, servicesConfig); + node_fs_1.default.writeFileSync(servicesConfigPath, servicesConfig); platform_setup_1.SetupAndroid.setup(buildParameters); } } @@ -7461,34 +6838,23 @@ exports.SetupAndroid = setup_android_1.default; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); class SetupAndroid { - static setup(buildParameters) { - return __awaiter(this, void 0, void 0, function* () { - const { targetPlatform, androidKeystoreBase64, androidKeystoreName, projectPath } = buildParameters; - if (targetPlatform === 'Android' && androidKeystoreBase64 !== '' && androidKeystoreName !== '') { - SetupAndroid.setupAndroidRun(androidKeystoreBase64, androidKeystoreName, projectPath); - } - }); + static async setup(buildParameters) { + const { targetPlatform, androidKeystoreBase64, androidKeystoreName, projectPath } = buildParameters; + if (targetPlatform === 'Android' && androidKeystoreBase64 !== '' && androidKeystoreName !== '') { + SetupAndroid.setupAndroidRun(androidKeystoreBase64, androidKeystoreName, projectPath); + } } static setupAndroidRun(androidKeystoreBase64, androidKeystoreName, projectPath) { const decodedKeystore = Buffer.from(androidKeystoreBase64, 'base64').toString('binary'); const githubWorkspace = process.env.GITHUB_WORKSPACE || ''; - fs_1.default.writeFileSync(path_1.default.join(githubWorkspace, projectPath, androidKeystoreName), decodedKeystore, 'binary'); + node_fs_1.default.writeFileSync(node_path_1.default.join(githubWorkspace, projectPath, androidKeystoreName), decodedKeystore, 'binary'); } } exports["default"] = SetupAndroid; @@ -7501,78 +6867,63 @@ exports["default"] = SetupAndroid; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const unity_changeset_1 = __nccwpck_require__(4635); +const unity_changeset_1 = __nccwpck_require__(31560); const exec_1 = __nccwpck_require__(71514); const cache_1 = __nccwpck_require__(27799); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); class SetupMac { - static setup(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.editorVersion}/Unity.app/Contents/MacOS/Unity`; - if (!fs_1.default.existsSync(this.unityHubExecPath)) { - yield SetupMac.installUnityHub(buildParameters); - } - if (!fs_1.default.existsSync(unityEditorPath)) { - yield SetupMac.installUnity(buildParameters); - } - yield SetupMac.setEnvironmentVariables(buildParameters, actionFolder); - }); + static async setup(buildParameters, actionFolder) { + const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.editorVersion}/Unity.app/Contents/MacOS/Unity`; + if (!node_fs_1.default.existsSync(this.unityHubExecPath)) { + await SetupMac.installUnityHub(buildParameters); + } + if (!node_fs_1.default.existsSync(unityEditorPath)) { + await SetupMac.installUnity(buildParameters); + } + await SetupMac.setEnvironmentVariables(buildParameters, actionFolder); } - static installUnityHub(buildParameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - // Can't use quotes in the cache package so we need a different path - const unityHubCachePath = `/Applications/Unity\\ Hub.app`; - const targetHubVersion = buildParameters.unityHubVersionOnMac !== '' - ? buildParameters.unityHubVersionOnMac - : yield SetupMac.getLatestUnityHubVersion(); - const restoreKey = `Cache-MacOS-UnityHub@${targetHubVersion}`; - if (buildParameters.cacheUnityInstallationOnMac) { - const cacheId = yield cache_1.restoreCache([unityHubCachePath], restoreKey); - if (cacheId) { - // Cache restored successfully, unity hub is installed now - return; - } + static async installUnityHub(buildParameters, silent = false) { + // Can't use quotes in the cache package so we need a different path + const unityHubCachePath = `/Applications/Unity\\ Hub.app`; + const targetHubVersion = buildParameters.unityHubVersionOnMac !== '' + ? buildParameters.unityHubVersionOnMac + : await SetupMac.getLatestUnityHubVersion(); + const restoreKey = `Cache-MacOS-UnityHub@${targetHubVersion}`; + if (buildParameters.cacheUnityInstallationOnMac) { + const cacheId = await cache_1.restoreCache([unityHubCachePath], restoreKey); + if (cacheId) { + // Cache restored successfully, unity hub is installed now + return; } - const commandSuffix = buildParameters.unityHubVersionOnMac !== '' ? `@${buildParameters.unityHubVersionOnMac}` : ''; - const command = `brew install unity-hub${commandSuffix}`; - // Ignoring return code because the log seems to overflow the internal buffer which triggers - // a false error - const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); - if (errorCode) { - throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); - } - if (buildParameters.cacheUnityInstallationOnMac) { - yield cache_1.saveCache([unityHubCachePath], restoreKey); - } - }); + } + const commandSuffix = buildParameters.unityHubVersionOnMac !== '' ? `@${buildParameters.unityHubVersionOnMac}` : ''; + const command = `brew install unity-hub${commandSuffix}`; + // Ignoring return code because the log seems to overflow the internal buffer which triggers + // a false error + const errorCode = await exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); + if (errorCode) { + throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); + } + if (buildParameters.cacheUnityInstallationOnMac) { + await cache_1.saveCache([unityHubCachePath], restoreKey); + } } /** * Gets the latest version of Unity Hub available on brew * @returns The latest version of Unity Hub available on brew */ - static getLatestUnityHubVersion() { - return __awaiter(this, void 0, void 0, function* () { - // Need to check if the latest version available is the same as the one we have cached - const hubVersionCommand = `/bin/bash -c "brew info unity-hub | grep -o '[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+'"`; - const result = yield exec_1.getExecOutput(hubVersionCommand, undefined, { silent: true }); - if (result.exitCode === 0 && result.stdout !== '') { - return result.stdout; - } - return ''; - }); + static async getLatestUnityHubVersion() { + // Need to check if the latest version available is the same as the one we have cached + const hubVersionCommand = `/bin/bash -c "brew info unity-hub | grep -o '[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+'"`; + const result = await exec_1.getExecOutput(hubVersionCommand, undefined, { silent: true }); + if (result.exitCode === 0 && result.stdout !== '') { + return result.stdout; + } + return ''; } static getModuleParametersForTargetPlatform(targetPlatform) { let moduleArgument = ''; @@ -7597,63 +6948,59 @@ class SetupMac { } return moduleArgument; } - static installUnity(buildParameters, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.editorVersion}`; - const key = `Cache-MacOS-UnityEditor-With-Module-${buildParameters.targetPlatform}@${buildParameters.editorVersion}`; - if (buildParameters.cacheUnityInstallationOnMac) { - const cacheId = yield cache_1.restoreCache([unityEditorPath], key); - if (cacheId) { - // Cache restored successfully, unity editor is installed now - return; - } + static async installUnity(buildParameters, silent = false) { + const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.editorVersion}`; + const key = `Cache-MacOS-UnityEditor-With-Module-${buildParameters.targetPlatform}@${buildParameters.editorVersion}`; + if (buildParameters.cacheUnityInstallationOnMac) { + const cacheId = await cache_1.restoreCache([unityEditorPath], key); + if (cacheId) { + // Cache restored successfully, unity editor is installed now + return; } - const unityChangeset = yield unity_changeset_1.getUnityChangeset(buildParameters.editorVersion); - const moduleArgument = SetupMac.getModuleParametersForTargetPlatform(buildParameters.targetPlatform); - const command = `${this.unityHubExecPath} -- --headless install \ + } + const unityChangeset = await unity_changeset_1.getUnityChangeset(buildParameters.editorVersion); + const moduleArgument = SetupMac.getModuleParametersForTargetPlatform(buildParameters.targetPlatform); + const command = `${this.unityHubExecPath} -- --headless install \ --version ${buildParameters.editorVersion} \ --changeset ${unityChangeset.changeset} \ ${moduleArgument} \ --childModules `; - // Ignoring return code because the log seems to overflow the internal buffer which triggers - // a false error - const errorCode = yield exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); - if (errorCode) { - throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); - } - if (buildParameters.cacheUnityInstallationOnMac) { - yield cache_1.saveCache([unityEditorPath], key); - } - }); + // Ignoring return code because the log seems to overflow the internal buffer which triggers + // a false error + const errorCode = await exec_1.exec(command, undefined, { silent, ignoreReturnCode: true }); + if (errorCode) { + throw new Error(`There was an error installing the Unity Editor. See logs above for details.`); + } + if (buildParameters.cacheUnityInstallationOnMac) { + await cache_1.saveCache([unityEditorPath], key); + } } - static setEnvironmentVariables(buildParameters, actionFolder) { - return __awaiter(this, void 0, void 0, function* () { - // Need to set environment variables from here because we execute - // the scripts on the host for mac - process.env.ACTION_FOLDER = actionFolder; - process.env.UNITY_VERSION = buildParameters.editorVersion; - process.env.UNITY_SERIAL = buildParameters.unitySerial; - process.env.UNITY_LICENSING_SERVER = buildParameters.unityLicensingServer; - process.env.PROJECT_PATH = buildParameters.projectPath; - process.env.BUILD_TARGET = buildParameters.targetPlatform; - process.env.BUILD_NAME = buildParameters.buildName; - process.env.BUILD_PATH = buildParameters.buildPath; - process.env.BUILD_FILE = buildParameters.buildFile; - process.env.BUILD_METHOD = buildParameters.buildMethod; - process.env.VERSION = buildParameters.buildVersion; - process.env.ANDROID_VERSION_CODE = buildParameters.androidVersionCode; - process.env.ANDROID_KEYSTORE_NAME = buildParameters.androidKeystoreName; - process.env.ANDROID_KEYSTORE_BASE64 = buildParameters.androidKeystoreBase64; - process.env.ANDROID_KEYSTORE_PASS = buildParameters.androidKeystorePass; - process.env.ANDROID_KEYALIAS_NAME = buildParameters.androidKeyaliasName; - process.env.ANDROID_KEYALIAS_PASS = buildParameters.androidKeyaliasPass; - process.env.ANDROID_TARGET_SDK_VERSION = buildParameters.androidTargetSdkVersion; - process.env.ANDROID_SDK_MANAGER_PARAMETERS = buildParameters.androidSdkManagerParameters; - process.env.ANDROID_EXPORT_TYPE = buildParameters.androidExportType; - process.env.ANDROID_SYMBOL_TYPE = buildParameters.androidSymbolType; - process.env.CUSTOM_PARAMETERS = buildParameters.customParameters; - process.env.CHOWN_FILES_TO = buildParameters.chownFilesTo; - }); + static async setEnvironmentVariables(buildParameters, actionFolder) { + // Need to set environment variables from here because we execute + // the scripts on the host for mac + process.env.ACTION_FOLDER = actionFolder; + process.env.UNITY_VERSION = buildParameters.editorVersion; + process.env.UNITY_SERIAL = buildParameters.unitySerial; + process.env.UNITY_LICENSING_SERVER = buildParameters.unityLicensingServer; + process.env.PROJECT_PATH = buildParameters.projectPath; + process.env.BUILD_TARGET = buildParameters.targetPlatform; + process.env.BUILD_NAME = buildParameters.buildName; + process.env.BUILD_PATH = buildParameters.buildPath; + process.env.BUILD_FILE = buildParameters.buildFile; + process.env.BUILD_METHOD = buildParameters.buildMethod; + process.env.VERSION = buildParameters.buildVersion; + process.env.ANDROID_VERSION_CODE = buildParameters.androidVersionCode; + process.env.ANDROID_KEYSTORE_NAME = buildParameters.androidKeystoreName; + process.env.ANDROID_KEYSTORE_BASE64 = buildParameters.androidKeystoreBase64; + process.env.ANDROID_KEYSTORE_PASS = buildParameters.androidKeystorePass; + process.env.ANDROID_KEYALIAS_NAME = buildParameters.androidKeyaliasName; + process.env.ANDROID_KEYALIAS_PASS = buildParameters.androidKeyaliasPass; + process.env.ANDROID_TARGET_SDK_VERSION = buildParameters.androidTargetSdkVersion; + process.env.ANDROID_SDK_MANAGER_PARAMETERS = buildParameters.androidSdkManagerParameters; + process.env.ANDROID_EXPORT_TYPE = buildParameters.androidExportType; + process.env.ANDROID_SYMBOL_TYPE = buildParameters.androidSymbolType; + process.env.CUSTOM_PARAMETERS = buildParameters.customParameters; + process.env.CHOWN_FILES_TO = buildParameters.chownFilesTo; } } SetupMac.unityHubBasePath = `/Applications/"Unity Hub.app"`; @@ -7668,49 +7015,34 @@ exports["default"] = SetupMac; "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const exec_1 = __nccwpck_require__(71514); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); class SetupWindows { - static setup(buildParameters) { - return __awaiter(this, void 0, void 0, function* () { - const { targetPlatform } = buildParameters; - yield SetupWindows.setupWindowsRun(targetPlatform); - }); + static async setup(buildParameters) { + const { targetPlatform } = buildParameters; + await SetupWindows.setupWindowsRun(targetPlatform); } - static setupWindowsRun(targetPlatform, silent = false) { - return __awaiter(this, void 0, void 0, function* () { - if (!fs_1.default.existsSync('c:/regkeys')) { - fs_1.default.mkdirSync('c:/regkeys'); - } - // These all need the Windows 10 SDK - switch (targetPlatform) { - case 'StandaloneWindows': - case 'StandaloneWindows64': - case 'WSAPlayer': - yield this.generateWinSDKRegKeys(silent); - break; - } - }); + static async setupWindowsRun(targetPlatform, silent = false) { + if (!node_fs_1.default.existsSync('c:/regkeys')) { + node_fs_1.default.mkdirSync('c:/regkeys'); + } + // These all need the Windows 10 SDK + switch (targetPlatform) { + case 'StandaloneWindows': + case 'StandaloneWindows64': + case 'WSAPlayer': + await this.generateWinSDKRegKeys(silent); + break; + } } - static generateWinSDKRegKeys(silent = false) { - return __awaiter(this, void 0, void 0, function* () { - // Export registry keys that point to the Windows 10 SDK - const exportWinSDKRegKeysCommand = 'reg export "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0" c:/regkeys/winsdk.reg /y'; - yield exec_1.exec(exportWinSDKRegKeysCommand, undefined, { silent }); - }); + static async generateWinSDKRegKeys(silent = false) { + // Export registry keys that point to the Windows 10 SDK + const exportWinSDKRegKeysCommand = 'reg export "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0" c:/regkeys/winsdk.reg /y'; + await exec_1.exec(exportWinSDKRegKeysCommand, undefined, { silent }); } } exports["default"] = SetupWindows; @@ -7727,7 +7059,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs_1 = __importDefault(__nccwpck_require__(57147)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); class ValidateWindows { static validate(buildParameters) { ValidateWindows.validateWindowsPlatformRequirements(buildParameters.targetPlatform); @@ -7740,13 +7072,7 @@ class ValidateWindows { static validateWindowsPlatformRequirements(platform) { switch (platform) { case 'StandaloneWindows': - this.checkForVisualStudio(); - this.checkForWin10SDK(); - break; case 'StandaloneWindows64': - this.checkForVisualStudio(); - this.checkForWin10SDK(); - break; case 'WSAPlayer': this.checkForVisualStudio(); this.checkForWin10SDK(); @@ -7758,7 +7084,7 @@ class ValidateWindows { } static checkForWin10SDK() { // Check for Windows 10 SDK on runner - const windows10SDKPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Windows Kits'); + const windows10SDKPathExists = node_fs_1.default.existsSync('C:/Program Files (x86)/Windows Kits'); if (!windows10SDKPathExists) { throw new Error(`Windows 10 SDK not found in default location. Make sure the runner has a Windows 10 SDK installed in the default @@ -7767,8 +7093,8 @@ class ValidateWindows { } static checkForVisualStudio() { // Note: When upgrading to Server 2022, we will need to move to just "program files" since VS will be 64-bit - const visualStudioInstallPathExists = fs_1.default.existsSync('C:/Program Files (x86)/Microsoft Visual Studio'); - const visualStudioDataPathExists = fs_1.default.existsSync('C:/ProgramData/Microsoft/VisualStudio'); + const visualStudioInstallPathExists = node_fs_1.default.existsSync('C:/Program Files (x86)/Microsoft Visual Studio'); + const visualStudioDataPathExists = node_fs_1.default.existsSync('C:/ProgramData/Microsoft/VisualStudio'); if (!visualStudioInstallPathExists || !visualStudioDataPathExists) { throw new Error(`Visual Studio not found at the default location. Make sure the runner has Visual Studio installed in the @@ -7892,72 +7218,61 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; Object.defineProperty(exports, "__esModule", ({ value: true })); const core = __importStar(__nccwpck_require__(42186)); const exec_1 = __nccwpck_require__(71514); class System { - static run(command, arguments_ = [], options = {}, shouldLog = true) { - return __awaiter(this, void 0, void 0, function* () { - let result = ''; - let error = ''; - let debug = ''; - const listeners = { - stdout: (dataBuffer) => { - result += dataBuffer.toString(); - }, - stderr: (dataBuffer) => { - error += dataBuffer.toString(); - }, - debug: (dataString) => { - debug += dataString.toString(); - }, - }; - const showOutput = () => { - if (debug !== '' && shouldLog) { - core.debug(debug); - } - if (result !== '' && shouldLog) { - core.info(result); - } - if (error !== '' && shouldLog) { - core.warning(error); - } - }; - const throwContextualError = (message) => { - let commandAsString = command; - if (Array.isArray(arguments_)) { - commandAsString += ` ${arguments_.join(' ')}`; - } - else if (typeof arguments_ === 'string') { - commandAsString += ` ${arguments_}`; - } - throw new Error(`Failed to run "${commandAsString}".\n ${message}`); - }; - try { - if (command.trim() === '') { - throw new Error(`Failed to execute empty command`); - } - const exitCode = yield exec_1.exec(command, arguments_, Object.assign({ silent: true, listeners }, options)); - showOutput(); - if (exitCode !== 0) { - throwContextualError(`Command returned non-zero exit code.\nError: ${error}`); - } + static async run(command, arguments_ = [], options = {}, shouldLog = true) { + let result = ''; + let error = ''; + let debug = ''; + const listeners = { + stdout: (dataBuffer) => { + result += dataBuffer.toString(); + }, + stderr: (dataBuffer) => { + error += dataBuffer.toString(); + }, + debug: (dataString) => { + debug += dataString; + }, + }; + const showOutput = () => { + if (debug !== '' && shouldLog) { + core.debug(debug); } - catch (inCommandError) { - showOutput(); - throwContextualError(`In-command error caught: ${inCommandError}`); + if (result !== '' && shouldLog) { + core.info(result); } - return result; - }); + if (error !== '' && shouldLog) { + core.warning(error); + } + }; + const throwContextualError = (message) => { + let commandAsString = command; + if (Array.isArray(arguments_)) { + commandAsString += ` ${arguments_.join(' ')}`; + } + else if (typeof arguments_ === 'string') { + commandAsString += ` ${arguments_}`; + } + throw new Error(`Failed to run "${commandAsString}".\n ${message}`); + }; + try { + if (command.trim() === '') { + throw new Error(`Failed to execute empty command`); + } + const exitCode = await exec_1.exec(command, arguments_, { silent: true, listeners, ...options }); + showOutput(); + if (exitCode !== 0) { + throwContextualError(`Command returned non-zero exit code.\nError: ${error}`); + } + } + catch (inCommandError) { + showOutput(); + throwContextualError(`In-command error caught: ${inCommandError}`); + } + return result; } } exports["default"] = System; @@ -7970,31 +7285,12 @@ exports["default"] = System; "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs = __importStar(__nccwpck_require__(57147)); -const path_1 = __importDefault(__nccwpck_require__(71017)); +const node_fs_1 = __importDefault(__nccwpck_require__(87561)); +const node_path_1 = __importDefault(__nccwpck_require__(49411)); class UnityVersioning { static get versionPattern() { return /20\d{2}\.\d\.\w{3,4}|3/; @@ -8006,11 +7302,11 @@ class UnityVersioning { return unityVersion; } static read(projectPath) { - const filePath = path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); - if (!fs.existsSync(filePath)) { + const filePath = node_path_1.default.join(projectPath, 'ProjectSettings', 'ProjectVersion.txt'); + if (!node_fs_1.default.existsSync(filePath)) { throw new Error(`Project settings file not found at "${filePath}". Have you correctly set the projectPath?`); } - return UnityVersioning.parse(fs.readFileSync(filePath, 'utf8')); + return UnityVersioning.parse(node_fs_1.default.readFileSync(filePath, 'utf8')); } static parse(projectVersionTxt) { const matches = projectVersionTxt.match(UnityVersioning.versionPattern); @@ -8065,15 +7361,6 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; @@ -8084,12 +7371,6 @@ const validation_error_1 = __importDefault(__nccwpck_require__(97266)); const input_1 = __importDefault(__nccwpck_require__(91933)); const system_1 = __importDefault(__nccwpck_require__(62177)); class Versioning { - static get projectPath() { - return input_1.default.projectPath; - } - static get isDirtyAllowed() { - return input_1.default.allowDirtyBuild; - } static get strategies() { return { None: 'None', Semantic: 'Semantic', Tag: 'Tag', Custom: 'Custom' }; } @@ -8100,8 +7381,7 @@ class Versioning { * Get the branch name of the (related) branch */ static get branch() { - // Todo - use optional chaining (https://github.com/zeit/ncc/issues/534) - return this.headRef || (this.ref && this.ref.slice(11)); + return this.headRef || this.ref?.slice(11); } /** * For pull requests we can reliably use GITHUB_HEAD_REF @@ -8130,52 +7410,40 @@ class Versioning { /** * Log up to maxDiffLines of the git diff. */ - static logDiff() { - return __awaiter(this, void 0, void 0, function* () { - const diffCommand = `git --no-pager diff | head -n ${this.maxDiffLines.toString()}`; - yield system_1.default.run('sh', undefined, { - input: Buffer.from(diffCommand), - silent: true, - }, false); - }); + static async logDiff() { + const diffCommand = `git --no-pager diff | head -n ${this.maxDiffLines.toString()}`; + await system_1.default.run('sh', undefined, { + input: Buffer.from(diffCommand), + silent: true, + }, false); } /** * Regex to parse version description into separate fields */ - static get descriptionRegex1() { - return /^v?([\d.]+)-(\d+)-g(\w+)-?(\w+)*/g; + static get descriptionRegexes() { + return [ + /^v?([\d.]+)-(\d+)-g(\w+)-?(\w+)*/g, + /^v?([\d.]+-\w+)-(\d+)-g(\w+)-?(\w+)*/g, + /^v?([\d.]+-\w+\.\d+)-(\d+)-g(\w+)-?(\w+)*/g, + ]; } - static get descriptionRegex2() { - return /^v?([\d.]+-\w+)-(\d+)-g(\w+)-?(\w+)*/g; - } - static get descriptionRegex3() { - return /^v?([\d.]+-\w+\.\d+)-(\d+)-g(\w+)-?(\w+)*/g; - } - static determineBuildVersion(strategy, inputVersion) { - return __awaiter(this, void 0, void 0, function* () { - // Validate input - if (!Object.hasOwnProperty.call(this.strategies, strategy)) { - throw new validation_error_1.default(`Versioning strategy should be one of ${Object.values(this.strategies).join(', ')}.`); - } - let version; - switch (strategy) { - case this.strategies.None: - version = 'none'; - break; - case this.strategies.Custom: - version = inputVersion; - break; - case this.strategies.Semantic: - version = yield this.generateSemanticVersion(); - break; - case this.strategies.Tag: - version = yield this.generateTagVersion(); - break; - default: - throw new not_implemented_exception_1.default(`Strategy ${strategy} is not implemented.`); - } - return version; - }); + static async determineBuildVersion(strategy, inputVersion) { + // Validate input + if (!Object.hasOwnProperty.call(this.strategies, strategy)) { + throw new validation_error_1.default(`Versioning strategy should be one of ${Object.values(this.strategies).join(', ')}.`); + } + switch (strategy) { + case this.strategies.None: + return 'none'; + case this.strategies.Custom: + return inputVersion; + case this.strategies.Semantic: + return await this.generateSemanticVersion(); + case this.strategies.Tag: + return await this.generateTagVersion(); + default: + throw new not_implemented_exception_1.default(`Strategy ${strategy} is not implemented.`); + } } /** * Automatically generates a version based on SemVer out of the box. @@ -8187,54 +7455,50 @@ class Versioning { * * @See: https://semver.org/ */ - static generateSemanticVersion() { - return __awaiter(this, void 0, void 0, function* () { - if (yield this.isShallow()) { - yield this.fetch(); - } - yield this.logDiff(); - if ((yield this.isDirty()) && !this.isDirtyAllowed) { - throw new Error('Branch is dirty. Refusing to base semantic version on uncommitted changes'); - } - if (!(yield this.hasAnyVersionTags())) { - const version = `0.0.${yield this.getTotalNumberOfCommits()}`; - core.info(`Generated version ${version} (no version tags found).`); - return version; - } - const versionDescriptor = yield this.parseSemanticVersion(); - if (versionDescriptor) { - const { tag, commits, hash } = versionDescriptor; - // Ensure 3 digits (commits should always be patch level) - const [major, minor, patch] = `${tag}.${commits}`.split('.'); - const threeDigitVersion = /^\d+$/.test(patch) ? `${major}.${minor}.${patch}` : `${major}.0.${minor}`; - core.info(`Found semantic version ${threeDigitVersion} for ${this.branch}@${hash}`); - return `${threeDigitVersion}`; - } - const version = `0.0.${yield this.getTotalNumberOfCommits()}`; - core.info(`Generated version ${version} (semantic version couldn't be determined).`); + static async generateSemanticVersion() { + if (await this.isShallow()) { + await this.fetch(); + } + await this.logDiff(); + if ((await this.isDirty()) && !input_1.default.allowDirtyBuild) { + throw new Error('Branch is dirty. Refusing to base semantic version on uncommitted changes'); + } + if (!(await this.hasAnyVersionTags())) { + const version = `0.0.${await this.getTotalNumberOfCommits()}`; + core.info(`Generated version ${version} (no version tags found).`); return version; - }); + } + const versionDescriptor = await this.parseSemanticVersion(); + if (versionDescriptor) { + const { tag, commits, hash } = versionDescriptor; + // Ensure 3 digits (commits should always be patch level) + const [major, minor, patch] = `${tag}.${commits}`.split('.'); + const threeDigitVersion = /^\d+$/.test(patch) ? `${major}.${minor}.${patch}` : `${major}.0.${minor}`; + core.info(`Found semantic version ${threeDigitVersion} for ${this.branch}@${hash}`); + return `${threeDigitVersion}`; + } + const version = `0.0.${await this.getTotalNumberOfCommits()}`; + core.info(`Generated version ${version} (semantic version couldn't be determined).`); + return version; } /** * Generate the proper version for unity based on an existing tag. */ - static generateTagVersion() { - return __awaiter(this, void 0, void 0, function* () { - let tag = yield this.getTag(); - if (tag.charAt(0) === 'v') { - tag = tag.slice(1); - } - return tag; - }); + static async generateTagVersion() { + let tag = await this.getTag(); + if (tag.charAt(0) === 'v') { + tag = tag.slice(1); + } + return tag; } /** * Parses the versionDescription into their named parts. */ - static parseSemanticVersion() { - return __awaiter(this, void 0, void 0, function* () { - const description = yield this.getVersionDescription(); + static async parseSemanticVersion() { + const description = await this.getVersionDescription(); + for (const descriptionRegex of Versioning.descriptionRegexes) { try { - const [match, tag, commits, hash] = this.descriptionRegex1.exec(description); + const [match, tag, commits, hash] = descriptionRegex.exec(description); return { match, tag, @@ -8242,42 +7506,19 @@ class Versioning { hash, }; } - catch (_a) { - try { - const [match, tag, commits, hash] = this.descriptionRegex2.exec(description); - return { - match, - tag, - commits, - hash, - }; - } - catch (_b) { - try { - const [match, tag, commits, hash] = this.descriptionRegex3.exec(description); - return { - match, - tag, - commits, - hash, - }; - } - catch (_c) { - core.warning(`Failed to parse git describe output or version can not be determined through: "${description}".`); - return false; - } - } + catch { + continue; } - }); + } + core.warning(`Failed to parse git describe output or version can not be determined through: "${description}".`); + return false; } /** * Returns whether the repository is shallow. */ - static isShallow() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.git(['rev-parse', '--is-shallow-repository']); - return output !== 'false\n'; - }); + static async isShallow() { + const output = await this.git(['rev-parse', '--is-shallow-repository']); + return output !== 'false\n'; } /** * Retrieves refs from the configured remote. @@ -8286,16 +7527,14 @@ class Versioning { * * Note: `--all` should not be used, and would break fetching for push event. */ - static fetch() { - return __awaiter(this, void 0, void 0, function* () { - try { - yield this.git(['fetch', '--unshallow']); - } - catch (error) { - core.warning(`Fetch --unshallow caught: ${error}`); - yield this.git(['fetch']); - } - }); + static async fetch() { + try { + await this.git(['fetch', '--unshallow']); + } + catch (error) { + core.warning(`Fetch --unshallow caught: ${error}`); + await this.git(['fetch']); + } } /** * Retrieves information about the branch. @@ -8305,67 +7544,55 @@ class Versioning { * In this format v0.12 is the latest tag, 24 are the number of commits since, and gd2198ab * identifies the current commit. */ - static getVersionDescription() { - return __awaiter(this, void 0, void 0, function* () { - return this.git(['describe', '--long', '--tags', '--always', this.sha]); - }); + static async getVersionDescription() { + return this.git(['describe', '--long', '--tags', '--always', this.sha]); } /** * Returns whether there are uncommitted changes that are not ignored. */ - static isDirty() { - return __awaiter(this, void 0, void 0, function* () { - const output = yield this.git(['status', '--porcelain']); - const isDirty = output !== ''; - if (isDirty) { - core.warning('Changes were made to the following files and folders:\n'); - core.warning(output); - } - return isDirty; - }); + static async isDirty() { + const output = await this.git(['status', '--porcelain']); + const isDirty = output !== ''; + if (isDirty) { + core.warning('Changes were made to the following files and folders:\n'); + core.warning(output); + } + return isDirty; } /** * Get the tag if there is one pointing at HEAD */ - static getTag() { - return __awaiter(this, void 0, void 0, function* () { - return (yield this.git(['tag', '--points-at', 'HEAD'])).trim(); - }); + static async getTag() { + return (await this.git(['tag', '--points-at', 'HEAD'])).trim(); } /** * Whether the current tree has any version tags yet. * * Note: Currently this is run in all OSes, so the syntax must be cross-platform. */ - static hasAnyVersionTags() { - return __awaiter(this, void 0, void 0, function* () { - const numberOfTagsAsString = yield system_1.default.run('sh', undefined, { - input: Buffer.from(`git tag --list --merged HEAD | grep -E '${this.grepCompatibleInputVersionRegex}' | wc -l`), - cwd: this.projectPath, - silent: false, - }); - const numberOfTags = Number.parseInt(numberOfTagsAsString, 10); - return numberOfTags !== 0; + static async hasAnyVersionTags() { + const numberOfTagsAsString = await system_1.default.run('sh', undefined, { + input: Buffer.from(`git tag --list --merged HEAD | grep -E '${this.grepCompatibleInputVersionRegex}' | wc -l`), + cwd: input_1.default.projectPath, + silent: false, }); + const numberOfTags = Number.parseInt(numberOfTagsAsString, 10); + return numberOfTags !== 0; } /** * Get the total number of commits on head. * * Note: HEAD should not be used, as it may be detached, resulting in an additional count. */ - static getTotalNumberOfCommits() { - return __awaiter(this, void 0, void 0, function* () { - const numberOfCommitsAsString = yield this.git(['rev-list', '--count', this.sha]); - return Number.parseInt(numberOfCommitsAsString, 10); - }); + static async getTotalNumberOfCommits() { + const numberOfCommitsAsString = await this.git(['rev-list', '--count', this.sha]); + return Number.parseInt(numberOfCommitsAsString, 10); } /** * Run git in the specified project path */ - static git(arguments_, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - return system_1.default.run('git', arguments_, Object.assign({ cwd: this.projectPath }, options), false); - }); + static async git(arguments_, options = {}) { + return system_1.default.run('git', arguments_, { cwd: input_1.default.projectPath, ...options }, false); } } exports["default"] = Versioning; @@ -16932,7 +16159,7 @@ var abortController = __nccwpck_require__(52557); var tunnel = __nccwpck_require__(74294); var stream = __nccwpck_require__(12781); var FormData = __nccwpck_require__(46279); -var node_fetch = __nccwpck_require__(37461); +var node_fetch = __nccwpck_require__(80467); var coreTracing = __nccwpck_require__(94175); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } @@ -22940,3963 +22167,6 @@ module.exports = function(dst, src) { }; -/***/ }), - -/***/ 37461: -/***/ ((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__(21990)); -var https = _interopDefault(__nccwpck_require__(95687)); -var zlib = _interopDefault(__nccwpck_require__(59796)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); - -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ - -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(22877).convert); -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - - accumBytes += chunk.length; - accum.push(chunk); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); - - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} - -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } - - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} - -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} - -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ - -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; - -const URL$1 = Url.URL || whatwgUrl.URL; - -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; - -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; - - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; - -/** - * isSameProtocol reports whether the two provided URLs use the same protocol. - * - * Both domains must already be in canonical form. - * @param {string|URL} original - * @param {string|URL} destination - */ -const isSameProtocol = function isSameProtocol(destination, original) { - const orig = new URL$1(original).protocol; - const dest = new URL$1(destination).protocol; - - return orig === dest; -}; - -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; - - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - destroyStream(request.body, error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } - - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - - if (response && response.body) { - destroyStream(response.body, err); - } - - finalize(); - }); - - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } - - if (response && response.body) { - destroyStream(response.body, err); - } - }); - - /* c8 ignore next 18 */ - if (parseInt(process.version.substring(1)) < 14) { - // Before Node.js 14, pipeline() does not fully support async iterators and does not always - // properly handle when the socket close/end events are out of order. - req.on('socket', function (s) { - s.addListener('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = s.listenerCount('data') > 0; - - // if end happened before close but the socket didn't emit an error, do it now - if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - response.body.emit('error', err); - } - }); - }); - } - - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } - - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } - - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; - - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } - - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - raw.on('end', function () { - // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. - if (!response) { - response = new Response(body, response_options); - resolve(response); - } - }); - return; - } - - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); - - writeToStream(req, request); - }); -} -function fixResponseChunkedTransferBadEnding(request, errorCallback) { - let socket; - - request.on('socket', function (s) { - socket = s; - }); - - request.on('response', function (response) { - const headers = response.headers; - - if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { - response.once('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = 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; - - -/***/ }), - -/***/ 71412: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var punycode = __nccwpck_require__(85477); -var mappingTable = __nccwpck_require__(46086); - -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 -}; - -function normalize(str) { // fix bug in v8 - return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); -} - -function findStatus(val) { - var start = 0; - var end = mappingTable.length - 1; - - while (start <= end) { - var mid = Math.floor((start + end) / 2); - - var target = mappingTable[mid]; - if (target[0][0] <= val && target[0][1] >= val) { - return target; - } else if (target[0][0] > val) { - end = mid - 1; - } else { - start = mid + 1; - } - } - - return null; -} - -var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; - -function countSymbols(string) { - return string - // replace every surrogate pair with a BMP symbol - .replace(regexAstralSymbols, '_') - // then get the length - .length; -} - -function mapChars(domain_name, useSTD3, processing_option) { - var hasError = false; - var processed = ""; - - var len = countSymbols(domain_name); - for (var i = 0; i < len; ++i) { - var codePoint = domain_name.codePointAt(i); - var status = findStatus(codePoint); - - switch (status[1]) { - case "disallowed": - hasError = true; - processed += String.fromCodePoint(codePoint); - break; - case "ignored": - break; - case "mapped": - processed += String.fromCodePoint.apply(String, status[2]); - break; - case "deviation": - if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { - processed += String.fromCodePoint.apply(String, status[2]); - } else { - processed += String.fromCodePoint(codePoint); - } - break; - case "valid": - processed += String.fromCodePoint(codePoint); - break; - case "disallowed_STD3_mapped": - if (useSTD3) { - hasError = true; - processed += String.fromCodePoint(codePoint); - } else { - processed += String.fromCodePoint.apply(String, status[2]); - } - break; - case "disallowed_STD3_valid": - if (useSTD3) { - hasError = true; - } - - processed += String.fromCodePoint(codePoint); - break; - } - } - - return { - string: processed, - error: hasError - }; -} - -var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; - -function validateLabel(label, processing_option) { - if (label.substr(0, 4) === "xn--") { - label = punycode.toUnicode(label); - processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; - } - - var error = false; - - if (normalize(label) !== label || - (label[3] === "-" && label[4] === "-") || - label[0] === "-" || label[label.length - 1] === "-" || - label.indexOf(".") !== -1 || - label.search(combiningMarksRegex) === 0) { - error = true; - } - - var len = countSymbols(label); - for (var i = 0; i < len; ++i) { - var status = findStatus(label.codePointAt(i)); - if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || - (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && - status[1] !== "valid" && status[1] !== "deviation")) { - error = true; - break; - } - } - - return { - label: label, - error: error - }; -} - -function processing(domain_name, useSTD3, processing_option) { - var result = mapChars(domain_name, useSTD3, processing_option); - result.string = normalize(result.string); - - var labels = result.string.split("."); - for (var i = 0; i < labels.length; ++i) { - try { - var validation = validateLabel(labels[i]); - labels[i] = validation.label; - result.error = result.error || validation.error; - } catch(e) { - result.error = true; - } - } - - return { - string: labels.join("."), - error: result.error - }; -} - -module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { - var result = processing(domain_name, useSTD3, processing_option); - var labels = result.string.split("."); - labels = labels.map(function(l) { - try { - return punycode.toASCII(l); - } catch(e) { - result.error = true; - return l; - } - }); - - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; - } - - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } - } - } - - if (result.error) return null; - return labels.join("."); -}; - -module.exports.toUnicode = function(domain_name, useSTD3) { - var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); - - return { - domain: result.string, - error: result.error - }; -}; - -module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; - - -/***/ }), - -/***/ 87049: -/***/ ((module) => { - -"use strict"; - - -var conversions = {}; -module.exports = conversions; - -function sign(x) { - return x < 0 ? -1 : 1; -} - -function evenRound(x) { - // Round x to the nearest integer, choosing the even integer if it lies halfway between two. - if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) - return Math.floor(x); - } else { - return Math.round(x); - } -} - -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; - } - const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); - const upperBound = Math.pow(2, bitLength) - 1; - - const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); - const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); - - return function(V, opts) { - if (!opts) opts = {}; - - let x = +V; - - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } - - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } - - return x; - } - - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); - - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } - - if (!Number.isFinite(x) || x === 0) { - return 0; - } - - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; - - if (!typeOpts.unsigned && x >= moduloBound) { - return x - moduloVal; - } else if (typeOpts.unsigned) { - if (x < 0) { - x += moduloVal; - } else if (x === -0) { // don't return negative zero - return 0; - } - } - - return x; - } -} - -conversions["void"] = function () { - return undefined; -}; - -conversions["boolean"] = function (val) { - return !!val; -}; - -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); - -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); - -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); - -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); - -conversions["double"] = function (V) { - const x = +V; - - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } - - return x; -}; - -conversions["unrestricted double"] = function (V) { - const x = +V; - - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); - } - - return x; -}; - -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; - -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; - - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } - - return String(V); -}; - -conversions["ByteString"] = function (V, opts) { - const x = String(V); - let c = undefined; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError("Argument is not a valid bytestring"); - } - } - - return x; -}; - -conversions["USVString"] = function (V) { - const S = String(V); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } - } - - return U.join(''); -}; - -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; - } - - return V; -}; - -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); - } - - return V; -}; - - -/***/ }), - -/***/ 66598: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const usm = __nccwpck_require__(41872); - -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; - - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); - } - } - - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } - - this._url = parsedURL; - - // TODO: query stuff - } - - get href() { - return usm.serializeURL(this._url); - } - - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } - - this._url = parsedURL; - } - - get origin() { - return usm.serializeURLOrigin(this._url); - } - - get protocol() { - return this._url.scheme + ":"; - } - - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); - } - - get username() { - return this._url.username; - } - - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - usm.setTheUsername(this._url, v); - } - - get password() { - return this._url.password; - } - - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - usm.setThePassword(this._url, v); - } - - get host() { - const url = this._url; - - if (url.host === null) { - return ""; - } - - if (url.port === null) { - return usm.serializeHost(url.host); - } - - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); - } - - set host(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); - } - - get hostname() { - if (this._url.host === null) { - return ""; - } - - return usm.serializeHost(this._url.host); - } - - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); - } - - get port() { - if (this._url.port === null) { - return ""; - } - - return usm.serializeInteger(this._url.port); - } - - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); - } - } - - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; - } - - if (this._url.path.length === 0) { - return ""; - } - - return "/" + this._url.path.join("/"); - } - - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); - } - - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; - } - - return "?" + this._url.query; - } - - set search(v) { - // TODO: query stuff - - const url = this._url; - - if (v === "") { - url.query = null; - return; - } - - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); - } - - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; - } - - return "#" + this._url.fragment; - } - - set hash(v) { - if (v === "") { - this._url.fragment = null; - return; - } - - const input = v[0] === "#" ? v.substring(1) : v; - this._url.fragment = ""; - usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); - } - - toJSON() { - return this.href; - } -}; - - -/***/ }), - -/***/ 80864: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const conversions = __nccwpck_require__(87049); -const utils = __nccwpck_require__(77687); -const Impl = __nccwpck_require__(66598); - -const impl = utils.implSymbol; - -function URL(url) { - if (!this || this[impl] || !(this instanceof URL)) { - throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); - } - if (arguments.length < 1) { - throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); - } - const args = []; - for (let i = 0; i < arguments.length && i < 2; ++i) { - args[i] = arguments[i]; - } - args[0] = conversions["USVString"](args[0]); - if (args[1] !== undefined) { - args[1] = conversions["USVString"](args[1]); - } - - module.exports.setup(this, args); -} - -URL.prototype.toJSON = function toJSON() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - const args = []; - for (let i = 0; i < arguments.length && i < 0; ++i) { - args[i] = arguments[i]; - } - return this[impl].toJSON.apply(this[impl], args); -}; -Object.defineProperty(URL.prototype, "href", { - get() { - return this[impl].href; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].href = V; - }, - enumerable: true, - configurable: true -}); - -URL.prototype.toString = function () { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - return this.href; -}; - -Object.defineProperty(URL.prototype, "origin", { - get() { - return this[impl].origin; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "protocol", { - get() { - return this[impl].protocol; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].protocol = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "username", { - get() { - return this[impl].username; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].username = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); - -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); - - -module.exports = { - is(obj) { - return !!obj && obj[impl] instanceof Impl.implementation; - }, - create(constructorArgs, privateData) { - let obj = Object.create(URL.prototype); - this.setup(obj, constructorArgs, privateData); - return obj; - }, - setup(obj, constructorArgs, privateData) { - if (!privateData) privateData = {}; - privateData.wrapper = obj; - - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } - } -}; - - - -/***/ }), - -/***/ 21990: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -exports.URL = __nccwpck_require__(80864)["interface"]; -exports.serializeURL = __nccwpck_require__(41872).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(41872).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(41872).basicURLParse; -exports.setTheUsername = __nccwpck_require__(41872).setTheUsername; -exports.setThePassword = __nccwpck_require__(41872).setThePassword; -exports.serializeHost = __nccwpck_require__(41872).serializeHost; -exports.serializeInteger = __nccwpck_require__(41872).serializeInteger; -exports.parseURL = __nccwpck_require__(41872).parseURL; - - -/***/ }), - -/***/ 41872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const punycode = __nccwpck_require__(85477); -const tr46 = __nccwpck_require__(71412); - -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 }); -}; - - -/***/ }), - -/***/ 77687: -/***/ ((module) => { - -"use strict"; - - -module.exports.mixin = function mixin(target, source) { - const keys = Object.getOwnPropertyNames(source); - for (let i = 0; i < keys.length; ++i) { - Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); - } -}; - -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); - -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; - -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; - - - /***/ }), /***/ 27094: @@ -54227,6 +49497,4374 @@ exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 98348: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.testDefinitions = void 0; +/** Reference to the array that `Deno.test` calls insert their definition into. */ +exports.testDefinitions = []; + + +/***/ }), + +/***/ 19766: +/***/ (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); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.testDefinitions = exports.Deno = void 0; +exports.Deno = __nccwpck_require__(24618); +__exportStar(__nccwpck_require__(24618), exports); +var definitions_js_1 = __nccwpck_require__(98348); +Object.defineProperty(exports, "testDefinitions", ({ enumerable: true, get: function () { return definitions_js_1.testDefinitions; } })); + + +/***/ }), + +/***/ 24618: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.test = void 0; +const definitions_js_1 = __nccwpck_require__(98348); +const test = function test() { + var _a, _b; + let testDef; + const firstArg = arguments[0]; + const secondArg = arguments[1]; + const thirdArg = arguments[2]; + if (typeof firstArg === "string") { + if (typeof secondArg === "object") { + if (typeof thirdArg === "function") { + if (secondArg.fn != null) { + throw new TypeError("Unexpected 'fn' field in options, test function is already provided as the third argument."); + } + } + if (secondArg.name != null) { + throw new TypeError("Unexpected 'name' field in options, test name is already provided as the first argument."); + } + // name, options, fn + testDef = { name: firstArg, fn: thirdArg, ...secondArg }; + } + else { + // name, fn + testDef = { name: firstArg, fn: secondArg }; + } + } + else if (firstArg instanceof Function) { + // function only + if (firstArg.name.length === 0) { + throw new TypeError("The test function must have a name"); + } + testDef = { fn: firstArg, name: firstArg.name }; + if (secondArg != null) { + throw new TypeError("Unexpected second argument to Deno.test()"); + } + } + else if (typeof firstArg === "object") { + testDef = { ...firstArg }; + if (typeof secondArg === "function") { + // options, fn + testDef.fn = secondArg; + if (firstArg.fn != null) { + throw new TypeError("Unexpected 'fn' field in options, test function is already provided as the second argument."); + } + if (testDef.name == null) { + if (secondArg.name.length === 0) { + throw new TypeError("The test function must have a name"); + } + // options without name, fn + testDef.name = secondArg.name; + } + } + else { + if (typeof firstArg.fn !== "function") { + throw new TypeError("Expected 'fn' field in the first argument to be a test function."); + } + } + } + else { + throw new TypeError("Unknown test overload"); + } + if (typeof testDef.fn !== "function") { + throw new TypeError("Missing test function"); + } + if (((_b = (_a = testDef.name) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) === 0) { + throw new TypeError("The test name can't be empty"); + } + definitions_js_1.testDefinitions.push(testDef); +}; +exports.test = test; + + +/***/ }), + +/***/ 32854: +/***/ (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); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(63367), exports); +__exportStar(__nccwpck_require__(43032), exports); + + +/***/ }), + +/***/ 59395: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __classPrivateFieldSet = (this && this.__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; +}; +var __classPrivateFieldGet = (this && this.__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); +}; +var _Conn_socket; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TlsConn = exports.Conn = void 0; +const net_1 = __nccwpck_require__(41808); +const FsFile_js_1 = __nccwpck_require__(61631); +class Conn extends FsFile_js_1.FsFile { + constructor(rid, localAddr, remoteAddr, socket) { + super(rid); + this.rid = rid; + this.localAddr = localAddr; + this.remoteAddr = remoteAddr; + _Conn_socket.set(this, void 0); + __classPrivateFieldSet(this, _Conn_socket, socket || new net_1.Socket({ fd: rid }), "f"); + } + async closeWrite() { + await new Promise((resolve) => __classPrivateFieldGet(this, _Conn_socket, "f").end(resolve)); + } + setNoDelay(enable) { + __classPrivateFieldGet(this, _Conn_socket, "f").setNoDelay(enable); + } + setKeepAlive(enable) { + __classPrivateFieldGet(this, _Conn_socket, "f").setKeepAlive(enable); + } +} +exports.Conn = Conn; +_Conn_socket = new WeakMap(); +class TlsConn extends Conn { + handshake() { + console.warn("@deno/shim-deno: Handshake is not supported."); + return Promise.resolve({ + alpnProtocol: null, + }); + } +} +exports.TlsConn = TlsConn; + + +/***/ }), + +/***/ 6068: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __classPrivateFieldSet = (this && this.__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; +}; +var __classPrivateFieldGet = (this && this.__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); +}; +var _Listener_listener; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Listener = void 0; +const close_js_1 = __nccwpck_require__(44781); +const errors = __importStar(__nccwpck_require__(82826)); +class Listener { + constructor(rid, addr, listener) { + this.rid = rid; + this.addr = addr; + _Listener_listener.set(this, void 0); + __classPrivateFieldSet(this, _Listener_listener, listener, "f"); + } + async accept() { + if (!__classPrivateFieldGet(this, _Listener_listener, "f")) { + throw new errors.BadResource("Listener not initialised"); + } + const result = await __classPrivateFieldGet(this, _Listener_listener, "f").next(); + if (result.done) { + throw new errors.BadResource("Server not listening"); + } + return result.value; + } + async next() { + let conn; + try { + conn = await this.accept(); + } + catch (error) { + if (error instanceof errors.BadResource) { + return { value: undefined, done: true }; + } + throw error; + } + return { value: conn, done: false }; + } + return(value) { + this.close(); + return Promise.resolve({ value, done: true }); + } + close() { + (0, close_js_1.close)(this.rid); + } + ref() { + throw new Error("Not implemented"); + } + unref() { + throw new Error("Not implemented"); + } + [(_Listener_listener = new WeakMap(), Symbol.asyncIterator)]() { + return this; + } +} +exports.Listener = Listener; + + +/***/ }), + +/***/ 49046: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_BUFFER_SIZE = void 0; +exports.DEFAULT_BUFFER_SIZE = 32 * 1024; + + +/***/ }), + +/***/ 50937: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const errors = __importStar(__nccwpck_require__(82826)); +const mapper = (Ctor) => (err) => Object.assign(new Ctor(err.message), { + stack: err.stack, +}); +const map = { + EEXIST: mapper(errors.AlreadyExists), + ENOENT: mapper(errors.NotFound), +}; +const isNodeErr = (e) => { + return e instanceof Error && "code" in e; +}; +function mapError(e) { + var _a; + if (!isNodeErr(e)) + return e; + return ((_a = map[e.code]) === null || _a === void 0 ? void 0 : _a.call(map, e)) || e; +} +exports["default"] = mapError; + + +/***/ }), + +/***/ 8423: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +// getAccessFlag and getCreationFlag adapted from the original in Rust's std::fs +// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getFsFlag = exports.getCreationFlag = exports.getAccessFlag = void 0; +const errors = __importStar(__nccwpck_require__(82826)); +const fs_1 = __nccwpck_require__(57147); +const os_1 = __importDefault(__nccwpck_require__(22037)); +const { O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY } = fs_1.constants; +function getAccessFlag(opts) { + if (opts.read && !opts.write && !opts.append) + return O_RDONLY; + if (!opts.read && opts.write && !opts.append) + return O_WRONLY; + if (opts.read && opts.write && !opts.append) + return O_RDWR; + if (!opts.read && opts.append) + return O_WRONLY | O_APPEND; + if (opts.read && opts.append) + return O_RDWR | O_APPEND; + if (!opts.read && !opts.write && !opts.append) { + throw new errors.BadResource("EINVAL: One of 'read', 'write', 'append' is required to open file."); + } + throw new errors.BadResource("EINVAL: Invalid fs flags."); +} +exports.getAccessFlag = getAccessFlag; +function getCreationFlag(opts) { + if (!opts.write && !opts.append) { + if (opts.truncate || opts.create || opts.createNew) { + throw new errors.BadResource("EINVAL: One of 'write', 'append' is required to 'truncate', 'create' or 'createNew' file."); + } + } + if (opts.append) { + if (opts.truncate && !opts.createNew) { + throw new errors.BadResource("EINVAL: unexpected 'truncate': true and 'createNew': false when 'append' is true."); + } + } + if (!opts.create && !opts.truncate && !opts.createNew) + return 0; + if (opts.create && !opts.truncate && !opts.createNew) + return O_CREAT; + if (!opts.create && opts.truncate && !opts.createNew) { + if (os_1.default.platform() === "win32") { + // for some reason only providing O_TRUNC on windows will + // throw a "EINVAL: invalid argument", so to work around this + // we relax the restriction here to also create the file if it + // doesn't exist + return O_CREAT | O_TRUNC; + } + else { + return O_TRUNC; + } + } + if (opts.create && opts.truncate && !opts.createNew) { + return O_CREAT | O_TRUNC; + } + if (opts.createNew) + return O_CREAT | O_EXCL; + throw new errors.BadResource("EINVAL: Invalid fs flags."); +} +exports.getCreationFlag = getCreationFlag; +function getFsFlag(flags) { + return getAccessFlag(flags) | getCreationFlag(flags); +} +exports.getFsFlag = getFsFlag; + + +/***/ }), + +/***/ 32341: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.merge = exports.mapAsync = exports.map = void 0; +function* map(iter, f) { + for (const i of iter) { + yield f(i); + } +} +exports.map = map; +async function* mapAsync(iter, f) { + for await (const i of iter) { + yield f(i); + } +} +exports.mapAsync = mapAsync; +async function* merge(iterables) { + const racers = new Map(map(map(iterables, (iter) => iter[Symbol.asyncIterator]()), (iter) => [iter, iter.next()])); + while (racers.size > 0) { + const winner = await Promise.race(map(racers.entries(), ([iter, prom]) => prom.then((result) => ({ result, iter })))); + if (winner.result.done) { + racers.delete(winner.iter); + } + else { + yield await winner.result.value; + racers.set(winner.iter, winner.iter.next()); + } + } +} +exports.merge = merge; + + +/***/ }), + +/***/ 94970: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.randomId = void 0; +const randomId = () => { + const n = (Math.random() * 0xfffff * 1000000).toString(16); + return "" + n.slice(0, 6); +}; +exports.randomId = randomId; + + +/***/ }), + +/***/ 95040: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +/// +var __classPrivateFieldSet = (this && this.__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; +}; +var __classPrivateFieldGet = (this && this.__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); +}; +var _BufferStreamReader_instances, _BufferStreamReader_stream, _BufferStreamReader_error, _BufferStreamReader_ended, _BufferStreamReader_pendingActions, _BufferStreamReader_runPendingActions, _StreamWriter_stream; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StreamWriter = exports.BufferStreamReader = void 0; +class BufferStreamReader { + constructor(stream) { + _BufferStreamReader_instances.add(this); + _BufferStreamReader_stream.set(this, void 0); + _BufferStreamReader_error.set(this, void 0); + _BufferStreamReader_ended.set(this, false); + _BufferStreamReader_pendingActions.set(this, []); + __classPrivateFieldSet(this, _BufferStreamReader_stream, stream, "f"); + __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").pause(); + __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").on("error", (error) => { + __classPrivateFieldSet(this, _BufferStreamReader_error, error, "f"); + __classPrivateFieldGet(this, _BufferStreamReader_instances, "m", _BufferStreamReader_runPendingActions).call(this); + }); + __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").on("readable", () => { + __classPrivateFieldGet(this, _BufferStreamReader_instances, "m", _BufferStreamReader_runPendingActions).call(this); + }); + __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").on("end", () => { + __classPrivateFieldSet(this, _BufferStreamReader_ended, true, "f"); + __classPrivateFieldGet(this, _BufferStreamReader_instances, "m", _BufferStreamReader_runPendingActions).call(this); + }); + } + readAll() { + return new Promise((resolve, reject) => { + const chunks = []; + const action = () => { + if (__classPrivateFieldGet(this, _BufferStreamReader_error, "f")) { + reject(__classPrivateFieldGet(this, _BufferStreamReader_error, "f")); + return; + } + const buffer = __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").read(); + if (buffer != null) { + chunks.push(buffer); + __classPrivateFieldGet(this, _BufferStreamReader_pendingActions, "f").push(action); + } + else if (__classPrivateFieldGet(this, _BufferStreamReader_ended, "f")) { + const result = Buffer.concat(chunks); + resolve(result); + } + else { + __classPrivateFieldGet(this, _BufferStreamReader_pendingActions, "f").push(action); + } + }; + action(); + }); + } + read(p) { + return new Promise((resolve, reject) => { + const action = () => { + if (__classPrivateFieldGet(this, _BufferStreamReader_error, "f")) { + reject(__classPrivateFieldGet(this, _BufferStreamReader_error, "f")); + return; + } + const readBuffer = __classPrivateFieldGet(this, _BufferStreamReader_stream, "f").read(p.byteLength); + if (readBuffer && readBuffer.byteLength > 0) { + readBuffer.copy(p, 0, 0, readBuffer.byteLength); + resolve(readBuffer.byteLength); + return; + } + if (__classPrivateFieldGet(this, _BufferStreamReader_ended, "f")) { + resolve(null); + } + else { + __classPrivateFieldGet(this, _BufferStreamReader_pendingActions, "f").push(action); + } + }; + action(); + }); + } +} +exports.BufferStreamReader = BufferStreamReader; +_BufferStreamReader_stream = new WeakMap(), _BufferStreamReader_error = new WeakMap(), _BufferStreamReader_ended = new WeakMap(), _BufferStreamReader_pendingActions = new WeakMap(), _BufferStreamReader_instances = new WeakSet(), _BufferStreamReader_runPendingActions = function _BufferStreamReader_runPendingActions() { + const errors = []; + for (const action of __classPrivateFieldGet(this, _BufferStreamReader_pendingActions, "f").splice(0)) { + try { + action(); + } + catch (err) { + errors.push(err); + } + } + if (errors.length > 0) { + throw (errors.length > 1 ? new AggregateError(errors) : errors[0]); + } +}; +class StreamWriter { + constructor(stream) { + _StreamWriter_stream.set(this, void 0); + __classPrivateFieldSet(this, _StreamWriter_stream, stream, "f"); + } + write(p) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _StreamWriter_stream, "f").write(p, (err) => { + if (err) { + reject(err); + } + else { + resolve(p.byteLength); + } + }); + }); + } +} +exports.StreamWriter = StreamWriter; +_StreamWriter_stream = new WeakMap(); + + +/***/ }), + +/***/ 70717: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.typescript = exports.deno = void 0; +exports.deno = "1.22.1"; +exports.typescript = "4.6.2"; + + +/***/ }), + +/***/ 9136: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PermissionStatus = exports.Permissions = exports.FsFile = exports.File = void 0; +var FsFile_js_1 = __nccwpck_require__(61631); +Object.defineProperty(exports, "File", ({ enumerable: true, get: function () { return FsFile_js_1.File; } })); +Object.defineProperty(exports, "FsFile", ({ enumerable: true, get: function () { return FsFile_js_1.FsFile; } })); +var Permissions_js_1 = __nccwpck_require__(30711); +Object.defineProperty(exports, "Permissions", ({ enumerable: true, get: function () { return Permissions_js_1.Permissions; } })); +var PermissionStatus_js_1 = __nccwpck_require__(90751); +Object.defineProperty(exports, "PermissionStatus", ({ enumerable: true, get: function () { return PermissionStatus_js_1.PermissionStatus; } })); + + +/***/ }), + +/***/ 61631: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.File = exports.FsFile = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const fstat_js_1 = __nccwpck_require__(44667); +const fstatSync_js_1 = __nccwpck_require__(40301); +const ftruncate_js_1 = __nccwpck_require__(6203); +const ftruncateSync_js_1 = __nccwpck_require__(45758); +const read_js_1 = __nccwpck_require__(7653); +const readSync_js_1 = __nccwpck_require__(27537); +const write_js_1 = __nccwpck_require__(63178); +const writeSync_js_1 = __nccwpck_require__(8331); +class FsFile { + constructor(rid) { + this.rid = rid; + } + async write(p) { + return await (0, write_js_1.write)(this.rid, p); + } + writeSync(p) { + return (0, writeSync_js_1.writeSync)(this.rid, p); + } + async truncate(len) { + await (0, ftruncate_js_1.ftruncate)(this.rid, len); + } + truncateSync(len) { + return (0, ftruncateSync_js_1.ftruncateSync)(this.rid, len); + } + read(p) { + return (0, read_js_1.read)(this.rid, p); + } + readSync(p) { + return (0, readSync_js_1.readSync)(this.rid, p); + } + seek(_offset, _whence) { + throw new Error("Method not implemented."); + } + seekSync(_offset, _whence) { + throw new Error("Method not implemented."); + } + async stat() { + return await (0, fstat_js_1.fstat)(this.rid); + } + statSync() { + return (0, fstatSync_js_1.fstatSync)(this.rid); + } + close() { + fs.closeSync(this.rid); + } + get readable() { + throw new Error("Not implemented."); + } + get writable() { + throw new Error("Not implemented."); + } +} +exports.FsFile = FsFile; +const File = FsFile; +exports.File = File; + + +/***/ }), + +/***/ 90751: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +var _a, _b; +var _c; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PermissionStatus = void 0; +// The listeners don't actually matter because the state of these permissions +// is constant and mocked as Node.js has all doors open. +(_a = (_c = globalThis).EventTarget) !== null && _a !== void 0 ? _a : (_c.EventTarget = (_b = (__nccwpck_require__(82361).EventTarget)) !== null && _b !== void 0 ? _b : null); +class PermissionStatus extends EventTarget { + /** @internal */ + constructor(state) { + super(); + this.state = state; + this.onchange = null; + } +} +exports.PermissionStatus = PermissionStatus; + + +/***/ }), + +/***/ 30711: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Permissions = void 0; +const PermissionStatus_js_1 = __nccwpck_require__(90751); +class Permissions { + query(_desc) { + return Promise.resolve(new PermissionStatus_js_1.PermissionStatus("granted")); + } + revoke(_desc) { + return Promise.resolve(new PermissionStatus_js_1.PermissionStatus("denied")); + } + request(desc) { + return this.query(desc); + } +} +exports.Permissions = Permissions; + + +/***/ }), + +/***/ 56914: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SeekMode = void 0; +var SeekMode_js_1 = __nccwpck_require__(60874); +Object.defineProperty(exports, "SeekMode", ({ enumerable: true, get: function () { return SeekMode_js_1.SeekMode; } })); + + +/***/ }), + +/***/ 60874: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SeekMode = void 0; +var SeekMode; +(function (SeekMode) { + SeekMode[SeekMode["Start"] = 0] = "Start"; + SeekMode[SeekMode["Current"] = 1] = "Current"; + SeekMode[SeekMode["End"] = 2] = "End"; +})(SeekMode = exports.SeekMode || (exports.SeekMode = {})); + + +/***/ }), + +/***/ 35082: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// Command palette -> Organize imports +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readSync = exports.readLinkSync = exports.readLink = exports.readFileSync = exports.readFile = exports.readDirSync = exports.readDir = exports.read = exports.openSync = exports.open = exports.mkdirSync = exports.mkdir = exports.memoryUsage = exports.makeTempFileSync = exports.makeTempFile = exports.makeTempDirSync = exports.makeTempDir = exports.lstatSync = exports.lstat = exports.listenTls = exports.listen = exports.linkSync = exports.link = exports.kill = exports.inspect = exports.ftruncateSync = exports.ftruncate = exports.fsyncSync = exports.fsync = exports.fstatSync = exports.fstat = exports.fdatasyncSync = exports.fdatasync = exports.exit = exports.execPath = exports.cwd = exports.createSync = exports.create = exports.copyFileSync = exports.copyFile = exports.copy = exports.connectTls = exports.connect = exports.close = exports.chownSync = exports.chown = exports.chmodSync = exports.chmod = exports.chdir = exports.isatty = void 0; +exports.args = exports.writeTextFileSync = exports.writeTextFile = exports.writeSync = exports.writeFileSync = exports.writeFile = exports.write = exports.watchFs = exports.truncateSync = exports.truncate = exports.test = exports.symlinkSync = exports.symlink = exports.statSync = exports.stat = exports.shutdown = exports.run = exports.Process = exports.renameSync = exports.rename = exports.removeSync = exports.remove = exports.realPathSync = exports.realPath = exports.readTextFileSync = exports.readTextFile = void 0; +var tty_1 = __nccwpck_require__(76224); +Object.defineProperty(exports, "isatty", ({ enumerable: true, get: function () { return tty_1.isatty; } })); +var chdir_js_1 = __nccwpck_require__(58914); +Object.defineProperty(exports, "chdir", ({ enumerable: true, get: function () { return chdir_js_1.chdir; } })); +var chmod_js_1 = __nccwpck_require__(33236); +Object.defineProperty(exports, "chmod", ({ enumerable: true, get: function () { return chmod_js_1.chmod; } })); +var chmodSync_js_1 = __nccwpck_require__(74299); +Object.defineProperty(exports, "chmodSync", ({ enumerable: true, get: function () { return chmodSync_js_1.chmodSync; } })); +var chown_js_1 = __nccwpck_require__(27306); +Object.defineProperty(exports, "chown", ({ enumerable: true, get: function () { return chown_js_1.chown; } })); +var chownSync_js_1 = __nccwpck_require__(40472); +Object.defineProperty(exports, "chownSync", ({ enumerable: true, get: function () { return chownSync_js_1.chownSync; } })); +var close_js_1 = __nccwpck_require__(44781); +Object.defineProperty(exports, "close", ({ enumerable: true, get: function () { return close_js_1.close; } })); +var connect_js_1 = __nccwpck_require__(35075); +Object.defineProperty(exports, "connect", ({ enumerable: true, get: function () { return connect_js_1.connect; } })); +var connectTls_js_1 = __nccwpck_require__(50237); +Object.defineProperty(exports, "connectTls", ({ enumerable: true, get: function () { return connectTls_js_1.connectTls; } })); +var copy_js_1 = __nccwpck_require__(35748); +Object.defineProperty(exports, "copy", ({ enumerable: true, get: function () { return copy_js_1.copy; } })); +var copyFile_js_1 = __nccwpck_require__(94268); +Object.defineProperty(exports, "copyFile", ({ enumerable: true, get: function () { return copyFile_js_1.copyFile; } })); +var copyFileSync_js_1 = __nccwpck_require__(56957); +Object.defineProperty(exports, "copyFileSync", ({ enumerable: true, get: function () { return copyFileSync_js_1.copyFileSync; } })); +var create_js_1 = __nccwpck_require__(27109); +Object.defineProperty(exports, "create", ({ enumerable: true, get: function () { return create_js_1.create; } })); +var createSync_js_1 = __nccwpck_require__(15736); +Object.defineProperty(exports, "createSync", ({ enumerable: true, get: function () { return createSync_js_1.createSync; } })); +var cwd_js_1 = __nccwpck_require__(98296); +Object.defineProperty(exports, "cwd", ({ enumerable: true, get: function () { return cwd_js_1.cwd; } })); +var execPath_js_1 = __nccwpck_require__(56531); +Object.defineProperty(exports, "execPath", ({ enumerable: true, get: function () { return execPath_js_1.execPath; } })); +var exit_js_1 = __nccwpck_require__(30830); +Object.defineProperty(exports, "exit", ({ enumerable: true, get: function () { return exit_js_1.exit; } })); +var fdatasync_js_1 = __nccwpck_require__(26640); +Object.defineProperty(exports, "fdatasync", ({ enumerable: true, get: function () { return fdatasync_js_1.fdatasync; } })); +var fdatasyncSync_js_1 = __nccwpck_require__(5226); +Object.defineProperty(exports, "fdatasyncSync", ({ enumerable: true, get: function () { return fdatasyncSync_js_1.fdatasyncSync; } })); +var fstat_js_1 = __nccwpck_require__(44667); +Object.defineProperty(exports, "fstat", ({ enumerable: true, get: function () { return fstat_js_1.fstat; } })); +var fstatSync_js_1 = __nccwpck_require__(40301); +Object.defineProperty(exports, "fstatSync", ({ enumerable: true, get: function () { return fstatSync_js_1.fstatSync; } })); +var fsync_js_1 = __nccwpck_require__(97965); +Object.defineProperty(exports, "fsync", ({ enumerable: true, get: function () { return fsync_js_1.fsync; } })); +var fsyncSync_js_1 = __nccwpck_require__(81540); +Object.defineProperty(exports, "fsyncSync", ({ enumerable: true, get: function () { return fsyncSync_js_1.fsyncSync; } })); +var ftruncate_js_1 = __nccwpck_require__(6203); +Object.defineProperty(exports, "ftruncate", ({ enumerable: true, get: function () { return ftruncate_js_1.ftruncate; } })); +var ftruncateSync_js_1 = __nccwpck_require__(45758); +Object.defineProperty(exports, "ftruncateSync", ({ enumerable: true, get: function () { return ftruncateSync_js_1.ftruncateSync; } })); +var inspect_js_1 = __nccwpck_require__(56559); +Object.defineProperty(exports, "inspect", ({ enumerable: true, get: function () { return inspect_js_1.inspect; } })); +var kill_js_1 = __nccwpck_require__(37009); +Object.defineProperty(exports, "kill", ({ enumerable: true, get: function () { return kill_js_1.kill; } })); +var link_js_1 = __nccwpck_require__(12767); +Object.defineProperty(exports, "link", ({ enumerable: true, get: function () { return link_js_1.link; } })); +var linkSync_js_1 = __nccwpck_require__(10908); +Object.defineProperty(exports, "linkSync", ({ enumerable: true, get: function () { return linkSync_js_1.linkSync; } })); +var listen_js_1 = __nccwpck_require__(85046); +Object.defineProperty(exports, "listen", ({ enumerable: true, get: function () { return listen_js_1.listen; } })); +var listenTls_js_1 = __nccwpck_require__(66936); +Object.defineProperty(exports, "listenTls", ({ enumerable: true, get: function () { return listenTls_js_1.listenTls; } })); +var lstat_js_1 = __nccwpck_require__(72694); +Object.defineProperty(exports, "lstat", ({ enumerable: true, get: function () { return lstat_js_1.lstat; } })); +var lstatSync_js_1 = __nccwpck_require__(36916); +Object.defineProperty(exports, "lstatSync", ({ enumerable: true, get: function () { return lstatSync_js_1.lstatSync; } })); +var makeTempDir_js_1 = __nccwpck_require__(54361); +Object.defineProperty(exports, "makeTempDir", ({ enumerable: true, get: function () { return makeTempDir_js_1.makeTempDir; } })); +var makeTempDirSync_js_1 = __nccwpck_require__(54491); +Object.defineProperty(exports, "makeTempDirSync", ({ enumerable: true, get: function () { return makeTempDirSync_js_1.makeTempDirSync; } })); +var makeTempFile_js_1 = __nccwpck_require__(10484); +Object.defineProperty(exports, "makeTempFile", ({ enumerable: true, get: function () { return makeTempFile_js_1.makeTempFile; } })); +var makeTempFileSync_js_1 = __nccwpck_require__(16541); +Object.defineProperty(exports, "makeTempFileSync", ({ enumerable: true, get: function () { return makeTempFileSync_js_1.makeTempFileSync; } })); +var memoryUsage_js_1 = __nccwpck_require__(69021); +Object.defineProperty(exports, "memoryUsage", ({ enumerable: true, get: function () { return memoryUsage_js_1.memoryUsage; } })); +var mkdir_js_1 = __nccwpck_require__(64987); +Object.defineProperty(exports, "mkdir", ({ enumerable: true, get: function () { return mkdir_js_1.mkdir; } })); +var mkdirSync_js_1 = __nccwpck_require__(52404); +Object.defineProperty(exports, "mkdirSync", ({ enumerable: true, get: function () { return mkdirSync_js_1.mkdirSync; } })); +var open_js_1 = __nccwpck_require__(35217); +Object.defineProperty(exports, "open", ({ enumerable: true, get: function () { return open_js_1.open; } })); +var openSync_js_1 = __nccwpck_require__(81070); +Object.defineProperty(exports, "openSync", ({ enumerable: true, get: function () { return openSync_js_1.openSync; } })); +var read_js_1 = __nccwpck_require__(7653); +Object.defineProperty(exports, "read", ({ enumerable: true, get: function () { return read_js_1.read; } })); +var readDir_js_1 = __nccwpck_require__(14766); +Object.defineProperty(exports, "readDir", ({ enumerable: true, get: function () { return readDir_js_1.readDir; } })); +var readDirSync_js_1 = __nccwpck_require__(24128); +Object.defineProperty(exports, "readDirSync", ({ enumerable: true, get: function () { return readDirSync_js_1.readDirSync; } })); +var readFile_js_1 = __nccwpck_require__(19838); +Object.defineProperty(exports, "readFile", ({ enumerable: true, get: function () { return readFile_js_1.readFile; } })); +var readFileSync_js_1 = __nccwpck_require__(41575); +Object.defineProperty(exports, "readFileSync", ({ enumerable: true, get: function () { return readFileSync_js_1.readFileSync; } })); +var readLink_js_1 = __nccwpck_require__(37278); +Object.defineProperty(exports, "readLink", ({ enumerable: true, get: function () { return readLink_js_1.readLink; } })); +var readLinkSync_js_1 = __nccwpck_require__(32318); +Object.defineProperty(exports, "readLinkSync", ({ enumerable: true, get: function () { return readLinkSync_js_1.readLinkSync; } })); +var readSync_js_1 = __nccwpck_require__(27537); +Object.defineProperty(exports, "readSync", ({ enumerable: true, get: function () { return readSync_js_1.readSync; } })); +var readTextFile_js_1 = __nccwpck_require__(15584); +Object.defineProperty(exports, "readTextFile", ({ enumerable: true, get: function () { return readTextFile_js_1.readTextFile; } })); +var readTextFileSync_js_1 = __nccwpck_require__(10887); +Object.defineProperty(exports, "readTextFileSync", ({ enumerable: true, get: function () { return readTextFileSync_js_1.readTextFileSync; } })); +var realPath_js_1 = __nccwpck_require__(12428); +Object.defineProperty(exports, "realPath", ({ enumerable: true, get: function () { return realPath_js_1.realPath; } })); +var realPathSync_js_1 = __nccwpck_require__(68232); +Object.defineProperty(exports, "realPathSync", ({ enumerable: true, get: function () { return realPathSync_js_1.realPathSync; } })); +var remove_js_1 = __nccwpck_require__(67882); +Object.defineProperty(exports, "remove", ({ enumerable: true, get: function () { return remove_js_1.remove; } })); +var removeSync_js_1 = __nccwpck_require__(66225); +Object.defineProperty(exports, "removeSync", ({ enumerable: true, get: function () { return removeSync_js_1.removeSync; } })); +var rename_js_1 = __nccwpck_require__(72946); +Object.defineProperty(exports, "rename", ({ enumerable: true, get: function () { return rename_js_1.rename; } })); +var renameSync_js_1 = __nccwpck_require__(29995); +Object.defineProperty(exports, "renameSync", ({ enumerable: true, get: function () { return renameSync_js_1.renameSync; } })); +var run_js_1 = __nccwpck_require__(81158); +Object.defineProperty(exports, "Process", ({ enumerable: true, get: function () { return run_js_1.Process; } })); +Object.defineProperty(exports, "run", ({ enumerable: true, get: function () { return run_js_1.run; } })); +var shutdown_js_1 = __nccwpck_require__(84122); +Object.defineProperty(exports, "shutdown", ({ enumerable: true, get: function () { return shutdown_js_1.shutdown; } })); +var stat_js_1 = __nccwpck_require__(29006); +Object.defineProperty(exports, "stat", ({ enumerable: true, get: function () { return stat_js_1.stat; } })); +var statSync_js_1 = __nccwpck_require__(22627); +Object.defineProperty(exports, "statSync", ({ enumerable: true, get: function () { return statSync_js_1.statSync; } })); +var symlink_js_1 = __nccwpck_require__(73162); +Object.defineProperty(exports, "symlink", ({ enumerable: true, get: function () { return symlink_js_1.symlink; } })); +var symlinkSync_js_1 = __nccwpck_require__(51041); +Object.defineProperty(exports, "symlinkSync", ({ enumerable: true, get: function () { return symlinkSync_js_1.symlinkSync; } })); +var test_js_1 = __nccwpck_require__(24305); +Object.defineProperty(exports, "test", ({ enumerable: true, get: function () { return test_js_1.test; } })); +var truncate_js_1 = __nccwpck_require__(42947); +Object.defineProperty(exports, "truncate", ({ enumerable: true, get: function () { return truncate_js_1.truncate; } })); +var truncateSync_js_1 = __nccwpck_require__(721); +Object.defineProperty(exports, "truncateSync", ({ enumerable: true, get: function () { return truncateSync_js_1.truncateSync; } })); +var watchFs_js_1 = __nccwpck_require__(71351); +Object.defineProperty(exports, "watchFs", ({ enumerable: true, get: function () { return watchFs_js_1.watchFs; } })); +var write_js_1 = __nccwpck_require__(63178); +Object.defineProperty(exports, "write", ({ enumerable: true, get: function () { return write_js_1.write; } })); +var writeFile_js_1 = __nccwpck_require__(44553); +Object.defineProperty(exports, "writeFile", ({ enumerable: true, get: function () { return writeFile_js_1.writeFile; } })); +var writeFileSync_js_1 = __nccwpck_require__(54356); +Object.defineProperty(exports, "writeFileSync", ({ enumerable: true, get: function () { return writeFileSync_js_1.writeFileSync; } })); +var writeSync_js_1 = __nccwpck_require__(8331); +Object.defineProperty(exports, "writeSync", ({ enumerable: true, get: function () { return writeSync_js_1.writeSync; } })); +var writeTextFile_js_1 = __nccwpck_require__(23238); +Object.defineProperty(exports, "writeTextFile", ({ enumerable: true, get: function () { return writeTextFile_js_1.writeTextFile; } })); +var writeTextFileSync_js_1 = __nccwpck_require__(55538); +Object.defineProperty(exports, "writeTextFileSync", ({ enumerable: true, get: function () { return writeTextFileSync_js_1.writeTextFileSync; } })); +var args_js_1 = __nccwpck_require__(23710); +Object.defineProperty(exports, "args", ({ enumerable: true, get: function () { return args_js_1.args; } })); + + +/***/ }), + +/***/ 58914: +/***/ (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.chdir = void 0; +const url_1 = __nccwpck_require__(57310); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const chdir = function (path) { + try { + return process.chdir(path instanceof URL ? (0, url_1.fileURLToPath)(path) : path); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new variables_js_1.errors.NotFound(`No such file or directory (os error 2), chdir '${path}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.chdir = chdir; + + +/***/ }), + +/***/ 33236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +exports.chmod = fs.chmod; + + +/***/ }), + +/***/ 74299: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.chmodSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.chmodSync = fs.chmodSync; + + +/***/ }), + +/***/ 27306: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.chown = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const chown = async (path, uid, gid) => await fs.chown(path, uid !== null && uid !== void 0 ? uid : -1, gid !== null && gid !== void 0 ? gid : -1); +exports.chown = chown; + + +/***/ }), + +/***/ 40472: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.chownSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const chownSync = (path, uid, gid) => fs.chownSync(path, uid !== null && uid !== void 0 ? uid : -1, gid !== null && gid !== void 0 ? gid : -1); +exports.chownSync = chownSync; + + +/***/ }), + +/***/ 44781: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.close = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.close = fs.closeSync; + + +/***/ }), + +/***/ 35075: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.connect = void 0; +const net_1 = __nccwpck_require__(41808); +const Conn_js_1 = __nccwpck_require__(59395); +const connect = function connect(options) { + if (options.transport === "unix") { + throw new Error("Unstable UnixConnectOptions is not implemented"); + } + const { transport = "tcp", hostname = "127.0.0.1", port } = options; + if (transport !== "tcp") { + throw new Error("Deno.connect is only implemented for transport: tcp"); + } + const socket = (0, net_1.createConnection)({ port, host: hostname }); + socket.on("error", (err) => console.error(err)); + return new Promise((resolve) => { + socket.once("connect", () => { + // @ts-expect-error undocumented socket._handle property + const rid = socket._handle.fd; + const localAddr = { + // cannot be undefined while socket is connected + hostname: socket.localAddress, + port: socket.localPort, + transport: "tcp", + }; + const remoteAddr = { + // cannot be undefined while socket is connected + hostname: socket.remoteAddress, + port: socket.remotePort, + transport: "tcp", + }; + resolve(new Conn_js_1.Conn(rid, localAddr, remoteAddr, socket)); + }); + }); +}; +exports.connect = connect; + + +/***/ }), + +/***/ 50237: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.connectTls = void 0; +const tls_1 = __nccwpck_require__(24404); +const Conn_js_1 = __nccwpck_require__(59395); +const readTextFile_js_1 = __nccwpck_require__(15584); +const connectTls = async function connectTls({ port, hostname = "127.0.0.1", certFile }) { + const cert = certFile && await (0, readTextFile_js_1.readTextFile)(certFile); + const socket = (0, tls_1.connect)({ port, host: hostname, cert }); + return new Promise((resolve) => { + socket.on("connect", () => { + // @ts-expect-error undocumented socket._handle property + const rid = socket._handle.fd; + const localAddr = { + // cannot be undefined while socket is connected + hostname: socket.localAddress, + port: socket.localPort, + transport: "tcp", + }; + const remoteAddr = { + // cannot be undefined while socket is connected + hostname: socket.remoteAddress, + port: socket.remotePort, + transport: "tcp", + }; + resolve(new Conn_js_1.TlsConn(rid, localAddr, remoteAddr, socket)); + }); + }); +}; +exports.connectTls = connectTls; + + +/***/ }), + +/***/ 35748: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.copy = void 0; +const consts_js_1 = __nccwpck_require__(49046); +const copy = async function copy(src, dst, options) { + var _a; + let n = 0; + const bufSize = (_a = options === null || options === void 0 ? void 0 : options.bufSize) !== null && _a !== void 0 ? _a : consts_js_1.DEFAULT_BUFFER_SIZE; + const b = new Uint8Array(bufSize); + let gotEOF = false; + while (gotEOF === false) { + const result = await src.read(b); + if (result === null) { + gotEOF = true; + } + else { + let nwritten = 0; + while (nwritten < result) { + nwritten += await dst.write(b.subarray(nwritten, result)); + } + n += nwritten; + } + } + return n; +}; +exports.copy = copy; + + +/***/ }), + +/***/ 94268: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.copyFile = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const errors = __importStar(__nccwpck_require__(82826)); +const copyFile = async (src, dest) => { + try { + await fs.copyFile(src, dest); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new errors.NotFound(`File not found, copy '${src}' -> '${dest}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.copyFile = copyFile; + + +/***/ }), + +/***/ 56957: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.copyFileSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const errors = __importStar(__nccwpck_require__(82826)); +const copyFileSync = (src, dest) => { + try { + fs.copyFileSync(src, dest); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new errors.NotFound(`File not found, copy '${src}' -> '${dest}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.copyFileSync = copyFileSync; + + +/***/ }), + +/***/ 27109: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.create = void 0; +const open_js_1 = __nccwpck_require__(35217); +const create = async function create(path) { + return await (0, open_js_1.open)(path, { write: true, create: true, truncate: true }); +}; +exports.create = create; + + +/***/ }), + +/***/ 15736: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createSync = void 0; +const openSync_js_1 = __nccwpck_require__(81070); +const createSync = function createSync(path) { + return (0, openSync_js_1.openSync)(path, { + create: true, + truncate: true, + read: true, + write: true, + }); +}; +exports.createSync = createSync; + + +/***/ }), + +/***/ 98296: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.cwd = void 0; +exports.cwd = process.cwd; + + +/***/ }), + +/***/ 56531: +/***/ (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.execPath = void 0; +const which_1 = __importDefault(__nccwpck_require__(34207)); +const execPath = () => which_1.default.sync("deno"); +exports.execPath = execPath; + + +/***/ }), + +/***/ 30830: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.exit = void 0; +const exit = function exit(code) { + return process.exit(code); +}; +exports.exit = exit; + + +/***/ }), + +/***/ 26640: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fdatasync = void 0; +const fs_1 = __nccwpck_require__(57147); +const util_1 = __nccwpck_require__(73837); +const _fdatasync = (0, util_1.promisify)(fs_1.fdatasync); +exports.fdatasync = _fdatasync; + + +/***/ }), + +/***/ 5226: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fdatasyncSync = void 0; +const fs_1 = __nccwpck_require__(57147); +exports.fdatasyncSync = fs_1.fdatasyncSync; + + +/***/ }), + +/***/ 44667: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fstat = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const util_1 = __nccwpck_require__(73837); +const stat_js_1 = __nccwpck_require__(29006); +const nodeFstat = (0, util_1.promisify)(fs.fstat); +const fstat = async function (fd) { + return (0, stat_js_1.denoifyFileInfo)(await nodeFstat(fd)); +}; +exports.fstat = fstat; + + +/***/ }), + +/***/ 40301: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fstatSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const stat_js_1 = __nccwpck_require__(29006); +const fstatSync = function fstatSync(fd) { + return (0, stat_js_1.denoifyFileInfo)((0, fs_1.fstatSync)(fd)); +}; +exports.fstatSync = fstatSync; + + +/***/ }), + +/***/ 97965: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fsync = void 0; +const fs_1 = __nccwpck_require__(57147); +const util_1 = __nccwpck_require__(73837); +const fsync = function fsync(rid) { + return (0, util_1.promisify)(fs_1.fsync)(rid); +}; +exports.fsync = fsync; + + +/***/ }), + +/***/ 81540: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fsyncSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const fsyncSync = function fsyncSync(rid) { + return (0, fs_1.fsyncSync)(rid); +}; +exports.fsyncSync = fsyncSync; + + +/***/ }), + +/***/ 6203: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ftruncate = void 0; +const fs_1 = __nccwpck_require__(57147); +const util_1 = __nccwpck_require__(73837); +const _ftruncate = (0, util_1.promisify)(fs_1.ftruncate); +exports.ftruncate = _ftruncate; + + +/***/ }), + +/***/ 45758: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ftruncateSync = void 0; +const fs_1 = __nccwpck_require__(57147); +exports.ftruncateSync = fs_1.ftruncateSync; + + +/***/ }), + +/***/ 56559: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.inspect = void 0; +const util = __importStar(__nccwpck_require__(73837)); +const inspect = (value, options = {}) => util.inspect(value, options); +exports.inspect = inspect; + + +/***/ }), + +/***/ 37009: +/***/ (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.kill = void 0; +const os_1 = __importDefault(__nccwpck_require__(22037)); +const process_1 = __importDefault(__nccwpck_require__(77282)); +const kill = function (pid, signo) { + if (pid < 0 && os_1.default.platform() === "win32") { + throw new TypeError("Invalid pid"); + } + process_1.default.kill(pid, signo); +}; +exports.kill = kill; + + +/***/ }), + +/***/ 12767: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.link = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +exports.link = fs.link; + + +/***/ }), + +/***/ 10908: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.linkSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.linkSync = fs.linkSync; + + +/***/ }), + +/***/ 85046: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listen = void 0; +const net_1 = __nccwpck_require__(41808); +const Conn_js_1 = __nccwpck_require__(59395); +const Listener_js_1 = __nccwpck_require__(6068); +async function* _listen(server, waitFor) { + await waitFor; + while (server.listening) { + yield new Promise((resolve) => server.once("connection", (socket) => { + socket.on("error", (err) => console.error(err)); + // @ts-expect-error undocumented socket._handle property + const rid = socket._handle.fd; + const localAddr = { + // cannot be undefined while socket is connected + hostname: socket.localAddress, + port: socket.localPort, + transport: "tcp", + }; + const remoteAddr = { + // cannot be undefined while socket is connected + hostname: socket.remoteAddress, + port: socket.remotePort, + transport: "tcp", + }; + resolve(new Conn_js_1.Conn(rid, localAddr, remoteAddr)); + })); + } +} +const listen = function listen(options) { + if (options.transport === "unix") { + throw new Error("Unstable UnixListenOptions is not implemented"); + } + const { port, hostname = "0.0.0.0", transport = "tcp" } = options; + if (transport !== "tcp") { + throw new Error("Deno.listen is only implemented for transport: tcp"); + } + const server = (0, net_1.createServer)(); + const waitFor = new Promise((resolve) => + // server._handle.fd is assigned immediately on .listen() + server.listen(port, hostname, resolve)); + // @ts-expect-error undocumented socket._handle property + const listener = new Listener_js_1.Listener(server._handle.fd, { + hostname, + port, + transport: "tcp", + }, _listen(server, waitFor)); + return listener; +}; +exports.listen = listen; + + +/***/ }), + +/***/ 66936: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.listenTls = void 0; +const tls_1 = __nccwpck_require__(24404); +const Conn_js_1 = __nccwpck_require__(59395); +const Listener_js_1 = __nccwpck_require__(6068); +const readTextFileSync_js_1 = __nccwpck_require__(10887); +async function* _listen(server, waitFor) { + await waitFor; + while (server.listening) { + yield new Promise((resolve) => server.once("secureConnection", (socket) => { + socket.on("error", (err) => console.error(err)); + // @ts-expect-error undocumented socket._handle property + const rid = socket._handle.fd; + const localAddr = { + // cannot be undefined while socket is connected + hostname: socket.localAddress, + port: socket.localPort, + transport: "tcp", + }; + const remoteAddr = { + // cannot be undefined while socket is connected + hostname: socket.remoteAddress, + port: socket.remotePort, + transport: "tcp", + }; + resolve(new Conn_js_1.TlsConn(rid, localAddr, remoteAddr)); + })); + } +} +const listenTls = function listen({ port, hostname = "0.0.0.0", transport = "tcp", certFile, keyFile }) { + if (transport !== "tcp") { + throw new Error("Deno.listen is only implemented for transport: tcp"); + } + const [cert, key] = [certFile, keyFile].map((f) => f == null ? undefined : (0, readTextFileSync_js_1.readTextFileSync)(f)); + const server = (0, tls_1.createServer)({ cert, key }); + const waitFor = new Promise((resolve) => + // server._handle.fd is assigned immediately on .listen() + server.listen(port, hostname, resolve)); + // @ts-expect-error undocumented socket._handle property + const listener = new Listener_js_1.Listener(server._handle.fd, { + hostname, + port, + transport: "tcp", + }, _listen(server, waitFor)); + return listener; +}; +exports.listenTls = listenTls; + + +/***/ }), + +/***/ 72694: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.lstat = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const stat_js_1 = __nccwpck_require__(29006); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const lstat = async (path) => { + try { + return (0, stat_js_1.denoifyFileInfo)(await fs.lstat(path)); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.lstat = lstat; + + +/***/ }), + +/***/ 36916: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.lstatSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const stat_js_1 = __nccwpck_require__(29006); +const lstatSync = (path) => (0, stat_js_1.denoifyFileInfo)(fs.lstatSync(path)); +exports.lstatSync = lstatSync; + + +/***/ }), + +/***/ 54361: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeTempDir = void 0; +const promises_1 = __nccwpck_require__(73292); +const path_1 = __nccwpck_require__(71017); +const os_1 = __nccwpck_require__(22037); +const makeTempDir = function makeTempDir({ prefix = "" } = {}) { + return (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), prefix || "/")); +}; +exports.makeTempDir = makeTempDir; + + +/***/ }), + +/***/ 54491: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeTempDirSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const path_1 = __nccwpck_require__(71017); +const os_1 = __nccwpck_require__(22037); +const makeTempDirSync = function makeTempDirSync({ prefix = "" } = {}) { + return (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), prefix || "/")); +}; +exports.makeTempDirSync = makeTempDirSync; + + +/***/ }), + +/***/ 10484: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeTempFile = void 0; +const os_1 = __nccwpck_require__(22037); +const path_1 = __nccwpck_require__(71017); +const random_id_js_1 = __nccwpck_require__(94970); +const writeTextFile_js_1 = __nccwpck_require__(23238); +const makeTempFile = async function makeTempFile({ prefix = "" } = {}) { + const name = (0, path_1.join)((0, os_1.tmpdir)(), prefix, (0, random_id_js_1.randomId)()); + await (0, writeTextFile_js_1.writeTextFile)(name, ""); + return name; +}; +exports.makeTempFile = makeTempFile; + + +/***/ }), + +/***/ 16541: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.makeTempFileSync = void 0; +const os_1 = __nccwpck_require__(22037); +const path_1 = __nccwpck_require__(71017); +const random_id_js_1 = __nccwpck_require__(94970); +const writeTextFileSync_js_1 = __nccwpck_require__(55538); +const makeTempFileSync = function makeTempFileSync({ prefix = "" } = {}) { + const name = (0, path_1.join)((0, os_1.tmpdir)(), prefix, (0, random_id_js_1.randomId)()); + (0, writeTextFileSync_js_1.writeTextFileSync)(name, ""); + return name; +}; +exports.makeTempFileSync = makeTempFileSync; + + +/***/ }), + +/***/ 69021: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.memoryUsage = void 0; +exports.memoryUsage = process.memoryUsage; + + +/***/ }), + +/***/ 64987: +/***/ (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.mkdir = void 0; +const promises_1 = __nccwpck_require__(73292); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const mkdir = async function mkdir(path, options) { + try { + await (0, promises_1.mkdir)(path, options); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "EEXIST") { + throw new variables_js_1.errors.AlreadyExists(`File exists (os error 17), mkdir '${path}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.mkdir = mkdir; + + +/***/ }), + +/***/ 52404: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mkdirSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const mkdirSync = (path, options) => { + try { + fs.mkdirSync(path, options); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "EEXIST") { + throw new variables_js_1.errors.AlreadyExists(`File exists (os error 17), mkdir '${path}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.mkdirSync = mkdirSync; + + +/***/ }), + +/***/ 35217: +/***/ (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.open = void 0; +const fs_1 = __nccwpck_require__(57147); +const util_1 = __nccwpck_require__(73837); +const FsFile_js_1 = __nccwpck_require__(61631); +const fs_flags_js_1 = __nccwpck_require__(8423); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const nodeOpen = (0, util_1.promisify)(fs_1.open); +const open = async function open(path, { read, write, append, truncate, create, createNew, mode = 0o666 } = { + read: true, +}) { + const flagMode = (0, fs_flags_js_1.getFsFlag)({ + read, + write, + append, + truncate, + create, + createNew, + }); + try { + const fd = await nodeOpen(path, flagMode, mode); + return new FsFile_js_1.File(fd); + } + catch (err) { + throw (0, errorMap_js_1.default)(err); + } +}; +exports.open = open; + + +/***/ }), + +/***/ 81070: +/***/ (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.openSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const FsFile_js_1 = __nccwpck_require__(61631); +const fs_flags_js_1 = __nccwpck_require__(8423); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const openSync = function openSync(path, { read, write, append, truncate, create, createNew, mode = 0o666 } = { + read: true, +}) { + const flagMode = (0, fs_flags_js_1.getFsFlag)({ + read, + write, + append, + truncate, + create, + createNew, + }); + try { + const fd = (0, fs_1.openSync)(path, flagMode, mode); + return new FsFile_js_1.File(fd); + } + catch (err) { + throw (0, errorMap_js_1.default)(err); + } +}; +exports.openSync = openSync; + + +/***/ }), + +/***/ 7653: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.read = void 0; +const util_1 = __nccwpck_require__(73837); +const fs_1 = __nccwpck_require__(57147); +const _read = (0, util_1.promisify)(fs_1.read); +const read = async function read(rid, buffer) { + if (buffer == null) { + throw new TypeError("Buffer must not be null."); + } + if (buffer.length === 0) { + return 0; + } + const { bytesRead } = await _read(rid, buffer, 0, buffer.length, null); + // node returns 0 on EOF, Deno expects null + return bytesRead === 0 ? null : bytesRead; +}; +exports.read = read; + + +/***/ }), + +/***/ 14766: +/***/ (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.readDir = void 0; +const promises_1 = __nccwpck_require__(73292); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readDir = async function* readDir(path) { + try { + for await (const e of await (0, promises_1.opendir)(String(path))) { + const ent = { + name: e.name, + isFile: e.isFile(), + isDirectory: e.isDirectory(), + isSymlink: e.isSymbolicLink(), + }; + yield ent; + } + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readDir = readDir; + + +/***/ }), + +/***/ 24128: +/***/ (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.readDirSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readDirSync = function* readDir(path) { + try { + for (const e of (0, fs_1.readdirSync)(String(path), { withFileTypes: true })) { + const ent = { + name: e.name, + isFile: e.isFile(), + isDirectory: e.isDirectory(), + isSymlink: e.isSymbolicLink(), + }; + yield ent; + } + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readDirSync = readDirSync; + + +/***/ }), + +/***/ 19838: +/***/ (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.readFile = void 0; +const promises_1 = __nccwpck_require__(73292); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readFile = async function readFile(path, { signal } = {}) { + try { + const buf = await (0, promises_1.readFile)(path, { signal }); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.length); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readFile = readFile; + + +/***/ }), + +/***/ 41575: +/***/ (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.readFileSync = void 0; +const fs_1 = __nccwpck_require__(57147); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readFileSync = function readFileSync(path) { + try { + const buf = (0, fs_1.readFileSync)(path); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.length); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readFileSync = readFileSync; + + +/***/ }), + +/***/ 37278: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readLink = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +exports.readLink = fs.readlink; + + +/***/ }), + +/***/ 32318: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readLinkSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.readLinkSync = fs.readlinkSync; + + +/***/ }), + +/***/ 27537: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const readSync = (fd, buffer) => { + const bytesRead = fs.readSync(fd, buffer); + // node returns 0 on EOF, Deno expects null + return bytesRead === 0 ? null : bytesRead; +}; +exports.readSync = readSync; + + +/***/ }), + +/***/ 15584: +/***/ (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.readTextFile = void 0; +const promises_1 = __nccwpck_require__(73292); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readTextFile = async (path, { signal } = {}) => { + try { + return await (0, promises_1.readFile)(path, { encoding: "utf8", signal }); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readTextFile = readTextFile; + + +/***/ }), + +/***/ 10887: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.readTextFileSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const readTextFileSync = function (path) { + try { + return fs.readFileSync(path, "utf8"); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.readTextFileSync = readTextFileSync; + + +/***/ }), + +/***/ 12428: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.realPath = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +exports.realPath = fs.realpath; + + +/***/ }), + +/***/ 68232: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.realPathSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.realPathSync = fs.realpathSync; + + +/***/ }), + +/***/ 67882: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.remove = void 0; +const promises_1 = __nccwpck_require__(73292); +const remove = async function remove(path, options = {}) { + const innerOptions = options.recursive + ? { recursive: true, force: true } + : {}; + try { + return await (0, promises_1.rm)(path, innerOptions); + } + catch (err) { + if (err.code === "ERR_FS_EISDIR") { + return await (0, promises_1.rmdir)(path, innerOptions); + } + else { + throw err; + } + } +}; +exports.remove = remove; + + +/***/ }), + +/***/ 66225: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.removeSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const removeSync = (path, options = {}) => { + const innerOptions = options.recursive + ? { recursive: true, force: true } + : {}; + try { + fs.rmSync(path, innerOptions); + } + catch (err) { + if (err.code === "ERR_FS_EISDIR") { + fs.rmdirSync(path, innerOptions); + } + else { + throw err; + } + } +}; +exports.removeSync = removeSync; + + +/***/ }), + +/***/ 72946: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.rename = void 0; +const promises_1 = __nccwpck_require__(73292); +const rename = function rename(oldpath, newpath) { + return (0, promises_1.rename)(oldpath, newpath); +}; +exports.rename = rename; + + +/***/ }), + +/***/ 29995: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.renameSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.renameSync = fs.renameSync; + + +/***/ }), + +/***/ 81158: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __classPrivateFieldSet = (this && this.__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; +}; +var __classPrivateFieldGet = (this && this.__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); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _Process_process, _Process_stderr, _Process_stdout, _Process_stdin, _Process_status, _Process_receivedStatus, _ProcessReadStream_stream, _ProcessReadStream_bufferStreamReader, _ProcessReadStream_closed, _ProcessWriteStream_stream, _ProcessWriteStream_streamWriter, _ProcessWriteStream_closed; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Process = exports.run = void 0; +const child_process_1 = __importDefault(__nccwpck_require__(32081)); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const os_1 = __importDefault(__nccwpck_require__(22037)); +const url_1 = __importDefault(__nccwpck_require__(57310)); +const events_1 = __nccwpck_require__(82361); +const which_1 = __importDefault(__nccwpck_require__(34207)); +const streams_js_1 = __nccwpck_require__(95040); +const errors = __importStar(__nccwpck_require__(82826)); +const run = function run(options) { + const [cmd, ...args] = options.cmd; + if (options.cwd && !fs_1.default.existsSync(options.cwd)) { + throw new Error("The directory name is invalid."); + } + // childProcess.spawn will asynchronously check if the command exists, but + // we need to do this synchronously + const commandName = getCmd(cmd); + if (!which_1.default.sync(commandName, { nothrow: true })) { + throw new errors.NotFound("The system cannot find the file specified."); + } + const process = child_process_1.default.spawn(commandName, args, { + cwd: options.cwd, + env: getEnv(options), + uid: options.uid, + gid: options.gid, + shell: false, + stdio: [ + getStdio(options.stdin, "in"), + getStdio(options.stdout, "out"), + getStdio(options.stderr, "out"), + ], + }); + return new Process(process); +}; +exports.run = run; +function getStdio(value, kind) { + if (value === "inherit" || value == null) { + return "inherit"; // default + } + else if (value === "piped") { + return "pipe"; + } + else if (value === "null") { + return "ignore"; + } + else if (typeof value === "number") { + switch (kind) { + case "in": + return fs_1.default.createReadStream(null, { fd: value }); + case "out": + return fs_1.default.createWriteStream(null, { fd: value }); + default: { + const _assertNever = kind; + throw new Error("Unreachable."); + } + } + } + else { + const _assertNever = value; + throw new Error("Unknown value."); + } +} +function getCmd(firstArg) { + if (firstArg instanceof URL) { + return url_1.default.fileURLToPath(firstArg); + } + else { + return firstArg; + } +} +function getEnv(options) { + var _a; + const env = (_a = options.env) !== null && _a !== void 0 ? _a : {}; + for (const name in process.env) { + if (!Object.prototype.hasOwnProperty.call(env, name)) { + if (options.clearEnv) { + if (os_1.default.platform() === "win32") { + env[name] = ""; + } + else { + delete env[name]; + } + } + else { + env[name] = process.env[name]; + } + } + } + return env; +} +class Process { + /** @internal */ + constructor(process) { + var _a, _b, _c; + _Process_process.set(this, void 0); + _Process_stderr.set(this, void 0); + _Process_stdout.set(this, void 0); + _Process_stdin.set(this, void 0); + _Process_status.set(this, void 0); + _Process_receivedStatus.set(this, false); + __classPrivateFieldSet(this, _Process_process, process, "f"); + __classPrivateFieldSet(this, _Process_stdout, (_a = ProcessReadStream.fromNullable(__classPrivateFieldGet(this, _Process_process, "f").stdout)) !== null && _a !== void 0 ? _a : null, "f"); + __classPrivateFieldSet(this, _Process_stderr, (_b = ProcessReadStream.fromNullable(__classPrivateFieldGet(this, _Process_process, "f").stderr)) !== null && _b !== void 0 ? _b : null, "f"); + __classPrivateFieldSet(this, _Process_stdin, (_c = ProcessWriteStream.fromNullable(__classPrivateFieldGet(this, _Process_process, "f").stdin)) !== null && _c !== void 0 ? _c : null, "f"); + __classPrivateFieldSet(this, _Process_status, (0, events_1.once)(process, "exit"), "f"); + } + get rid() { + // todo: useful to return something? + return NaN; + } + get pid() { + // only undefined when the process doesn't spawn, in which case this + // will never be reached + return __classPrivateFieldGet(this, _Process_process, "f").pid; + } + get stdin() { + return __classPrivateFieldGet(this, _Process_stdin, "f"); + } + get stdout() { + return __classPrivateFieldGet(this, _Process_stdout, "f"); + } + get stderr() { + return __classPrivateFieldGet(this, _Process_stderr, "f"); + } + async status() { + const [receivedCode, signalName] = await __classPrivateFieldGet(this, _Process_status, "f"); + // when there is a signal, the exit code is 128 + signal code + const signal = signalName + ? os_1.default.constants.signals[signalName] + : receivedCode > 128 + ? receivedCode - 128 + : undefined; + const code = receivedCode != null + ? receivedCode + : signal != null + ? 128 + signal + : undefined; + const success = code === 0; + __classPrivateFieldSet(this, _Process_receivedStatus, true, "f"); + return { code, signal, success }; + } + async output() { + if (!__classPrivateFieldGet(this, _Process_stdout, "f")) { + throw new TypeError("stdout was not piped"); + } + const result = await __classPrivateFieldGet(this, _Process_stdout, "f").readAll(); + __classPrivateFieldGet(this, _Process_stdout, "f").close(); + return result; + } + async stderrOutput() { + if (!__classPrivateFieldGet(this, _Process_stderr, "f")) { + throw new TypeError("stderr was not piped"); + } + const result = await __classPrivateFieldGet(this, _Process_stderr, "f").readAll(); + __classPrivateFieldGet(this, _Process_stderr, "f").close(); + return result; + } + close() { + // Deno doesn't close any stdio streams here + __classPrivateFieldGet(this, _Process_process, "f").unref(); + __classPrivateFieldGet(this, _Process_process, "f").kill(); + } + kill(signo) { + if (__classPrivateFieldGet(this, _Process_receivedStatus, "f")) { + throw new errors.NotFound("entity not found"); + } + __classPrivateFieldGet(this, _Process_process, "f").kill(signo); + } +} +exports.Process = Process; +_Process_process = new WeakMap(), _Process_stderr = new WeakMap(), _Process_stdout = new WeakMap(), _Process_stdin = new WeakMap(), _Process_status = new WeakMap(), _Process_receivedStatus = new WeakMap(); +class ProcessReadStream { + constructor(stream) { + _ProcessReadStream_stream.set(this, void 0); + _ProcessReadStream_bufferStreamReader.set(this, void 0); + _ProcessReadStream_closed.set(this, false); + __classPrivateFieldSet(this, _ProcessReadStream_stream, stream, "f"); + __classPrivateFieldSet(this, _ProcessReadStream_bufferStreamReader, new streams_js_1.BufferStreamReader(stream), "f"); + } + static fromNullable(stream) { + return stream ? new ProcessReadStream(stream) : undefined; + } + readAll() { + if (__classPrivateFieldGet(this, _ProcessReadStream_closed, "f")) { + return Promise.resolve(new Uint8Array(0)); + } + else { + return __classPrivateFieldGet(this, _ProcessReadStream_bufferStreamReader, "f").readAll(); + } + } + read(p) { + if (__classPrivateFieldGet(this, _ProcessReadStream_closed, "f")) { + return Promise.resolve(null); + } + else { + return __classPrivateFieldGet(this, _ProcessReadStream_bufferStreamReader, "f").read(p); + } + } + close() { + __classPrivateFieldSet(this, _ProcessReadStream_closed, true, "f"); + __classPrivateFieldGet(this, _ProcessReadStream_stream, "f").destroy(); + } + get readable() { + throw new Error("Not implemented."); + } + get writable() { + throw new Error("Not implemented."); + } +} +_ProcessReadStream_stream = new WeakMap(), _ProcessReadStream_bufferStreamReader = new WeakMap(), _ProcessReadStream_closed = new WeakMap(); +class ProcessWriteStream { + constructor(stream) { + _ProcessWriteStream_stream.set(this, void 0); + _ProcessWriteStream_streamWriter.set(this, void 0); + _ProcessWriteStream_closed.set(this, false); + __classPrivateFieldSet(this, _ProcessWriteStream_stream, stream, "f"); + __classPrivateFieldSet(this, _ProcessWriteStream_streamWriter, new streams_js_1.StreamWriter(stream), "f"); + } + static fromNullable(stream) { + return stream ? new ProcessWriteStream(stream) : undefined; + } + write(p) { + if (__classPrivateFieldGet(this, _ProcessWriteStream_closed, "f")) { + return Promise.resolve(0); + } + else { + return __classPrivateFieldGet(this, _ProcessWriteStream_streamWriter, "f").write(p); + } + } + close() { + __classPrivateFieldSet(this, _ProcessWriteStream_closed, true, "f"); + __classPrivateFieldGet(this, _ProcessWriteStream_stream, "f").end(); + } +} +_ProcessWriteStream_stream = new WeakMap(), _ProcessWriteStream_streamWriter = new WeakMap(), _ProcessWriteStream_closed = new WeakMap(); + + +/***/ }), + +/***/ 84122: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.shutdown = void 0; +const net_1 = __nccwpck_require__(41808); +const shutdown = async function shutdown(rid) { + await new Promise((resolve) => new net_1.Socket({ fd: rid }).end(resolve)); +}; +exports.shutdown = shutdown; + + +/***/ }), + +/***/ 29006: +/***/ (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.stat = exports.denoifyFileInfo = void 0; +const promises_1 = __nccwpck_require__(73292); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +function denoifyFileInfo(s) { + return { + atime: s.atime, + birthtime: s.birthtime, + blksize: s.blksize, + blocks: s.blocks, + dev: s.dev, + gid: s.gid, + ino: s.ino, + isDirectory: s.isDirectory(), + isFile: s.isFile(), + isSymlink: s.isSymbolicLink(), + mode: s.mode, + mtime: s.mtime, + nlink: s.nlink, + rdev: s.rdev, + size: s.size, + uid: s.uid, + }; +} +exports.denoifyFileInfo = denoifyFileInfo; +const stat = async (path) => { + try { + return denoifyFileInfo(await (0, promises_1.stat)(path)); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.stat = stat; + + +/***/ }), + +/***/ 22627: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.statSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const stat_js_1 = __nccwpck_require__(29006); +const statSync = (path) => (0, stat_js_1.denoifyFileInfo)(fs.statSync(path)); +exports.statSync = statSync; + + +/***/ }), + +/***/ 73162: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.symlink = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const symlink = async (oldpath, newpath, options) => await fs.symlink(oldpath, newpath, options === null || options === void 0 ? void 0 : options.type); +exports.symlink = symlink; + + +/***/ }), + +/***/ 51041: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.symlinkSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const symlinkSync = (oldpath, newpath, options) => fs.symlinkSync(oldpath, newpath, options === null || options === void 0 ? void 0 : options.type); +exports.symlinkSync = symlinkSync; + + +/***/ }), + +/***/ 24305: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.test = void 0; +var shim_deno_test_1 = __nccwpck_require__(19766); +Object.defineProperty(exports, "test", ({ enumerable: true, get: function () { return shim_deno_test_1.test; } })); + + +/***/ }), + +/***/ 42947: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.truncate = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const truncate = async (name, len) => { + try { + return await fs.truncate(name, len); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new variables_js_1.errors.NotFound(`No such file or directory (os error 2), truncate '${name}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.truncate = truncate; + + +/***/ }), + +/***/ 721: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.truncateSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const truncateSync = (name, len) => { + try { + return fs.truncateSync(name, len); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new variables_js_1.errors.NotFound(`No such file or directory (os error 2), truncate '${name}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.truncateSync = truncateSync; + + +/***/ }), + +/***/ 71351: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.watchFs = void 0; +const promises_1 = __nccwpck_require__(73292); +const path_1 = __nccwpck_require__(71017); +const iterutil_js_1 = __nccwpck_require__(32341); +const watchFs = function watchFs(paths, options = { recursive: true }) { + paths = Array.isArray(paths) ? paths : [paths]; + const ac = new AbortController(); + const { signal } = ac; + // TODO(mkr): create valid rids for watchers + const rid = -1; + const masterWatcher = (0, iterutil_js_1.merge)(paths.map((path) => (0, iterutil_js_1.mapAsync)((0, promises_1.watch)(path, { recursive: options === null || options === void 0 ? void 0 : options.recursive, signal }), (info) => ({ + kind: "modify", + paths: [(0, path_1.resolve)(path, info.filename)], + })))); + function close() { + ac.abort(); + } + return Object.assign(masterWatcher, { rid, close }); +}; +exports.watchFs = watchFs; + + +/***/ }), + +/***/ 63178: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.write = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const util_1 = __nccwpck_require__(73837); +const nodeWrite = (0, util_1.promisify)(fs.write); +const write = async (fd, data) => { + const { bytesWritten } = await nodeWrite(fd, data); + return bytesWritten; +}; +exports.write = write; + + +/***/ }), + +/***/ 44553: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeFile = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const fs_flags_js_1 = __nccwpck_require__(8423); +const writeFile = async function writeFile(path, data, { append = false, create = true, mode, signal } = {}) { + const truncate = create && !append; + const flag = (0, fs_flags_js_1.getFsFlag)({ append, create, truncate, write: true }); + try { + await fs.writeFile(path, data, { flag, signal }); + if (mode !== undefined) + await fs.chmod(path, mode); + } + catch (error) { + throw (0, errorMap_js_1.default)(error); + } +}; +exports.writeFile = writeFile; + + +/***/ }), + +/***/ 54356: +/***/ (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.writeFileSync = void 0; +const os_1 = __nccwpck_require__(22037); +const openSync_js_1 = __nccwpck_require__(81070); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const statSync_js_1 = __nccwpck_require__(22627); +const chmodSync_js_1 = __nccwpck_require__(74299); +const writeFileSync = function writeFileSync(path, data, options = {}) { + try { + if (options.create !== undefined) { + const create = !!options.create; + if (!create) { + // verify that file exists + (0, statSync_js_1.statSync)(path); + } + } + const openOptions = options.append + ? { write: true, create: true, append: true } + : { write: true, create: true, truncate: true }; + const file = (0, openSync_js_1.openSync)(path, openOptions); + if (options.mode !== undefined && + options.mode !== null && + (0, os_1.platform)() !== "win32") { + (0, chmodSync_js_1.chmodSync)(path, options.mode); + } + let nwritten = 0; + while (nwritten < data.length) { + nwritten += file.writeSync(data.subarray(nwritten)); + } + file.close(); + } + catch (e) { + throw (0, errorMap_js_1.default)(e); + } +}; +exports.writeFileSync = writeFileSync; + + +/***/ }), + +/***/ 8331: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +exports.writeSync = fs.writeSync; + + +/***/ }), + +/***/ 23238: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeTextFile = void 0; +const fs = __importStar(__nccwpck_require__(73292)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const fs_flags_js_1 = __nccwpck_require__(8423); +const writeTextFile = async function writeTextFile(path, data, { append = false, create = true, mode, signal } = {}) { + const truncate = create && !append; + const flag = (0, fs_flags_js_1.getFsFlag)({ append, create, truncate, write: true }); + try { + await fs.writeFile(path, data, { flag, mode, signal }); + if (mode !== undefined) + await fs.chmod(path, mode); + } + catch (error) { + throw (0, errorMap_js_1.default)(error); + } +}; +exports.writeTextFile = writeTextFile; + + +/***/ }), + +/***/ 55538: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeTextFileSync = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const writeTextFileSync = (path, data, { append = false, create = true, mode } = {}) => { + const flag = create ? (append ? "a" : "w") : "r+"; + try { + fs.writeFileSync(path, data, { flag, mode }); + if (mode !== undefined) + fs.chmodSync(path, mode); + } + catch (error) { + throw (0, errorMap_js_1.default)(error); + } +}; +exports.writeTextFileSync = writeTextFileSync; + + +/***/ }), + +/***/ 63367: +/***/ (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); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(9136), exports); +__exportStar(__nccwpck_require__(56914), exports); +__exportStar(__nccwpck_require__(35082), exports); +__exportStar(__nccwpck_require__(99780), exports); +__exportStar(__nccwpck_require__(9335), exports); + + +/***/ }), + +/***/ 99780: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +/// + + +/***/ }), + +/***/ 9335: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = exports.resources = exports.ppid = exports.pid = exports.permissions = exports.noColor = exports.metrics = exports.mainModule = exports.errors = exports.env = exports.customInspect = exports.build = void 0; +var build_js_1 = __nccwpck_require__(4102); +Object.defineProperty(exports, "build", ({ enumerable: true, get: function () { return build_js_1.build; } })); +var customInspect_js_1 = __nccwpck_require__(74535); +Object.defineProperty(exports, "customInspect", ({ enumerable: true, get: function () { return customInspect_js_1.customInspect; } })); +var env_js_1 = __nccwpck_require__(89702); +Object.defineProperty(exports, "env", ({ enumerable: true, get: function () { return env_js_1.env; } })); +exports.errors = __importStar(__nccwpck_require__(82826)); +var mainModule_js_1 = __nccwpck_require__(49117); +Object.defineProperty(exports, "mainModule", ({ enumerable: true, get: function () { return mainModule_js_1.mainModule; } })); +var metrics_js_1 = __nccwpck_require__(26710); +Object.defineProperty(exports, "metrics", ({ enumerable: true, get: function () { return metrics_js_1.metrics; } })); +var noColor_js_1 = __nccwpck_require__(46612); +Object.defineProperty(exports, "noColor", ({ enumerable: true, get: function () { return noColor_js_1.noColor; } })); +var permissions_js_1 = __nccwpck_require__(70170); +Object.defineProperty(exports, "permissions", ({ enumerable: true, get: function () { return permissions_js_1.permissions; } })); +var pid_js_1 = __nccwpck_require__(80993); +Object.defineProperty(exports, "pid", ({ enumerable: true, get: function () { return pid_js_1.pid; } })); +var ppid_js_1 = __nccwpck_require__(9093); +Object.defineProperty(exports, "ppid", ({ enumerable: true, get: function () { return ppid_js_1.ppid; } })); +var resources_js_1 = __nccwpck_require__(10277); +Object.defineProperty(exports, "resources", ({ enumerable: true, get: function () { return resources_js_1.resources; } })); +__exportStar(__nccwpck_require__(35141), exports); +var version_js_1 = __nccwpck_require__(32101); +Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return version_js_1.version; } })); + + +/***/ }), + +/***/ 23710: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.args = void 0; +exports.args = process.argv.slice(2); + + +/***/ }), + +/***/ 4102: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/// +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.build = void 0; +const os = __importStar(__nccwpck_require__(22037)); +exports.build = { + arch: "x86_64", + os: ((p) => p === "win32" ? "windows" : p === "darwin" ? "darwin" : "linux")(os.platform()), + vendor: "pc", + target: ((p) => p === "win32" + ? "x86_64-pc-windows-msvc" + : p === "darwin" + ? "x86_64-apple-darwin" + : "x86_64-unknown-linux-gnu")(os.platform()), +}; + + +/***/ }), + +/***/ 74535: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.customInspect = void 0; +exports.customInspect = Symbol.for("nodejs.util.inspect.custom"); + + +/***/ }), + +/***/ 89702: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.env = void 0; +exports.env = { + get(key) { + return process.env[key]; + }, + set(key, value) { + process.env[key] = value; + }, + delete(key) { + delete process.env[key]; + }, + // @ts-expect-error https://github.com/denoland/deno/issues/10267 + toObject() { + return { ...process.env }; + }, +}; + + +/***/ }), + +/***/ 82826: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WriteZero = exports.UnexpectedEof = exports.TimedOut = exports.PermissionDenied = exports.NotFound = exports.NotConnected = exports.InvalidData = exports.Interrupted = exports.Http = exports.ConnectionReset = exports.ConnectionRefused = exports.ConnectionAborted = exports.Busy = exports.BrokenPipe = exports.BadResource = exports.AlreadyExists = exports.AddrNotAvailable = exports.AddrInUse = void 0; +// please keep sorted +class AddrInUse extends Error { +} +exports.AddrInUse = AddrInUse; +class AddrNotAvailable extends Error { +} +exports.AddrNotAvailable = AddrNotAvailable; +class AlreadyExists extends Error { +} +exports.AlreadyExists = AlreadyExists; +class BadResource extends Error { +} +exports.BadResource = BadResource; +class BrokenPipe extends Error { +} +exports.BrokenPipe = BrokenPipe; +class Busy extends Error { +} +exports.Busy = Busy; +class ConnectionAborted extends Error { +} +exports.ConnectionAborted = ConnectionAborted; +class ConnectionRefused extends Error { +} +exports.ConnectionRefused = ConnectionRefused; +class ConnectionReset extends Error { +} +exports.ConnectionReset = ConnectionReset; +class Http extends Error { +} +exports.Http = Http; +class Interrupted extends Error { +} +exports.Interrupted = Interrupted; +class InvalidData extends Error { +} +exports.InvalidData = InvalidData; +class NotConnected extends Error { +} +exports.NotConnected = NotConnected; +class NotFound extends Error { +} +exports.NotFound = NotFound; +class PermissionDenied extends Error { +} +exports.PermissionDenied = PermissionDenied; +class TimedOut extends Error { +} +exports.TimedOut = TimedOut; +class UnexpectedEof extends Error { +} +exports.UnexpectedEof = UnexpectedEof; +class WriteZero extends Error { +} +exports.WriteZero = WriteZero; + + +/***/ }), + +/***/ 49117: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var _a, _b; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mainModule = void 0; +/// +const path_1 = __nccwpck_require__(71017); +const url_1 = __nccwpck_require__(57310); +exports.mainModule = (0, url_1.pathToFileURL)((_b = (_a = require.main) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : (0, path_1.join)(__dirname, "$deno$repl.ts")).href; + + +/***/ }), + +/***/ 26710: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.metrics = void 0; +const metrics = function metrics() { + return { + opsDispatched: 0, + opsDispatchedSync: 0, + opsDispatchedAsync: 0, + opsDispatchedAsyncUnref: 0, + opsCompleted: 0, + opsCompletedSync: 0, + opsCompletedAsync: 0, + opsCompletedAsyncUnref: 0, + bytesSentControl: 0, + bytesSentData: 0, + bytesReceived: 0, + ops: {}, + }; +}; +exports.metrics = metrics; + + +/***/ }), + +/***/ 46612: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.noColor = void 0; +exports.noColor = process.env.NO_COLOR !== undefined; + + +/***/ }), + +/***/ 70170: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.permissions = void 0; +const Permissions_js_1 = __nccwpck_require__(30711); +exports.permissions = new Permissions_js_1.Permissions(); + + +/***/ }), + +/***/ 80993: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.pid = void 0; +exports.pid = process.pid; + + +/***/ }), + +/***/ 9093: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ppid = void 0; +exports.ppid = process.ppid; + + +/***/ }), + +/***/ 10277: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resources = void 0; +const resources = function resources() { + console.warn([ + "Deno.resources() shim returns a dummy object that does not update.", + "If you think this is a mistake, raise an issue at https://github.com/denoland/node_deno_shims/issues", + ].join("\n")); + return {}; +}; +exports.resources = resources; + + +/***/ }), + +/***/ 35141: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.stderr = exports.stdout = exports.stdin = void 0; +function chain(fn, cleanup) { + let prev; + return function _fn(...args) { + const curr = (prev || Promise.resolve()) + .then(() => fn(...args)) + .finally(cleanup || (() => { })) + .then((result) => { + if (prev === curr) + prev = undefined; + return result; + }); + return (prev = curr); + }; +} +exports.stdin = { + rid: 0, + read: chain((p) => { + return new Promise((resolve, reject) => { + process.stdin.resume(); + process.stdin.on("error", onerror); + process.stdin.once("readable", () => { + var _a; + process.stdin.off("error", onerror); + const data = (_a = process.stdin.read(p.length)) !== null && _a !== void 0 ? _a : process.stdin.read(); + if (data) { + p.set(data); + resolve(data.length > 0 ? data.length : null); + } + else { + resolve(null); + } + }); + function onerror(error) { + reject(error); + process.stdin.off("error", onerror); + } + }); + }, () => process.stdin.pause()), + get readable() { + throw new Error("Not implemented."); + }, + readSync() { + // Node.js doesn't support readSync for stdin + throw new Error("Not implemented."); + }, + close() { + process.stdin.destroy(); + }, +}; +exports.stdout = { + rid: 1, + write: chain((p) => { + return new Promise((resolve) => { + const result = process.stdout.write(p); + if (!result) { + process.stdout.once("drain", () => resolve(p.length)); + } + else { + resolve(p.length); + } + }); + }), + get writable() { + throw new Error("Not implemented."); + }, + writeSync() { + // Node.js doesn't support writeSync for stdout + throw new Error("Not implemented"); + }, + close() { + process.stdout.destroy(); + }, +}; +exports.stderr = { + rid: 2, + write: chain((p) => { + return new Promise((resolve) => { + const result = process.stderr.write(p); + if (!result) { + process.stderr.once("drain", () => resolve(p.length)); + } + else { + resolve(p.length); + } + }); + }), + get writable() { + throw new Error("Not implemented."); + }, + writeSync() { + // Node.js doesn't support writeSync for stderr + throw new Error("Not implemented"); + }, + close() { + process.stderr.destroy(); + }, +}; + + +/***/ }), + +/***/ 32101: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +/// +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +const version_js_1 = __nccwpck_require__(70717); +exports.version = { + deno: version_js_1.deno, + typescript: version_js_1.typescript, + v8: process.versions.v8, +}; + + +/***/ }), + +/***/ 43032: +/***/ (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.sleepSync = exports.utimeSync = exports.utime = exports.futimeSync = exports.futime = void 0; +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const errorMap_js_1 = __importDefault(__nccwpck_require__(50937)); +const variables_js_1 = __nccwpck_require__(9335); +const futime = async function (rid, atime, mtime) { + try { + await new Promise((resolve, reject) => { + // doesn't exist in fs.promises + fs_1.default.futimes(rid, atime, mtime, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }); + } + catch (error) { + throw (0, errorMap_js_1.default)(error); + } +}; +exports.futime = futime; +const futimeSync = function (rid, atime, mtime) { + try { + fs_1.default.futimesSync(rid, atime, mtime); + } + catch (error) { + throw (0, errorMap_js_1.default)(error); + } +}; +exports.futimeSync = futimeSync; +const utime = async function (path, atime, mtime) { + try { + await fs_1.default.promises.utimes(path, atime, mtime); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new variables_js_1.errors.NotFound(`No such file or directory (os error 2), utime '${path}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.utime = utime; +const utimeSync = function (path, atime, mtime) { + try { + fs_1.default.utimesSync(path, atime, mtime); + } + catch (error) { + if ((error === null || error === void 0 ? void 0 : error.code) === "ENOENT") { + throw new variables_js_1.errors.NotFound(`No such file or directory (os error 2), utime '${path}'`); + } + throw (0, errorMap_js_1.default)(error); + } +}; +exports.utimeSync = utimeSync; +const sleepSync = function (milliseconds) { + // https://github.com/sindresorhus/sleep-synchronously/blob/main/index.js + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); +}; +exports.sleepSync = sleepSync; + + +/***/ }), + +/***/ 95882: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Deno = void 0; +exports.Deno = __importStar(__nccwpck_require__(32854)); + + /***/ }), /***/ 56664: @@ -172394,7 +172032,7 @@ exports["default"] = { */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = __nccwpck_require__(53461); +const platform_1 = __nccwpck_require__(99957); const version_1 = __nccwpck_require__(98996); const semver_1 = __nccwpck_require__(81522); const major = version_1.VERSION.split('.')[0]; @@ -172796,7 +172434,7 @@ exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); /***/ }), -/***/ 53461: +/***/ 99957: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -175606,194 +175244,6 @@ PEMEncoder.prototype.encode = function encode (data, options) { module.exports = PEMEncoder -/***/ }), - -/***/ 75696: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const atob = __nccwpck_require__(84732); -const btoa = __nccwpck_require__(50012); - -module.exports = { - atob, - btoa -}; - - -/***/ }), - -/***/ 84732: -/***/ ((module) => { - -"use strict"; - - -/** - * Implementation of atob() according to the HTML and Infra specs, except that - * instead of throwing INVALID_CHARACTER_ERR we return null. - */ -function atob(data) { - // Web IDL requires DOMStrings to just be converted using ECMAScript - // ToString, which in our case amounts to using a template literal. - data = `${data}`; - // "Remove all ASCII whitespace from data." - data = data.replace(/[ \t\n\f\r]/g, ""); - // "If data's length divides by 4 leaving no remainder, then: if data ends - // with one or two U+003D (=) code points, then remove them from data." - if (data.length % 4 === 0) { - data = data.replace(/==?$/, ""); - } - // "If data's length divides by 4 leaving a remainder of 1, then return - // failure." - // - // "If data contains a code point that is not one of - // - // U+002B (+) - // U+002F (/) - // ASCII alphanumeric - // - // then return failure." - if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { - return null; - } - // "Let output be an empty byte sequence." - let output = ""; - // "Let buffer be an empty buffer that can have bits appended to it." - // - // We append bits via left-shift and or. accumulatedBits is used to track - // when we've gotten to 24 bits. - let buffer = 0; - let accumulatedBits = 0; - // "Let position be a position variable for data, initially pointing at the - // start of data." - // - // "While position does not point past the end of data:" - for (let i = 0; i < data.length; i++) { - // "Find the code point pointed to by position in the second column of - // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in - // the first cell of the same row. - // - // "Append to buffer the six bits corresponding to n, most significant bit - // first." - // - // atobLookup() implements the table from RFC 4648. - buffer <<= 6; - buffer |= atobLookup(data[i]); - accumulatedBits += 6; - // "If buffer has accumulated 24 bits, interpret them as three 8-bit - // big-endian numbers. Append three bytes with values equal to those - // numbers to output, in the same order, and then empty buffer." - if (accumulatedBits === 24) { - output += String.fromCharCode((buffer & 0xff0000) >> 16); - output += String.fromCharCode((buffer & 0xff00) >> 8); - output += String.fromCharCode(buffer & 0xff); - buffer = accumulatedBits = 0; - } - // "Advance position by 1." - } - // "If buffer is not empty, it contains either 12 or 18 bits. If it contains - // 12 bits, then discard the last four and interpret the remaining eight as - // an 8-bit big-endian number. If it contains 18 bits, then discard the last - // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append - // the one or two bytes with values equal to those one or two numbers to - // output, in the same order." - if (accumulatedBits === 12) { - buffer >>= 4; - output += String.fromCharCode(buffer); - } else if (accumulatedBits === 18) { - buffer >>= 2; - output += String.fromCharCode((buffer & 0xff00) >> 8); - output += String.fromCharCode(buffer & 0xff); - } - // "Return output." - return output; -} -/** - * A lookup table for atob(), which converts an ASCII character to the - * corresponding six-bit number. - */ - -const keystr = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -function atobLookup(chr) { - const index = keystr.indexOf(chr); - // Throw exception if character is not in the lookup string; should not be hit in tests - return index < 0 ? undefined : index; -} - -module.exports = atob; - - -/***/ }), - -/***/ 50012: -/***/ ((module) => { - -"use strict"; - - -/** - * btoa() as defined by the HTML and Infra specs, which mostly just references - * RFC 4648. - */ -function btoa(s) { - let i; - // String conversion as required by Web IDL. - s = `${s}`; - // "The btoa() method must throw an "InvalidCharacterError" DOMException if - // data contains any character whose code point is greater than U+00FF." - for (i = 0; i < s.length; i++) { - if (s.charCodeAt(i) > 255) { - return null; - } - } - let out = ""; - for (i = 0; i < s.length; i += 3) { - const groupsOfSix = [undefined, undefined, undefined, undefined]; - groupsOfSix[0] = s.charCodeAt(i) >> 2; - groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4; - if (s.length > i + 1) { - groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4; - groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2; - } - if (s.length > i + 2) { - groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6; - groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f; - } - for (let j = 0; j < groupsOfSix.length; j++) { - if (typeof groupsOfSix[j] === "undefined") { - out += "="; - } else { - out += btoaLookup(groupsOfSix[j]); - } - } - } - return out; -} - -/** - * Lookup table for btoa(), which converts a six-bit number into the - * corresponding ASCII character. - */ -const keystr = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -function btoaLookup(index) { - if (index >= 0 && index < 64) { - return keystr[index]; - } - - // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests. - return undefined; -} - -module.exports = btoa; - - /***/ }), /***/ 61231: @@ -215138,6 +214588,9 @@ function RequestSigner(request, credentials) { request.hostname = headers.Host || headers.host this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' + + this.extraHeadersToIgnore = request.extraHeadersToIgnore || Object.create(null) + this.extraHeadersToInclude = request.extraHeadersToInclude || Object.create(null) } RequestSigner.prototype.matchHost = function(host) { @@ -215147,7 +214600,7 @@ RequestSigner.prototype.matchHost = function(host) { // ES's hostParts are sometimes the other way round, if the value that is expected // to be region equals ‘es’ switch them back // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com - if (hostParts[1] === 'es') + if (hostParts[1] === 'es' || hostParts[1] === 'aoss') hostParts = hostParts.reverse() if (hostParts[1] == 's3') { @@ -215371,9 +214824,14 @@ RequestSigner.prototype.canonicalHeaders = function() { } RequestSigner.prototype.signedHeaders = function() { + var extraHeadersToInclude = this.extraHeadersToInclude, + extraHeadersToIgnore = this.extraHeadersToIgnore return Object.keys(this.request.headers) .map(function(key) { return key.toLowerCase() }) - .filter(function(key) { return HEADERS_TO_IGNORE[key] == null }) + .filter(function(key) { + return extraHeadersToInclude[key] || + (HEADERS_TO_IGNORE[key] == null && !extraHeadersToIgnore[key]) + }) .sort() .join(';') } @@ -216733,40 +216191,6 @@ function expand(str, isTop) { -/***/ }), - -/***/ 65653: -/***/ ((module) => { - -module.exports = process.hrtime || hrtime - -// polyfil for window.performance.now -var performance = global.performance || {} -var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() } - -// generate timestamp or delta -// see http://nodejs.org/api/process.html#process_process_hrtime -function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3 - var seconds = Math.floor(clocktime) - var nanoseconds = Math.floor((clocktime%1)*1e9) - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0] - nanoseconds = nanoseconds - previousTimestamp[1] - if (nanoseconds<0) { - seconds-- - nanoseconds += 1e9 - } - } - return [seconds,nanoseconds] -} - /***/ }), /***/ 29700: @@ -219058,12942 +218482,6 @@ function resolveCommand(parsed) { module.exports = resolveCommand; -/***/ }), - -/***/ 27455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule), - MatcherList: (__nccwpck_require__(25458).MatcherList) -}; -///CommonJS - - -/** - * @constructor - * @see https://developer.mozilla.org/en/CSS/@-moz-document - */ -CSSOM.CSSDocumentRule = function CSSDocumentRule() { - CSSOM.CSSRule.call(this); - this.matcher = new CSSOM.MatcherList(); - this.cssRules = []; -}; - -CSSOM.CSSDocumentRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSDocumentRule.prototype.constructor = CSSOM.CSSDocumentRule; -CSSOM.CSSDocumentRule.prototype.type = 10; -//FIXME -//CSSOM.CSSDocumentRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSDocumentRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -Object.defineProperty(CSSOM.CSSDocumentRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@-moz-document " + this.matcher.matcherText + " {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSDocumentRule = CSSOM.CSSDocumentRule; -///CommonJS - - -/***/ }), - -/***/ 33046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), - CSSRule: (__nccwpck_require__(23364).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#css-font-face-rule - */ -CSSOM.CSSFontFaceRule = function CSSFontFaceRule() { - CSSOM.CSSRule.call(this); - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSFontFaceRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule; -CSSOM.CSSFontFaceRule.prototype.type = 5; -//FIXME -//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSFontFaceRule.cpp -Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", { - get: function() { - return "@font-face {" + this.style.cssText + "}"; - } -}); - - -//.CommonJS -exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; -///CommonJS - - -/***/ }), - -/***/ 57986: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/shadow-dom/#host-at-rule - */ -CSSOM.CSSHostRule = function CSSHostRule() { - CSSOM.CSSRule.call(this); - this.cssRules = []; -}; - -CSSOM.CSSHostRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule; -CSSOM.CSSHostRule.prototype.type = 1001; -//FIXME -//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@host {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSHostRule = CSSOM.CSSHostRule; -///CommonJS - - -/***/ }), - -/***/ 49776: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule), - CSSStyleSheet: (__nccwpck_require__(62486).CSSStyleSheet), - MediaList: (__nccwpck_require__(63849).MediaList) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssimportrule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule - */ -CSSOM.CSSImportRule = function CSSImportRule() { - CSSOM.CSSRule.call(this); - this.href = ""; - this.media = new CSSOM.MediaList(); - this.styleSheet = new CSSOM.CSSStyleSheet(); -}; - -CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; -CSSOM.CSSImportRule.prototype.type = 3; - -Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { - get: function() { - var mediaText = this.media.mediaText; - return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";"; - }, - set: function(cssText) { - var i = 0; - - /** - * @import url(partial.css) screen, handheld; - * || | - * after-import media - * | - * url - */ - var state = ''; - - var buffer = ''; - var index; - for (var character; (character = cssText.charAt(i)); i++) { - - switch (character) { - case ' ': - case '\t': - case '\r': - case '\n': - case '\f': - if (state === 'after-import') { - state = 'url'; - } else { - buffer += character; - } - break; - - case '@': - if (!state && cssText.indexOf('@import', i) === i) { - state = 'after-import'; - i += 'import'.length; - buffer = ''; - } - break; - - case 'u': - if (state === 'url' && cssText.indexOf('url(', i) === i) { - index = cssText.indexOf(')', i + 1); - if (index === -1) { - throw i + ': ")" not found'; - } - i += 'url('.length; - var url = cssText.slice(i, index); - if (url[0] === url[url.length - 1]) { - if (url[0] === '"' || url[0] === "'") { - url = url.slice(1, -1); - } - } - this.href = url; - i = index; - state = 'media'; - } - break; - - case '"': - if (state === 'url') { - index = cssText.indexOf('"', i + 1); - if (!index) { - throw i + ": '\"' not found"; - } - this.href = cssText.slice(i + 1, index); - i = index; - state = 'media'; - } - break; - - case "'": - if (state === 'url') { - index = cssText.indexOf("'", i + 1); - if (!index) { - throw i + ': "\'" not found'; - } - this.href = cssText.slice(i + 1, index); - i = index; - state = 'media'; - } - break; - - case ';': - if (state === 'media') { - if (buffer) { - this.media.mediaText = buffer.trim(); - } - } - break; - - default: - if (state === 'media') { - buffer += character; - } - break; - } - } - } -}); - - -//.CommonJS -exports.CSSImportRule = CSSOM.CSSImportRule; -///CommonJS - - -/***/ }), - -/***/ 97254: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule), - CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframeRule - */ -CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { - CSSOM.CSSRule.call(this); - this.keyText = ''; - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSKeyframeRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; -CSSOM.CSSKeyframeRule.prototype.type = 8; -//FIXME -//CSSOM.CSSKeyframeRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSKeyframeRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframeRule.cpp -Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", { - get: function() { - return this.keyText + " {" + this.style.cssText + "} "; - } -}); - - -//.CommonJS -exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; -///CommonJS - - -/***/ }), - -/***/ 16005: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframesRule - */ -CSSOM.CSSKeyframesRule = function CSSKeyframesRule() { - CSSOM.CSSRule.call(this); - this.name = ''; - this.cssRules = []; -}; - -CSSOM.CSSKeyframesRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSKeyframesRule.prototype.constructor = CSSOM.CSSKeyframesRule; -CSSOM.CSSKeyframesRule.prototype.type = 7; -//FIXME -//CSSOM.CSSKeyframesRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSKeyframesRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframesRule.cpp -Object.defineProperty(CSSOM.CSSKeyframesRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(" " + this.cssRules[i].cssText); - } - return "@" + (this._vendorPrefix || '') + "keyframes " + this.name + " { \n" + cssTexts.join("\n") + "\n}"; - } -}); - - -//.CommonJS -exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; -///CommonJS - - -/***/ }), - -/***/ 96791: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule), - MediaList: (__nccwpck_require__(63849).MediaList) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssmediarule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSMediaRule - */ -CSSOM.CSSMediaRule = function CSSMediaRule() { - CSSOM.CSSRule.call(this); - this.media = new CSSOM.MediaList(); - this.cssRules = []; -}; - -CSSOM.CSSMediaRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSMediaRule.prototype.constructor = CSSOM.CSSMediaRule; -CSSOM.CSSMediaRule.prototype.type = 4; -//FIXME -//CSSOM.CSSMediaRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSMediaRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://opensource.apple.com/source/WebCore/WebCore-658.28/css/CSSMediaRule.cpp -Object.defineProperty(CSSOM.CSSMediaRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@media " + this.media.mediaText + " {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSMediaRule = CSSOM.CSSMediaRule; -///CommonJS - - -/***/ }), - -/***/ 23364: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-cssrule-interface - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule - */ -CSSOM.CSSRule = function CSSRule() { - this.parentRule = null; - this.parentStyleSheet = null; -}; - -CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete -CSSOM.CSSRule.STYLE_RULE = 1; -CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete -CSSOM.CSSRule.IMPORT_RULE = 3; -CSSOM.CSSRule.MEDIA_RULE = 4; -CSSOM.CSSRule.FONT_FACE_RULE = 5; -CSSOM.CSSRule.PAGE_RULE = 6; -CSSOM.CSSRule.KEYFRAMES_RULE = 7; -CSSOM.CSSRule.KEYFRAME_RULE = 8; -CSSOM.CSSRule.MARGIN_RULE = 9; -CSSOM.CSSRule.NAMESPACE_RULE = 10; -CSSOM.CSSRule.COUNTER_STYLE_RULE = 11; -CSSOM.CSSRule.SUPPORTS_RULE = 12; -CSSOM.CSSRule.DOCUMENT_RULE = 13; -CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14; -CSSOM.CSSRule.VIEWPORT_RULE = 15; -CSSOM.CSSRule.REGION_STYLE_RULE = 16; - - -CSSOM.CSSRule.prototype = { - constructor: CSSOM.CSSRule - //FIXME -}; - - -//.CommonJS -exports.CSSRule = CSSOM.CSSRule; -///CommonJS - - -/***/ }), - -/***/ 45131: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration - */ -CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ - this.length = 0; - this.parentRule = null; - - // NON-STANDARD - this._importants = {}; -}; - - -CSSOM.CSSStyleDeclaration.prototype = { - - constructor: CSSOM.CSSStyleDeclaration, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set. - */ - getPropertyValue: function(name) { - return this[name] || ""; - }, - - /** - * - * @param {string} name - * @param {string} value - * @param {string} [priority=null] "important" or null - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty - */ - setProperty: function(name, value, priority) { - if (this[name]) { - // Property already exist. Overwrite it. - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - this[this.length] = name; - this.length++; - } - } else { - // New property. - this[this.length] = name; - this.length++; - } - this[name] = value + ""; - this._importants[name] = priority; - }, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. - */ - removeProperty: function(name) { - if (!(name in this)) { - return ""; - } - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - return ""; - } - var prevValue = this[name]; - this[name] = ""; - - // That's what WebKit and Opera do - Array.prototype.splice.call(this, index, 1); - - // That's what Firefox does - //this[index] = "" - - return prevValue; - }, - - getPropertyCSSValue: function() { - //FIXME - }, - - /** - * - * @param {String} name - */ - getPropertyPriority: function(name) { - return this._importants[name] || ""; - }, - - - /** - * element.style.overflow = "auto" - * element.style.getPropertyShorthand("overflow-x") - * -> "overflow" - */ - getPropertyShorthand: function() { - //FIXME - }, - - isPropertyImplicit: function() { - //FIXME - }, - - // Doesn't work in IE < 9 - get cssText(){ - var properties = []; - for (var i=0, length=this.length; i < length; ++i) { - var name = this[i]; - var value = this.getPropertyValue(name); - var priority = this.getPropertyPriority(name); - if (priority) { - priority = " !" + priority; - } - properties[i] = name + ": " + value + priority + ";"; - } - return properties.join(" "); - }, - - set cssText(text){ - var i, name; - for (i = this.length; i--;) { - name = this[i]; - this[name] = ""; - } - Array.prototype.splice.call(this, 0, this.length); - this._importants = {}; - - var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; - var length = dummyRule.length; - for (i = 0; i < length; ++i) { - name = dummyRule[i]; - this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); - } - } -}; - - -//.CommonJS -exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; -CSSOM.parse = (__nccwpck_require__(18025).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js -///CommonJS - - -/***/ }), - -/***/ 4608: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), - CSSRule: (__nccwpck_require__(23364).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssstylerule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule - */ -CSSOM.CSSStyleRule = function CSSStyleRule() { - CSSOM.CSSRule.call(this); - this.selectorText = ""; - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; -CSSOM.CSSStyleRule.prototype.type = 1; - -Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { - get: function() { - var text; - if (this.selectorText) { - text = this.selectorText + " {" + this.style.cssText + "}"; - } else { - text = ""; - } - return text; - }, - set: function(cssText) { - var rule = CSSOM.CSSStyleRule.parse(cssText); - this.style = rule.style; - this.selectorText = rule.selectorText; - } -}); - - -/** - * NON-STANDARD - * lightweight version of parse.js. - * @param {string} ruleText - * @return CSSStyleRule - */ -CSSOM.CSSStyleRule.parse = function(ruleText) { - var i = 0; - var state = "selector"; - var index; - var j = i; - var buffer = ""; - - var SIGNIFICANT_WHITESPACE = { - "selector": true, - "value": true - }; - - var styleRule = new CSSOM.CSSStyleRule(); - var name, priority=""; - - for (var character; (character = ruleText.charAt(i)); i++) { - - switch (character) { - - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - if (SIGNIFICANT_WHITESPACE[state]) { - // Squash 2 or more white-spaces in the row into 1 - switch (ruleText.charAt(i - 1)) { - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - break; - default: - buffer += " "; - break; - } - } - break; - - // String - case '"': - j = i + 1; - index = ruleText.indexOf('"', j) + 1; - if (!index) { - throw '" is missing'; - } - buffer += ruleText.slice(i, index); - i = index - 1; - break; - - case "'": - j = i + 1; - index = ruleText.indexOf("'", j) + 1; - if (!index) { - throw "' is missing"; - } - buffer += ruleText.slice(i, index); - i = index - 1; - break; - - // Comment - case "/": - if (ruleText.charAt(i + 1) === "*") { - i += 2; - index = ruleText.indexOf("*/", i); - if (index === -1) { - throw new SyntaxError("Missing */"); - } else { - i = index + 1; - } - } else { - buffer += character; - } - break; - - case "{": - if (state === "selector") { - styleRule.selectorText = buffer.trim(); - buffer = ""; - state = "name"; - } - break; - - case ":": - if (state === "name") { - name = buffer.trim(); - buffer = ""; - state = "value"; - } else { - buffer += character; - } - break; - - case "!": - if (state === "value" && ruleText.indexOf("!important", i) === i) { - priority = "important"; - i += "important".length; - } else { - buffer += character; - } - break; - - case ";": - if (state === "value") { - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - state = "name"; - } else { - buffer += character; - } - break; - - case "}": - if (state === "value") { - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - } else if (state === "name") { - break; - } else { - buffer += character; - } - state = "selector"; - break; - - default: - buffer += character; - break; - - } - } - - return styleRule; - -}; - - -//.CommonJS -exports.CSSStyleRule = CSSOM.CSSStyleRule; -///CommonJS - - -/***/ }), - -/***/ 62486: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - StyleSheet: (__nccwpck_require__(96785).StyleSheet), - CSSStyleRule: (__nccwpck_require__(4608).CSSStyleRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet - */ -CSSOM.CSSStyleSheet = function CSSStyleSheet() { - CSSOM.StyleSheet.call(this); - this.cssRules = []; -}; - - -CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet(); -CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; - - -/** - * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. - * - * sheet = new Sheet("body {margin: 0}") - * sheet.toString() - * -> "body{margin:0;}" - * sheet.insertRule("img {border: none}", 0) - * -> 0 - * sheet.toString() - * -> "img{border:none;}body{margin:0;}" - * - * @param {string} rule - * @param {number} index - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule - * @return {number} The index within the style sheet's rule collection of the newly inserted rule. - */ -CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { - if (index < 0 || index > this.cssRules.length) { - throw new RangeError("INDEX_SIZE_ERR"); - } - var cssRule = CSSOM.parse(rule).cssRules[0]; - cssRule.parentStyleSheet = this; - this.cssRules.splice(index, 0, cssRule); - return index; -}; - - -/** - * Used to delete a rule from the style sheet. - * - * sheet = new Sheet("img{border:none} body{margin:0}") - * sheet.toString() - * -> "img{border:none;}body{margin:0;}" - * sheet.deleteRule(0) - * sheet.toString() - * -> "body{margin:0;}" - * - * @param {number} index within the style sheet's rule list of the rule to remove. - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule - */ -CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { - if (index < 0 || index >= this.cssRules.length) { - throw new RangeError("INDEX_SIZE_ERR"); - } - this.cssRules.splice(index, 1); -}; - - -/** - * NON-STANDARD - * @return {string} serialize stylesheet - */ -CSSOM.CSSStyleSheet.prototype.toString = function() { - var result = ""; - var rules = this.cssRules; - for (var i=0; i { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(23364).CSSRule), -}; -///CommonJS - - -/** - * @constructor - * @see https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface - */ -CSSOM.CSSSupportsRule = function CSSSupportsRule() { - CSSOM.CSSRule.call(this); - this.conditionText = ''; - this.cssRules = []; -}; - -CSSOM.CSSSupportsRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSSupportsRule.prototype.constructor = CSSOM.CSSSupportsRule; -CSSOM.CSSSupportsRule.prototype.type = 12; - -Object.defineProperty(CSSOM.CSSSupportsRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - - for (var i = 0, length = this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - - return "@supports " + this.conditionText + " {" + cssTexts.join("") + "}"; - } -}); - -//.CommonJS -exports.CSSSupportsRule = CSSOM.CSSSupportsRule; -///CommonJS - - -/***/ }), - -/***/ 99957: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue - * - * TODO: add if needed - */ -CSSOM.CSSValue = function CSSValue() { -}; - -CSSOM.CSSValue.prototype = { - constructor: CSSOM.CSSValue, - - // @see: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue - set cssText(text) { - var name = this._getConstructorName(); - - throw new Error('DOMException: property "cssText" of "' + name + '" is readonly and can not be replaced with "' + text + '"!'); - }, - - get cssText() { - var name = this._getConstructorName(); - - throw new Error('getter "cssText" of "' + name + '" is not implemented!'); - }, - - _getConstructorName: function() { - var s = this.constructor.toString(), - c = s.match(/function\s([^\(]+)/), - name = c[1]; - - return name; - } -}; - - -//.CommonJS -exports.CSSValue = CSSOM.CSSValue; -///CommonJS - - -/***/ }), - -/***/ 75996: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSValue: (__nccwpck_require__(99957).CSSValue) -}; -///CommonJS - - -/** - * @constructor - * @see http://msdn.microsoft.com/en-us/library/ms537634(v=vs.85).aspx - * - */ -CSSOM.CSSValueExpression = function CSSValueExpression(token, idx) { - this._token = token; - this._idx = idx; -}; - -CSSOM.CSSValueExpression.prototype = new CSSOM.CSSValue(); -CSSOM.CSSValueExpression.prototype.constructor = CSSOM.CSSValueExpression; - -/** - * parse css expression() value - * - * @return {Object} - * - error: - * or - * - idx: - * - expression: - * - * Example: - * - * .selector { - * zoom: expression(documentElement.clientWidth > 1000 ? '1000px' : 'auto'); - * } - */ -CSSOM.CSSValueExpression.prototype.parse = function() { - var token = this._token, - idx = this._idx; - - var character = '', - expression = '', - error = '', - info, - paren = []; - - - for (; ; ++idx) { - character = token.charAt(idx); - - // end of token - if (character === '') { - error = 'css expression error: unfinished expression!'; - break; - } - - switch(character) { - case '(': - paren.push(character); - expression += character; - break; - - case ')': - paren.pop(character); - expression += character; - break; - - case '/': - if ((info = this._parseJSComment(token, idx))) { // comment? - if (info.error) { - error = 'css expression error: unfinished comment in expression!'; - } else { - idx = info.idx; - // ignore the comment - } - } else if ((info = this._parseJSRexExp(token, idx))) { // regexp - idx = info.idx; - expression += info.text; - } else { // other - expression += character; - } - break; - - case "'": - case '"': - info = this._parseJSString(token, idx, character); - if (info) { // string - idx = info.idx; - expression += info.text; - } else { - expression += character; - } - break; - - default: - expression += character; - break; - } - - if (error) { - break; - } - - // end of expression - if (paren.length === 0) { - break; - } - } - - var ret; - if (error) { - ret = { - error: error - }; - } else { - ret = { - idx: idx, - expression: expression - }; - } - - return ret; -}; - - -/** - * - * @return {Object|false} - * - idx: - * - text: - * or - * - error: - * or - * false - * - */ -CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { - var nextChar = token.charAt(idx + 1), - text; - - if (nextChar === '/' || nextChar === '*') { - var startIdx = idx, - endIdx, - commentEndChar; - - if (nextChar === '/') { // line comment - commentEndChar = '\n'; - } else if (nextChar === '*') { // block comment - commentEndChar = '*/'; - } - - endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); - if (endIdx !== -1) { - endIdx = endIdx + commentEndChar.length - 1; - text = token.substring(idx, endIdx + 1); - return { - idx: endIdx, - text: text - }; - } else { - var error = 'css expression error: unfinished comment in expression!'; - return { - error: error - }; - } - } else { - return false; - } -}; - - -/** - * - * @return {Object|false} - * - idx: - * - text: - * or - * false - * - */ -CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { - var endIdx = this._findMatchedIdx(token, idx, sep), - text; - - if (endIdx === -1) { - return false; - } else { - text = token.substring(idx, endIdx + sep.length); - - return { - idx: endIdx, - text: text - }; - } -}; - - -/** - * parse regexp in css expression - * - * @return {Object|false} - * - idx: - * - regExp: - * or - * false - */ - -/* - -all legal RegExp - -/a/ -(/a/) -[/a/] -[12, /a/] - -!/a/ - -+/a/ --/a/ -* /a/ -/ /a/ -%/a/ - -===/a/ -!==/a/ -==/a/ -!=/a/ ->/a/ ->=/a/ ->/a/ ->>>/a/ - -&&/a/ -||/a/ -?/a/ -=/a/ -,/a/ - - delete /a/ - in /a/ -instanceof /a/ - new /a/ - typeof /a/ - void /a/ - -*/ -CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { - var before = token.substring(0, idx).replace(/\s+$/, ""), - legalRegx = [ - /^$/, - /\($/, - /\[$/, - /\!$/, - /\+$/, - /\-$/, - /\*$/, - /\/\s+/, - /\%$/, - /\=$/, - /\>$/, - /<$/, - /\&$/, - /\|$/, - /\^$/, - /\~$/, - /\?$/, - /\,$/, - /delete$/, - /in$/, - /instanceof$/, - /new$/, - /typeof$/, - /void$/ - ]; - - var isLegal = legalRegx.some(function(reg) { - return reg.test(before); - }); - - if (!isLegal) { - return false; - } else { - var sep = '/'; - - // same logic as string - return this._parseJSString(token, idx, sep); - } -}; - - -/** - * - * find next sep(same line) index in `token` - * - * @return {Number} - * - */ -CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { - var startIdx = idx, - endIdx; - - var NOT_FOUND = -1; - - while(true) { - endIdx = token.indexOf(sep, startIdx + 1); - - if (endIdx === -1) { // not found - endIdx = NOT_FOUND; - break; - } else { - var text = token.substring(idx + 1, endIdx), - matched = text.match(/\\+$/); - if (!matched || matched[0] % 2 === 0) { // not escaped - break; - } else { - startIdx = endIdx; - } - } - } - - // boundary must be in the same line(js sting or regexp) - var nextNewLineIdx = token.indexOf('\n', idx + 1); - if (nextNewLineIdx < endIdx) { - endIdx = NOT_FOUND; - } - - - return endIdx; -}; - - - - -//.CommonJS -exports.CSSValueExpression = CSSOM.CSSValueExpression; -///CommonJS - - -/***/ }), - -/***/ 25458: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see https://developer.mozilla.org/en/CSS/@-moz-document - */ -CSSOM.MatcherList = function MatcherList(){ - this.length = 0; -}; - -CSSOM.MatcherList.prototype = { - - constructor: CSSOM.MatcherList, - - /** - * @return {string} - */ - get matcherText() { - return Array.prototype.join.call(this, ", "); - }, - - /** - * @param {string} value - */ - set matcherText(value) { - // just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','. - var values = value.split(","); - var length = this.length = values.length; - for (var i=0; i { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-medialist-interface - */ -CSSOM.MediaList = function MediaList(){ - this.length = 0; -}; - -CSSOM.MediaList.prototype = { - - constructor: CSSOM.MediaList, - - /** - * @return {string} - */ - get mediaText() { - return Array.prototype.join.call(this, ", "); - }, - - /** - * @param {string} value - */ - set mediaText(value) { - var values = value.split(","); - var length = this.length = values.length; - for (var i=0; i { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-stylesheet-interface - */ -CSSOM.StyleSheet = function StyleSheet() { - this.parentStyleSheet = null; -}; - - -//.CommonJS -exports.StyleSheet = CSSOM.StyleSheet; -///CommonJS - - -/***/ }), - -/***/ 98257: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleSheet: (__nccwpck_require__(62486).CSSStyleSheet), - CSSStyleRule: (__nccwpck_require__(4608).CSSStyleRule), - CSSMediaRule: (__nccwpck_require__(96791).CSSMediaRule), - CSSSupportsRule: (__nccwpck_require__(27967).CSSSupportsRule), - CSSStyleDeclaration: (__nccwpck_require__(45131).CSSStyleDeclaration), - CSSKeyframeRule: (__nccwpck_require__(97254).CSSKeyframeRule), - CSSKeyframesRule: (__nccwpck_require__(16005).CSSKeyframesRule) -}; -///CommonJS - - -/** - * Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively. - * @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet - * @nosideeffects - * @return {CSSOM.CSSStyleSheet} - */ -CSSOM.clone = function clone(stylesheet) { - - var cloned = new CSSOM.CSSStyleSheet(); - - var rules = stylesheet.cssRules; - if (!rules) { - return cloned; - } - - for (var i = 0, rulesLength = rules.length; i < rulesLength; i++) { - var rule = rules[i]; - var ruleClone = cloned.cssRules[i] = new rule.constructor(); - - var style = rule.style; - if (style) { - var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration(); - for (var j = 0, styleLength = style.length; j < styleLength; j++) { - var name = styleClone[j] = style[j]; - styleClone[name] = style[name]; - styleClone._importants[name] = style.getPropertyPriority(name); - } - styleClone.length = style.length; - } - - if (rule.hasOwnProperty('keyText')) { - ruleClone.keyText = rule.keyText; - } - - if (rule.hasOwnProperty('selectorText')) { - ruleClone.selectorText = rule.selectorText; - } - - if (rule.hasOwnProperty('mediaText')) { - ruleClone.mediaText = rule.mediaText; - } - - if (rule.hasOwnProperty('conditionText')) { - ruleClone.conditionText = rule.conditionText; - } - - if (rule.hasOwnProperty('cssRules')) { - ruleClone.cssRules = clone(rule).cssRules; - } - } - - return cloned; - -}; - -//.CommonJS -exports.clone = CSSOM.clone; -///CommonJS - - -/***/ }), - -/***/ 1295: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -exports.CSSStyleDeclaration = __nccwpck_require__(45131).CSSStyleDeclaration; -exports.CSSRule = __nccwpck_require__(23364).CSSRule; -exports.CSSStyleRule = __nccwpck_require__(4608).CSSStyleRule; -exports.MediaList = __nccwpck_require__(63849).MediaList; -exports.CSSMediaRule = __nccwpck_require__(96791).CSSMediaRule; -exports.CSSSupportsRule = __nccwpck_require__(27967).CSSSupportsRule; -exports.CSSImportRule = __nccwpck_require__(49776).CSSImportRule; -exports.CSSFontFaceRule = __nccwpck_require__(33046).CSSFontFaceRule; -exports.CSSHostRule = __nccwpck_require__(57986).CSSHostRule; -exports.StyleSheet = __nccwpck_require__(96785).StyleSheet; -exports.CSSStyleSheet = __nccwpck_require__(62486).CSSStyleSheet; -exports.CSSKeyframesRule = __nccwpck_require__(16005).CSSKeyframesRule; -exports.CSSKeyframeRule = __nccwpck_require__(97254).CSSKeyframeRule; -exports.MatcherList = __nccwpck_require__(25458).MatcherList; -exports.CSSDocumentRule = __nccwpck_require__(27455).CSSDocumentRule; -exports.CSSValue = __nccwpck_require__(99957).CSSValue; -exports.CSSValueExpression = __nccwpck_require__(75996).CSSValueExpression; -exports.parse = __nccwpck_require__(18025).parse; -exports.clone = __nccwpck_require__(98257).clone; - - -/***/ }), - -/***/ 18025: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @param {string} token - */ -CSSOM.parse = function parse(token) { - - var i = 0; - - /** - "before-selector" or - "selector" or - "atRule" or - "atBlock" or - "conditionBlock" or - "before-name" or - "name" or - "before-value" or - "value" - */ - var state = "before-selector"; - - var index; - var buffer = ""; - var valueParenthesisDepth = 0; - - var SIGNIFICANT_WHITESPACE = { - "selector": true, - "value": true, - "value-parenthesis": true, - "atRule": true, - "importRule-begin": true, - "importRule": true, - "atBlock": true, - "conditionBlock": true, - 'documentRule-begin': true - }; - - var styleSheet = new CSSOM.CSSStyleSheet(); - - // @type CSSStyleSheet|CSSMediaRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule - var currentScope = styleSheet; - - // @type CSSMediaRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule - var parentRule; - - var ancestorRules = []; - var hasAncestors = false; - var prevScope; - - var name, priority="", styleRule, mediaRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule; - - var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; - - var parseError = function(message) { - var lines = token.substring(0, i).split('\n'); - var lineCount = lines.length; - var charCount = lines.pop().length + 1; - var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); - error.line = lineCount; - /* jshint sub : true */ - error['char'] = charCount; - error.styleSheet = styleSheet; - throw error; - }; - - for (var character; (character = token.charAt(i)); i++) { - - switch (character) { - - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - if (SIGNIFICANT_WHITESPACE[state]) { - buffer += character; - } - break; - - // String - case '"': - index = i + 1; - do { - index = token.indexOf('"', index) + 1; - if (!index) { - parseError('Unmatched "'); - } - } while (token[index - 2] === '\\'); - buffer += token.slice(i, index); - i = index - 1; - switch (state) { - case 'before-value': - state = 'value'; - break; - case 'importRule-begin': - state = 'importRule'; - break; - } - break; - - case "'": - index = i + 1; - do { - index = token.indexOf("'", index) + 1; - if (!index) { - parseError("Unmatched '"); - } - } while (token[index - 2] === '\\'); - buffer += token.slice(i, index); - i = index - 1; - switch (state) { - case 'before-value': - state = 'value'; - break; - case 'importRule-begin': - state = 'importRule'; - break; - } - break; - - // Comment - case "/": - if (token.charAt(i + 1) === "*") { - i += 2; - index = token.indexOf("*/", i); - if (index === -1) { - parseError("Missing */"); - } else { - i = index + 1; - } - } else { - buffer += character; - } - if (state === "importRule-begin") { - buffer += " "; - state = "importRule"; - } - break; - - // At-rule - case "@": - if (token.indexOf("@-moz-document", i) === i) { - state = "documentRule-begin"; - documentRule = new CSSOM.CSSDocumentRule(); - documentRule.__starts = i; - i += "-moz-document".length; - buffer = ""; - break; - } else if (token.indexOf("@media", i) === i) { - state = "atBlock"; - mediaRule = new CSSOM.CSSMediaRule(); - mediaRule.__starts = i; - i += "media".length; - buffer = ""; - break; - } else if (token.indexOf("@supports", i) === i) { - state = "conditionBlock"; - supportsRule = new CSSOM.CSSSupportsRule(); - supportsRule.__starts = i; - i += "supports".length; - buffer = ""; - break; - } else if (token.indexOf("@host", i) === i) { - state = "hostRule-begin"; - i += "host".length; - hostRule = new CSSOM.CSSHostRule(); - hostRule.__starts = i; - buffer = ""; - break; - } else if (token.indexOf("@import", i) === i) { - state = "importRule-begin"; - i += "import".length; - buffer += "@import"; - break; - } else if (token.indexOf("@font-face", i) === i) { - state = "fontFaceRule-begin"; - i += "font-face".length; - fontFaceRule = new CSSOM.CSSFontFaceRule(); - fontFaceRule.__starts = i; - buffer = ""; - break; - } else { - atKeyframesRegExp.lastIndex = i; - var matchKeyframes = atKeyframesRegExp.exec(token); - if (matchKeyframes && matchKeyframes.index === i) { - state = "keyframesRule-begin"; - keyframesRule = new CSSOM.CSSKeyframesRule(); - keyframesRule.__starts = i; - keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found - i += matchKeyframes[0].length - 1; - buffer = ""; - break; - } else if (state === "selector") { - state = "atRule"; - } - } - buffer += character; - break; - - case "{": - if (state === "selector" || state === "atRule") { - styleRule.selectorText = buffer.trim(); - styleRule.style.__starts = i; - buffer = ""; - state = "before-name"; - } else if (state === "atBlock") { - mediaRule.media.mediaText = buffer.trim(); - - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = mediaRule; - mediaRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "conditionBlock") { - supportsRule.conditionText = buffer.trim(); - - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = supportsRule; - supportsRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "hostRule-begin") { - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = hostRule; - hostRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "fontFaceRule-begin") { - if (parentRule) { - fontFaceRule.parentRule = parentRule; - } - fontFaceRule.parentStyleSheet = styleSheet; - styleRule = fontFaceRule; - buffer = ""; - state = "before-name"; - } else if (state === "keyframesRule-begin") { - keyframesRule.name = buffer.trim(); - if (parentRule) { - ancestorRules.push(parentRule); - keyframesRule.parentRule = parentRule; - } - keyframesRule.parentStyleSheet = styleSheet; - currentScope = parentRule = keyframesRule; - buffer = ""; - state = "keyframeRule-begin"; - } else if (state === "keyframeRule-begin") { - styleRule = new CSSOM.CSSKeyframeRule(); - styleRule.keyText = buffer.trim(); - styleRule.__starts = i; - buffer = ""; - state = "before-name"; - } else if (state === "documentRule-begin") { - // FIXME: what if this '{' is in the url text of the match function? - documentRule.matcher.matcherText = buffer.trim(); - if (parentRule) { - ancestorRules.push(parentRule); - documentRule.parentRule = parentRule; - } - currentScope = parentRule = documentRule; - documentRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } - break; - - case ":": - if (state === "name") { - name = buffer.trim(); - buffer = ""; - state = "before-value"; - } else { - buffer += character; - } - break; - - case "(": - if (state === 'value') { - // ie css expression mode - if (buffer.trim() === 'expression') { - var info = (new CSSOM.CSSValueExpression(token, i)).parse(); - - if (info.error) { - parseError(info.error); - } else { - buffer += info.expression; - i = info.idx; - } - } else { - state = 'value-parenthesis'; - //always ensure this is reset to 1 on transition - //from value to value-parenthesis - valueParenthesisDepth = 1; - buffer += character; - } - } else if (state === 'value-parenthesis') { - valueParenthesisDepth++; - buffer += character; - } else { - buffer += character; - } - break; - - case ")": - if (state === 'value-parenthesis') { - valueParenthesisDepth--; - if (valueParenthesisDepth === 0) state = 'value'; - } - buffer += character; - break; - - case "!": - if (state === "value" && token.indexOf("!important", i) === i) { - priority = "important"; - i += "important".length; - } else { - buffer += character; - } - break; - - case ";": - switch (state) { - case "value": - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - state = "before-name"; - break; - case "atRule": - buffer = ""; - state = "before-selector"; - break; - case "importRule": - importRule = new CSSOM.CSSImportRule(); - importRule.parentStyleSheet = importRule.styleSheet.parentStyleSheet = styleSheet; - importRule.cssText = buffer + character; - styleSheet.cssRules.push(importRule); - buffer = ""; - state = "before-selector"; - break; - default: - buffer += character; - break; - } - break; - - case "}": - switch (state) { - case "value": - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - /* falls through */ - case "before-name": - case "name": - styleRule.__ends = i + 1; - if (parentRule) { - styleRule.parentRule = parentRule; - } - styleRule.parentStyleSheet = styleSheet; - currentScope.cssRules.push(styleRule); - buffer = ""; - if (currentScope.constructor === CSSOM.CSSKeyframesRule) { - state = "keyframeRule-begin"; - } else { - state = "before-selector"; - } - break; - case "keyframeRule-begin": - case "before-selector": - case "selector": - // End of media/supports/document rule. - if (!parentRule) { - parseError("Unexpected }"); - } - - // Handle rules nested in @media or @supports - hasAncestors = ancestorRules.length > 0; - - while (ancestorRules.length > 0) { - parentRule = ancestorRules.pop(); - - if ( - parentRule.constructor.name === "CSSMediaRule" - || parentRule.constructor.name === "CSSSupportsRule" - ) { - prevScope = currentScope; - currentScope = parentRule; - currentScope.cssRules.push(prevScope); - break; - } - - if (ancestorRules.length === 0) { - hasAncestors = false; - } - } - - if (!hasAncestors) { - currentScope.__ends = i + 1; - styleSheet.cssRules.push(currentScope); - currentScope = styleSheet; - parentRule = null; - } - - buffer = ""; - state = "before-selector"; - break; - } - break; - - default: - switch (state) { - case "before-selector": - state = "selector"; - styleRule = new CSSOM.CSSStyleRule(); - styleRule.__starts = i; - break; - case "before-name": - state = "name"; - break; - case "before-value": - state = "value"; - break; - case "importRule-begin": - state = "importRule"; - break; - } - buffer += character; - break; - } - } - - return styleSheet; -}; - - -//.CommonJS -exports.parse = CSSOM.parse; -// The following modules cannot be included sooner due to the mutual dependency with parse.js -CSSOM.CSSStyleSheet = (__nccwpck_require__(62486).CSSStyleSheet); -CSSOM.CSSStyleRule = (__nccwpck_require__(4608).CSSStyleRule); -CSSOM.CSSImportRule = (__nccwpck_require__(49776).CSSImportRule); -CSSOM.CSSMediaRule = (__nccwpck_require__(96791).CSSMediaRule); -CSSOM.CSSSupportsRule = (__nccwpck_require__(27967).CSSSupportsRule); -CSSOM.CSSFontFaceRule = (__nccwpck_require__(33046).CSSFontFaceRule); -CSSOM.CSSHostRule = (__nccwpck_require__(57986).CSSHostRule); -CSSOM.CSSStyleDeclaration = (__nccwpck_require__(45131).CSSStyleDeclaration); -CSSOM.CSSKeyframeRule = (__nccwpck_require__(97254).CSSKeyframeRule); -CSSOM.CSSKeyframesRule = (__nccwpck_require__(16005).CSSKeyframesRule); -CSSOM.CSSValueExpression = (__nccwpck_require__(75996).CSSValueExpression); -CSSOM.CSSDocumentRule = (__nccwpck_require__(27455).CSSDocumentRule); -///CommonJS - - -/***/ }), - -/***/ 15674: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/********************************************************************* - * This is a fork from the CSS Style Declaration part of - * https://github.com/NV/CSSOM - ********************************************************************/ - -var CSSOM = __nccwpck_require__(8331); -var allProperties = __nccwpck_require__(36685); -var allExtraProperties = __nccwpck_require__(92461); -var implementedProperties = __nccwpck_require__(93398); -var { dashedToCamelCase } = __nccwpck_require__(37032); -var getBasicPropertyDescriptor = __nccwpck_require__(95721); - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration - */ -var CSSStyleDeclaration = function CSSStyleDeclaration(onChangeCallback) { - this._values = {}; - this._importants = {}; - this._length = 0; - this._onChange = - onChangeCallback || - function() { - return; - }; -}; -CSSStyleDeclaration.prototype = { - constructor: CSSStyleDeclaration, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set. - */ - getPropertyValue: function(name) { - if (!this._values.hasOwnProperty(name)) { - return ''; - } - return this._values[name].toString(); - }, - - /** - * - * @param {string} name - * @param {string} value - * @param {string} [priority=null] "important" or null - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty - */ - setProperty: function(name, value, priority) { - if (value === undefined) { - return; - } - if (value === null || value === '') { - this.removeProperty(name); - return; - } - var isCustomProperty = name.indexOf('--') === 0; - if (isCustomProperty) { - this._setProperty(name, value, priority); - return; - } - var lowercaseName = name.toLowerCase(); - if (!allProperties.has(lowercaseName) && !allExtraProperties.has(lowercaseName)) { - return; - } - - this[lowercaseName] = value; - this._importants[lowercaseName] = priority; - }, - _setProperty: function(name, value, priority) { - if (value === undefined) { - return; - } - if (value === null || value === '') { - this.removeProperty(name); - return; - } - if (this._values[name]) { - // Property already exist. Overwrite it. - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - this[this._length] = name; - this._length++; - } - } else { - // New property. - this[this._length] = name; - this._length++; - } - this._values[name] = value; - this._importants[name] = priority; - this._onChange(this.cssText); - }, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. - */ - removeProperty: function(name) { - if (!this._values.hasOwnProperty(name)) { - return ''; - } - - var prevValue = this._values[name]; - delete this._values[name]; - delete this._importants[name]; - - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - return prevValue; - } - - // That's what WebKit and Opera do - Array.prototype.splice.call(this, index, 1); - - // That's what Firefox does - //this[index] = "" - - this._onChange(this.cssText); - return prevValue; - }, - - /** - * - * @param {String} name - */ - getPropertyPriority: function(name) { - return this._importants[name] || ''; - }, - - getPropertyCSSValue: function() { - //FIXME - return; - }, - - /** - * element.style.overflow = "auto" - * element.style.getPropertyShorthand("overflow-x") - * -> "overflow" - */ - getPropertyShorthand: function() { - //FIXME - return; - }, - - isPropertyImplicit: function() { - //FIXME - return; - }, - - /** - * http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-item - */ - item: function(index) { - index = parseInt(index, 10); - if (index < 0 || index >= this._length) { - return ''; - } - return this[index]; - }, -}; - -Object.defineProperties(CSSStyleDeclaration.prototype, { - cssText: { - get: function() { - var properties = []; - var i; - var name; - var value; - var priority; - for (i = 0; i < this._length; i++) { - name = this[i]; - value = this.getPropertyValue(name); - priority = this.getPropertyPriority(name); - if (priority !== '') { - priority = ' !' + priority; - } - properties.push([name, ': ', value, priority, ';'].join('')); - } - return properties.join(' '); - }, - set: function(value) { - var i; - this._values = {}; - Array.prototype.splice.call(this, 0, this._length); - this._importants = {}; - var dummyRule; - try { - dummyRule = CSSOM.parse('#bogus{' + value + '}').cssRules[0].style; - } catch (err) { - // malformed css, just return - return; - } - var rule_length = dummyRule.length; - var name; - for (i = 0; i < rule_length; ++i) { - name = dummyRule[i]; - this.setProperty( - dummyRule[i], - dummyRule.getPropertyValue(name), - dummyRule.getPropertyPriority(name) - ); - } - this._onChange(this.cssText); - }, - enumerable: true, - configurable: true, - }, - parentRule: { - get: function() { - return null; - }, - enumerable: true, - configurable: true, - }, - length: { - get: function() { - return this._length; - }, - /** - * This deletes indices if the new length is less then the current - * length. If the new length is more, it does nothing, the new indices - * will be undefined until set. - **/ - set: function(value) { - var i; - for (i = value; i < this._length; i++) { - delete this[i]; - } - this._length = value; - }, - enumerable: true, - configurable: true, - }, -}); - -__nccwpck_require__(13480)(CSSStyleDeclaration.prototype); - -allProperties.forEach(function(property) { - if (!implementedProperties.has(property)) { - var declaration = getBasicPropertyDescriptor(property); - Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); - Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); - } -}); - -allExtraProperties.forEach(function(property) { - if (!implementedProperties.has(property)) { - var declaration = getBasicPropertyDescriptor(property); - Object.defineProperty(CSSStyleDeclaration.prototype, property, declaration); - Object.defineProperty(CSSStyleDeclaration.prototype, dashedToCamelCase(property), declaration); - } -}); - -exports.CSSStyleDeclaration = CSSStyleDeclaration; - - -/***/ }), - -/***/ 92461: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * This file contains all implemented properties that are not a part of any - * current specifications or drafts, but are handled by browsers nevertheless. - */ - -var allWebkitProperties = __nccwpck_require__(39483); - -module.exports = new Set( - [ - 'background-position-x', - 'background-position-y', - 'background-repeat-x', - 'background-repeat-y', - 'color-interpolation', - 'color-profile', - 'color-rendering', - 'css-float', - 'enable-background', - 'fill', - 'fill-opacity', - 'fill-rule', - 'glyph-orientation-horizontal', - 'image-rendering', - 'kerning', - 'marker', - 'marker-end', - 'marker-mid', - 'marker-offset', - 'marker-start', - 'marks', - 'pointer-events', - 'shape-rendering', - 'size', - 'src', - 'stop-color', - 'stop-opacity', - 'stroke', - 'stroke-dasharray', - 'stroke-dashoffset', - 'stroke-linecap', - 'stroke-linejoin', - 'stroke-miterlimit', - 'stroke-opacity', - 'stroke-width', - 'text-anchor', - 'text-line-through', - 'text-line-through-color', - 'text-line-through-mode', - 'text-line-through-style', - 'text-line-through-width', - 'text-overline', - 'text-overline-color', - 'text-overline-mode', - 'text-overline-style', - 'text-overline-width', - 'text-rendering', - 'text-underline', - 'text-underline-color', - 'text-underline-mode', - 'text-underline-style', - 'text-underline-width', - 'unicode-range', - 'vector-effect', - ].concat(allWebkitProperties) -); - - -/***/ }), - -/***/ 36685: -/***/ ((module) => { - -"use strict"; - - -// autogenerated - 4/29/2020 - -/* - * - * https://www.w3.org/Style/CSS/all-properties.en.html - */ - -module.exports = new Set([ - 'align-content', - 'align-items', - 'align-self', - 'alignment-baseline', - 'all', - 'animation', - 'animation-delay', - 'animation-direction', - 'animation-duration', - 'animation-fill-mode', - 'animation-iteration-count', - 'animation-name', - 'animation-play-state', - 'animation-timing-function', - 'appearance', - 'azimuth', - 'background', - 'background-attachment', - 'background-blend-mode', - 'background-clip', - 'background-color', - 'background-image', - 'background-origin', - 'background-position', - 'background-repeat', - 'background-size', - 'baseline-shift', - 'block-overflow', - 'block-size', - 'bookmark-label', - 'bookmark-level', - 'bookmark-state', - 'border', - 'border-block', - 'border-block-color', - 'border-block-end', - 'border-block-end-color', - 'border-block-end-style', - 'border-block-end-width', - 'border-block-start', - 'border-block-start-color', - 'border-block-start-style', - 'border-block-start-width', - 'border-block-style', - 'border-block-width', - 'border-bottom', - 'border-bottom-color', - 'border-bottom-left-radius', - 'border-bottom-right-radius', - 'border-bottom-style', - 'border-bottom-width', - 'border-boundary', - 'border-collapse', - 'border-color', - 'border-end-end-radius', - 'border-end-start-radius', - 'border-image', - 'border-image-outset', - 'border-image-repeat', - 'border-image-slice', - 'border-image-source', - 'border-image-width', - 'border-inline', - 'border-inline-color', - 'border-inline-end', - 'border-inline-end-color', - 'border-inline-end-style', - 'border-inline-end-width', - 'border-inline-start', - 'border-inline-start-color', - 'border-inline-start-style', - 'border-inline-start-width', - 'border-inline-style', - 'border-inline-width', - 'border-left', - 'border-left-color', - 'border-left-style', - 'border-left-width', - 'border-radius', - 'border-right', - 'border-right-color', - 'border-right-style', - 'border-right-width', - 'border-spacing', - 'border-start-end-radius', - 'border-start-start-radius', - 'border-style', - 'border-top', - 'border-top-color', - 'border-top-left-radius', - 'border-top-right-radius', - 'border-top-style', - 'border-top-width', - 'border-width', - 'bottom', - 'box-decoration-break', - 'box-shadow', - 'box-sizing', - 'box-snap', - 'break-after', - 'break-before', - 'break-inside', - 'caption-side', - 'caret', - 'caret-color', - 'caret-shape', - 'chains', - 'clear', - 'clip', - 'clip-path', - 'clip-rule', - 'color', - 'color-adjust', - 'color-interpolation-filters', - 'color-scheme', - 'column-count', - 'column-fill', - 'column-gap', - 'column-rule', - 'column-rule-color', - 'column-rule-style', - 'column-rule-width', - 'column-span', - 'column-width', - 'columns', - 'contain', - 'content', - 'continue', - 'counter-increment', - 'counter-reset', - 'counter-set', - 'cue', - 'cue-after', - 'cue-before', - 'cursor', - 'direction', - 'display', - 'dominant-baseline', - 'elevation', - 'empty-cells', - 'filter', - 'flex', - 'flex-basis', - 'flex-direction', - 'flex-flow', - 'flex-grow', - 'flex-shrink', - 'flex-wrap', - 'float', - 'flood-color', - 'flood-opacity', - 'flow', - 'flow-from', - 'flow-into', - 'font', - 'font-family', - 'font-feature-settings', - 'font-kerning', - 'font-language-override', - 'font-optical-sizing', - 'font-palette', - 'font-size', - 'font-size-adjust', - 'font-stretch', - 'font-style', - 'font-synthesis', - 'font-synthesis-small-caps', - 'font-synthesis-style', - 'font-synthesis-weight', - 'font-variant', - 'font-variant-alternates', - 'font-variant-caps', - 'font-variant-east-asian', - 'font-variant-emoji', - 'font-variant-ligatures', - 'font-variant-numeric', - 'font-variant-position', - 'font-variation-settings', - 'font-weight', - 'footnote-display', - 'footnote-policy', - 'forced-color-adjust', - 'gap', - 'glyph-orientation-vertical', - 'grid', - 'grid-area', - 'grid-auto-columns', - 'grid-auto-flow', - 'grid-auto-rows', - 'grid-column', - 'grid-column-end', - 'grid-column-start', - 'grid-row', - 'grid-row-end', - 'grid-row-start', - 'grid-template', - 'grid-template-areas', - 'grid-template-columns', - 'grid-template-rows', - 'hanging-punctuation', - 'height', - 'hyphenate-character', - 'hyphenate-limit-chars', - 'hyphenate-limit-last', - 'hyphenate-limit-lines', - 'hyphenate-limit-zone', - 'hyphens', - 'image-orientation', - 'image-rendering', - 'image-resolution', - 'initial-letters', - 'initial-letters-align', - 'initial-letters-wrap', - 'inline-size', - 'inline-sizing', - 'inset', - 'inset-block', - 'inset-block-end', - 'inset-block-start', - 'inset-inline', - 'inset-inline-end', - 'inset-inline-start', - 'isolation', - 'justify-content', - 'justify-items', - 'justify-self', - 'left', - 'letter-spacing', - 'lighting-color', - 'line-break', - 'line-clamp', - 'line-grid', - 'line-height', - 'line-padding', - 'line-snap', - 'list-style', - 'list-style-image', - 'list-style-position', - 'list-style-type', - 'margin', - 'margin-block', - 'margin-block-end', - 'margin-block-start', - 'margin-bottom', - 'margin-inline', - 'margin-inline-end', - 'margin-inline-start', - 'margin-left', - 'margin-right', - 'margin-top', - 'marker-side', - 'mask', - 'mask-border', - 'mask-border-mode', - 'mask-border-outset', - 'mask-border-repeat', - 'mask-border-slice', - 'mask-border-source', - 'mask-border-width', - 'mask-clip', - 'mask-composite', - 'mask-image', - 'mask-mode', - 'mask-origin', - 'mask-position', - 'mask-repeat', - 'mask-size', - 'mask-type', - 'max-block-size', - 'max-height', - 'max-inline-size', - 'max-lines', - 'max-width', - 'min-block-size', - 'min-height', - 'min-inline-size', - 'min-width', - 'mix-blend-mode', - 'nav-down', - 'nav-left', - 'nav-right', - 'nav-up', - 'object-fit', - 'object-position', - 'offset', - 'offset-after', - 'offset-anchor', - 'offset-before', - 'offset-distance', - 'offset-end', - 'offset-path', - 'offset-position', - 'offset-rotate', - 'offset-start', - 'opacity', - 'order', - 'orphans', - 'outline', - 'outline-color', - 'outline-offset', - 'outline-style', - 'outline-width', - 'overflow', - 'overflow-block', - 'overflow-inline', - 'overflow-wrap', - 'overflow-x', - 'overflow-y', - 'padding', - 'padding-block', - 'padding-block-end', - 'padding-block-start', - 'padding-bottom', - 'padding-inline', - 'padding-inline-end', - 'padding-inline-start', - 'padding-left', - 'padding-right', - 'padding-top', - 'page', - 'page-break-after', - 'page-break-before', - 'page-break-inside', - 'pause', - 'pause-after', - 'pause-before', - 'pitch', - 'pitch-range', - 'place-content', - 'place-items', - 'place-self', - 'play-during', - 'position', - 'quotes', - 'region-fragment', - 'resize', - 'rest', - 'rest-after', - 'rest-before', - 'richness', - 'right', - 'row-gap', - 'ruby-align', - 'ruby-merge', - 'ruby-position', - 'running', - 'scroll-behavior', - 'scroll-margin', - 'scroll-margin-block', - 'scroll-margin-block-end', - 'scroll-margin-block-start', - 'scroll-margin-bottom', - 'scroll-margin-inline', - 'scroll-margin-inline-end', - 'scroll-margin-inline-start', - 'scroll-margin-left', - 'scroll-margin-right', - 'scroll-margin-top', - 'scroll-padding', - 'scroll-padding-block', - 'scroll-padding-block-end', - 'scroll-padding-block-start', - 'scroll-padding-bottom', - 'scroll-padding-inline', - 'scroll-padding-inline-end', - 'scroll-padding-inline-start', - 'scroll-padding-left', - 'scroll-padding-right', - 'scroll-padding-top', - 'scroll-snap-align', - 'scroll-snap-stop', - 'scroll-snap-type', - 'shape-image-threshold', - 'shape-inside', - 'shape-margin', - 'shape-outside', - 'spatial-navigation-action', - 'spatial-navigation-contain', - 'spatial-navigation-function', - 'speak', - 'speak-as', - 'speak-header', - 'speak-numeral', - 'speak-punctuation', - 'speech-rate', - 'stress', - 'string-set', - 'tab-size', - 'table-layout', - 'text-align', - 'text-align-all', - 'text-align-last', - 'text-combine-upright', - 'text-decoration', - 'text-decoration-color', - 'text-decoration-line', - 'text-decoration-style', - 'text-emphasis', - 'text-emphasis-color', - 'text-emphasis-position', - 'text-emphasis-style', - 'text-group-align', - 'text-indent', - 'text-justify', - 'text-orientation', - 'text-overflow', - 'text-shadow', - 'text-space-collapse', - 'text-space-trim', - 'text-spacing', - 'text-transform', - 'text-underline-position', - 'text-wrap', - 'top', - 'transform', - 'transform-box', - 'transform-origin', - 'transition', - 'transition-delay', - 'transition-duration', - 'transition-property', - 'transition-timing-function', - 'unicode-bidi', - 'user-select', - 'vertical-align', - 'visibility', - 'voice-balance', - 'voice-duration', - 'voice-family', - 'voice-pitch', - 'voice-range', - 'voice-rate', - 'voice-stress', - 'voice-volume', - 'volume', - 'white-space', - 'widows', - 'width', - 'will-change', - 'word-boundary-detection', - 'word-boundary-expansion', - 'word-break', - 'word-spacing', - 'word-wrap', - 'wrap-after', - 'wrap-before', - 'wrap-flow', - 'wrap-inside', - 'wrap-through', - 'writing-mode', - 'z-index', -]); - - -/***/ }), - -/***/ 39483: -/***/ ((module) => { - -"use strict"; - - -/** - * This file contains all implemented properties that are not a part of any - * current specifications or drafts, but are handled by browsers nevertheless. - */ - -module.exports = [ - 'animation', - 'animation-delay', - 'animation-direction', - 'animation-duration', - 'animation-fill-mode', - 'animation-iteration-count', - 'animation-name', - 'animation-play-state', - 'animation-timing-function', - 'appearance', - 'aspect-ratio', - 'backface-visibility', - 'background-clip', - 'background-composite', - 'background-origin', - 'background-size', - 'border-after', - 'border-after-color', - 'border-after-style', - 'border-after-width', - 'border-before', - 'border-before-color', - 'border-before-style', - 'border-before-width', - 'border-end', - 'border-end-color', - 'border-end-style', - 'border-end-width', - 'border-fit', - 'border-horizontal-spacing', - 'border-image', - 'border-radius', - 'border-start', - 'border-start-color', - 'border-start-style', - 'border-start-width', - 'border-vertical-spacing', - 'box-align', - 'box-direction', - 'box-flex', - 'box-flex-group', - 'box-lines', - 'box-ordinal-group', - 'box-orient', - 'box-pack', - 'box-reflect', - 'box-shadow', - 'color-correction', - 'column-axis', - 'column-break-after', - 'column-break-before', - 'column-break-inside', - 'column-count', - 'column-gap', - 'column-rule', - 'column-rule-color', - 'column-rule-style', - 'column-rule-width', - 'columns', - 'column-span', - 'column-width', - 'filter', - 'flex-align', - 'flex-direction', - 'flex-flow', - 'flex-item-align', - 'flex-line-pack', - 'flex-order', - 'flex-pack', - 'flex-wrap', - 'flow-from', - 'flow-into', - 'font-feature-settings', - 'font-kerning', - 'font-size-delta', - 'font-smoothing', - 'font-variant-ligatures', - 'highlight', - 'hyphenate-character', - 'hyphenate-limit-after', - 'hyphenate-limit-before', - 'hyphenate-limit-lines', - 'hyphens', - 'line-align', - 'line-box-contain', - 'line-break', - 'line-clamp', - 'line-grid', - 'line-snap', - 'locale', - 'logical-height', - 'logical-width', - 'margin-after', - 'margin-after-collapse', - 'margin-before', - 'margin-before-collapse', - 'margin-bottom-collapse', - 'margin-collapse', - 'margin-end', - 'margin-start', - 'margin-top-collapse', - 'marquee', - 'marquee-direction', - 'marquee-increment', - 'marquee-repetition', - 'marquee-speed', - 'marquee-style', - 'mask', - 'mask-attachment', - 'mask-box-image', - 'mask-box-image-outset', - 'mask-box-image-repeat', - 'mask-box-image-slice', - 'mask-box-image-source', - 'mask-box-image-width', - 'mask-clip', - 'mask-composite', - 'mask-image', - 'mask-origin', - 'mask-position', - 'mask-position-x', - 'mask-position-y', - 'mask-repeat', - 'mask-repeat-x', - 'mask-repeat-y', - 'mask-size', - 'match-nearest-mail-blockquote-color', - 'max-logical-height', - 'max-logical-width', - 'min-logical-height', - 'min-logical-width', - 'nbsp-mode', - 'overflow-scrolling', - 'padding-after', - 'padding-before', - 'padding-end', - 'padding-start', - 'perspective', - 'perspective-origin', - 'perspective-origin-x', - 'perspective-origin-y', - 'print-color-adjust', - 'region-break-after', - 'region-break-before', - 'region-break-inside', - 'region-overflow', - 'rtl-ordering', - 'svg-shadow', - 'tap-highlight-color', - 'text-combine', - 'text-decorations-in-effect', - 'text-emphasis', - 'text-emphasis-color', - 'text-emphasis-position', - 'text-emphasis-style', - 'text-fill-color', - 'text-orientation', - 'text-security', - 'text-size-adjust', - 'text-stroke', - 'text-stroke-color', - 'text-stroke-width', - 'transform', - 'transform-origin', - 'transform-origin-x', - 'transform-origin-y', - 'transform-origin-z', - 'transform-style', - 'transition', - 'transition-delay', - 'transition-duration', - 'transition-property', - 'transition-timing-function', - 'user-drag', - 'user-modify', - 'user-select', - 'wrap', - 'wrap-flow', - 'wrap-margin', - 'wrap-padding', - 'wrap-shape-inside', - 'wrap-shape-outside', - 'wrap-through', - 'writing-mode', - 'zoom', -].map(prop => 'webkit-' + prop); - - -/***/ }), - -/***/ 39139: -/***/ ((module) => { - -"use strict"; - - -module.exports.POSITION_AT_SHORTHAND = { - first: 0, - second: 1, -}; - - -/***/ }), - -/***/ 93398: -/***/ ((module) => { - -"use strict"; - - -// autogenerated - 4/29/2020 - -/* - * - * https://www.w3.org/Style/CSS/all-properties.en.html - */ - -var implementedProperties = new Set(); -implementedProperties.add("azimuth"); -implementedProperties.add("background"); -implementedProperties.add("background-attachment"); -implementedProperties.add("background-color"); -implementedProperties.add("background-image"); -implementedProperties.add("background-position"); -implementedProperties.add("background-repeat"); -implementedProperties.add("border"); -implementedProperties.add("border-bottom"); -implementedProperties.add("border-bottom-color"); -implementedProperties.add("border-bottom-style"); -implementedProperties.add("border-bottom-width"); -implementedProperties.add("border-collapse"); -implementedProperties.add("border-color"); -implementedProperties.add("border-left"); -implementedProperties.add("border-left-color"); -implementedProperties.add("border-left-style"); -implementedProperties.add("border-left-width"); -implementedProperties.add("border-right"); -implementedProperties.add("border-right-color"); -implementedProperties.add("border-right-style"); -implementedProperties.add("border-right-width"); -implementedProperties.add("border-spacing"); -implementedProperties.add("border-style"); -implementedProperties.add("border-top"); -implementedProperties.add("border-top-color"); -implementedProperties.add("border-top-style"); -implementedProperties.add("border-top-width"); -implementedProperties.add("border-width"); -implementedProperties.add("bottom"); -implementedProperties.add("clear"); -implementedProperties.add("clip"); -implementedProperties.add("color"); -implementedProperties.add("css-float"); -implementedProperties.add("flex"); -implementedProperties.add("flex-basis"); -implementedProperties.add("flex-grow"); -implementedProperties.add("flex-shrink"); -implementedProperties.add("float"); -implementedProperties.add("flood-color"); -implementedProperties.add("font"); -implementedProperties.add("font-family"); -implementedProperties.add("font-size"); -implementedProperties.add("font-style"); -implementedProperties.add("font-variant"); -implementedProperties.add("font-weight"); -implementedProperties.add("height"); -implementedProperties.add("left"); -implementedProperties.add("lighting-color"); -implementedProperties.add("line-height"); -implementedProperties.add("margin"); -implementedProperties.add("margin-bottom"); -implementedProperties.add("margin-left"); -implementedProperties.add("margin-right"); -implementedProperties.add("margin-top"); -implementedProperties.add("opacity"); -implementedProperties.add("outline-color"); -implementedProperties.add("padding"); -implementedProperties.add("padding-bottom"); -implementedProperties.add("padding-left"); -implementedProperties.add("padding-right"); -implementedProperties.add("padding-top"); -implementedProperties.add("right"); -implementedProperties.add("stop-color"); -implementedProperties.add("text-line-through-color"); -implementedProperties.add("text-overline-color"); -implementedProperties.add("text-underline-color"); -implementedProperties.add("top"); -implementedProperties.add("webkit-border-after-color"); -implementedProperties.add("webkit-border-before-color"); -implementedProperties.add("webkit-border-end-color"); -implementedProperties.add("webkit-border-start-color"); -implementedProperties.add("webkit-column-rule-color"); -implementedProperties.add("webkit-match-nearest-mail-blockquote-color"); -implementedProperties.add("webkit-tap-highlight-color"); -implementedProperties.add("webkit-text-emphasis-color"); -implementedProperties.add("webkit-text-fill-color"); -implementedProperties.add("webkit-text-stroke-color"); -implementedProperties.add("width"); -module.exports = implementedProperties; - - -/***/ }), - -/***/ 37032: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/********************************************************************* - * These are commonly used parsers for CSS Values they take a string * - * to parse and return a string after it's been converted, if needed * - ********************************************************************/ - - -const namedColors = __nccwpck_require__(3800); -const { hslToRgb } = __nccwpck_require__(90515); - -exports.TYPES = { - INTEGER: 1, - NUMBER: 2, - LENGTH: 3, - PERCENT: 4, - URL: 5, - COLOR: 6, - STRING: 7, - ANGLE: 8, - KEYWORD: 9, - NULL_OR_EMPTY_STR: 10, - CALC: 11, -}; - -// rough regular expressions -var integerRegEx = /^[-+]?[0-9]+$/; -var numberRegEx = /^[-+]?[0-9]*\.?[0-9]+$/; -var lengthRegEx = /^(0|[-+]?[0-9]*\.?[0-9]+(in|cm|em|mm|pt|pc|px|ex|rem|vh|vw|ch))$/; -var percentRegEx = /^[-+]?[0-9]*\.?[0-9]+%$/; -var urlRegEx = /^url\(\s*([^)]*)\s*\)$/; -var stringRegEx = /^("[^"]*"|'[^']*')$/; -var colorRegEx1 = /^#([0-9a-fA-F]{3,4}){1,2}$/; -var colorRegEx2 = /^rgb\(([^)]*)\)$/; -var colorRegEx3 = /^rgba\(([^)]*)\)$/; -var calcRegEx = /^calc\(([^)]*)\)$/; -var colorRegEx4 = /^hsla?\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*(,\s*(-?\d+|-?\d*.\d+)\s*)?\)/; -var angleRegEx = /^([-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/; - -// This will return one of the above types based on the passed in string -exports.valueType = function valueType(val) { - if (val === '' || val === null) { - return exports.TYPES.NULL_OR_EMPTY_STR; - } - if (typeof val === 'number') { - val = val.toString(); - } - - if (typeof val !== 'string') { - return undefined; - } - - if (integerRegEx.test(val)) { - return exports.TYPES.INTEGER; - } - if (numberRegEx.test(val)) { - return exports.TYPES.NUMBER; - } - if (lengthRegEx.test(val)) { - return exports.TYPES.LENGTH; - } - if (percentRegEx.test(val)) { - return exports.TYPES.PERCENT; - } - if (urlRegEx.test(val)) { - return exports.TYPES.URL; - } - if (calcRegEx.test(val)) { - return exports.TYPES.CALC; - } - if (stringRegEx.test(val)) { - return exports.TYPES.STRING; - } - if (angleRegEx.test(val)) { - return exports.TYPES.ANGLE; - } - if (colorRegEx1.test(val)) { - return exports.TYPES.COLOR; - } - - var res = colorRegEx2.exec(val); - var parts; - if (res !== null) { - parts = res[1].split(/\s*,\s*/); - if (parts.length !== 3) { - return undefined; - } - if ( - parts.every(percentRegEx.test.bind(percentRegEx)) || - parts.every(integerRegEx.test.bind(integerRegEx)) - ) { - return exports.TYPES.COLOR; - } - return undefined; - } - res = colorRegEx3.exec(val); - if (res !== null) { - parts = res[1].split(/\s*,\s*/); - if (parts.length !== 4) { - return undefined; - } - if ( - parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx)) || - parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx)) - ) { - if (numberRegEx.test(parts[3])) { - return exports.TYPES.COLOR; - } - } - return undefined; - } - - if (colorRegEx4.test(val)) { - return exports.TYPES.COLOR; - } - - // could still be a color, one of the standard keyword colors - val = val.toLowerCase(); - - if (namedColors.includes(val)) { - return exports.TYPES.COLOR; - } - - switch (val) { - // the following are deprecated in CSS3 - case 'activeborder': - case 'activecaption': - case 'appworkspace': - case 'background': - case 'buttonface': - case 'buttonhighlight': - case 'buttonshadow': - case 'buttontext': - case 'captiontext': - case 'graytext': - case 'highlight': - case 'highlighttext': - case 'inactiveborder': - case 'inactivecaption': - case 'inactivecaptiontext': - case 'infobackground': - case 'infotext': - case 'menu': - case 'menutext': - case 'scrollbar': - case 'threeddarkshadow': - case 'threedface': - case 'threedhighlight': - case 'threedlightshadow': - case 'threedshadow': - case 'window': - case 'windowframe': - case 'windowtext': - return exports.TYPES.COLOR; - default: - return exports.TYPES.KEYWORD; - } -}; - -exports.parseInteger = function parseInteger(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.INTEGER) { - return undefined; - } - return String(parseInt(val, 10)); -}; - -exports.parseNumber = function parseNumber(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.NUMBER && type !== exports.TYPES.INTEGER) { - return undefined; - } - return String(parseFloat(val)); -}; - -exports.parseLength = function parseLength(val) { - if (val === 0 || val === '0') { - return '0px'; - } - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.LENGTH) { - return undefined; - } - return val; -}; - -exports.parsePercent = function parsePercent(val) { - if (val === 0 || val === '0') { - return '0%'; - } - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.PERCENT) { - return undefined; - } - return val; -}; - -// either a length or a percent -exports.parseMeasurement = function parseMeasurement(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.CALC) { - return val; - } - - var length = exports.parseLength(val); - if (length !== undefined) { - return length; - } - return exports.parsePercent(val); -}; - -exports.parseUrl = function parseUrl(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - var res = urlRegEx.exec(val); - // does it match the regex? - if (!res) { - return undefined; - } - var str = res[1]; - // if it starts with single or double quotes, does it end with the same? - if ((str[0] === '"' || str[0] === "'") && str[0] !== str[str.length - 1]) { - return undefined; - } - if (str[0] === '"' || str[0] === "'") { - str = str.substr(1, str.length - 2); - } - - var i; - for (i = 0; i < str.length; i++) { - switch (str[i]) { - case '(': - case ')': - case ' ': - case '\t': - case '\n': - case "'": - case '"': - return undefined; - case '\\': - i++; - break; - } - } - - return 'url(' + str + ')'; -}; - -exports.parseString = function parseString(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.STRING) { - return undefined; - } - var i; - for (i = 1; i < val.length - 1; i++) { - switch (val[i]) { - case val[0]: - return undefined; - case '\\': - i++; - while (i < val.length - 1 && /[0-9A-Fa-f]/.test(val[i])) { - i++; - } - break; - } - } - if (i >= val.length) { - return undefined; - } - return val; -}; - -exports.parseColor = function parseColor(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - var red, - green, - blue, - hue, - saturation, - lightness, - alpha = 1; - var parts; - var res = colorRegEx1.exec(val); - // is it #aaa, #ababab, #aaaa, #abababaa - if (res) { - var defaultHex = val.substr(1); - var hex = val.substr(1); - if (hex.length === 3 || hex.length === 4) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; - - if (defaultHex.length === 4) { - hex = hex + defaultHex[3] + defaultHex[3]; - } - } - red = parseInt(hex.substr(0, 2), 16); - green = parseInt(hex.substr(2, 2), 16); - blue = parseInt(hex.substr(4, 2), 16); - if (hex.length === 8) { - var hexAlpha = hex.substr(6, 2); - var hexAlphaToRgbaAlpha = Number((parseInt(hexAlpha, 16) / 255).toFixed(3)); - - return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + hexAlphaToRgbaAlpha + ')'; - } - return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; - } - - res = colorRegEx2.exec(val); - if (res) { - parts = res[1].split(/\s*,\s*/); - if (parts.length !== 3) { - return undefined; - } - if (parts.every(percentRegEx.test.bind(percentRegEx))) { - red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); - green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); - blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); - } else if (parts.every(integerRegEx.test.bind(integerRegEx))) { - red = parseInt(parts[0], 10); - green = parseInt(parts[1], 10); - blue = parseInt(parts[2], 10); - } else { - return undefined; - } - red = Math.min(255, Math.max(0, red)); - green = Math.min(255, Math.max(0, green)); - blue = Math.min(255, Math.max(0, blue)); - return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; - } - - res = colorRegEx3.exec(val); - if (res) { - parts = res[1].split(/\s*,\s*/); - if (parts.length !== 4) { - return undefined; - } - if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx))) { - red = Math.floor((parseFloat(parts[0].slice(0, -1)) * 255) / 100); - green = Math.floor((parseFloat(parts[1].slice(0, -1)) * 255) / 100); - blue = Math.floor((parseFloat(parts[2].slice(0, -1)) * 255) / 100); - alpha = parseFloat(parts[3]); - } else if (parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx))) { - red = parseInt(parts[0], 10); - green = parseInt(parts[1], 10); - blue = parseInt(parts[2], 10); - alpha = parseFloat(parts[3]); - } else { - return undefined; - } - if (isNaN(alpha)) { - alpha = 1; - } - red = Math.min(255, Math.max(0, red)); - green = Math.min(255, Math.max(0, green)); - blue = Math.min(255, Math.max(0, blue)); - alpha = Math.min(1, Math.max(0, alpha)); - if (alpha === 1) { - return 'rgb(' + red + ', ' + green + ', ' + blue + ')'; - } - return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')'; - } - - res = colorRegEx4.exec(val); - if (res) { - const [, _hue, _saturation, _lightness, _alphaString = ''] = res; - const _alpha = parseFloat(_alphaString.replace(',', '').trim()); - if (!_hue || !_saturation || !_lightness) { - return undefined; - } - hue = parseFloat(_hue); - saturation = parseInt(_saturation, 10); - lightness = parseInt(_lightness, 10); - if (_alpha && numberRegEx.test(_alpha)) { - alpha = parseFloat(_alpha); - } - - const [r, g, b] = hslToRgb(hue, saturation / 100, lightness / 100); - if (!_alphaString || alpha === 1) { - return 'rgb(' + r + ', ' + g + ', ' + b + ')'; - } - return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; - } - - if (type === exports.TYPES.COLOR) { - return val; - } - return undefined; -}; - -exports.parseAngle = function parseAngle(val) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.ANGLE) { - return undefined; - } - var res = angleRegEx.exec(val); - var flt = parseFloat(res[1]); - if (res[2] === 'rad') { - flt *= 180 / Math.PI; - } else if (res[2] === 'grad') { - flt *= 360 / 400; - } - - while (flt < 0) { - flt += 360; - } - while (flt > 360) { - flt -= 360; - } - return flt + 'deg'; -}; - -exports.parseKeyword = function parseKeyword(val, valid_keywords) { - var type = exports.valueType(val); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - return val; - } - if (type !== exports.TYPES.KEYWORD) { - return undefined; - } - val = val.toString().toLowerCase(); - var i; - for (i = 0; i < valid_keywords.length; i++) { - if (valid_keywords[i].toLowerCase() === val) { - return valid_keywords[i]; - } - } - return undefined; -}; - -// utility to translate from border-width to borderWidth -var dashedToCamelCase = function(dashed) { - var i; - var camel = ''; - var nextCap = false; - for (i = 0; i < dashed.length; i++) { - if (dashed[i] !== '-') { - camel += nextCap ? dashed[i].toUpperCase() : dashed[i]; - nextCap = false; - } else { - nextCap = true; - } - } - return camel; -}; -exports.dashedToCamelCase = dashedToCamelCase; - -var is_space = /\s/; -var opening_deliminators = ['"', "'", '(']; -var closing_deliminators = ['"', "'", ')']; -// this splits on whitespace, but keeps quoted and parened parts together -var getParts = function(str) { - var deliminator_stack = []; - var length = str.length; - var i; - var parts = []; - var current_part = ''; - var opening_index; - var closing_index; - for (i = 0; i < length; i++) { - opening_index = opening_deliminators.indexOf(str[i]); - closing_index = closing_deliminators.indexOf(str[i]); - if (is_space.test(str[i])) { - if (deliminator_stack.length === 0) { - if (current_part !== '') { - parts.push(current_part); - } - current_part = ''; - } else { - current_part += str[i]; - } - } else { - if (str[i] === '\\') { - i++; - current_part += str[i]; - } else { - current_part += str[i]; - if ( - closing_index !== -1 && - closing_index === deliminator_stack[deliminator_stack.length - 1] - ) { - deliminator_stack.pop(); - } else if (opening_index !== -1) { - deliminator_stack.push(opening_index); - } - } - } - } - if (current_part !== '') { - parts.push(current_part); - } - return parts; -}; - -/* - * this either returns undefined meaning that it isn't valid - * or returns an object where the keys are dashed short - * hand properties and the values are the values to set - * on them - */ -exports.shorthandParser = function parse(v, shorthand_for) { - var obj = {}; - var type = exports.valueType(v); - if (type === exports.TYPES.NULL_OR_EMPTY_STR) { - Object.keys(shorthand_for).forEach(function(property) { - obj[property] = ''; - }); - return obj; - } - - if (typeof v === 'number') { - v = v.toString(); - } - - if (typeof v !== 'string') { - return undefined; - } - - if (v.toLowerCase() === 'inherit') { - return {}; - } - var parts = getParts(v); - var valid = true; - parts.forEach(function(part, i) { - var part_valid = false; - Object.keys(shorthand_for).forEach(function(property) { - if (shorthand_for[property].isValid(part, i)) { - part_valid = true; - obj[property] = part; - } - }); - valid = valid && part_valid; - }); - if (!valid) { - return undefined; - } - return obj; -}; - -exports.shorthandSetter = function(property, shorthand_for) { - return function(v) { - var obj = exports.shorthandParser(v, shorthand_for); - if (obj === undefined) { - return; - } - //console.log('shorthandSetter for:', property, 'obj:', obj); - Object.keys(obj).forEach(function(subprop) { - // in case subprop is an implicit property, this will clear - // *its* subpropertiesX - var camel = dashedToCamelCase(subprop); - this[camel] = obj[subprop]; - // in case it gets translated into something else (0 -> 0px) - obj[subprop] = this[camel]; - this.removeProperty(subprop); - // don't add in empty properties - if (obj[subprop] !== '') { - this._values[subprop] = obj[subprop]; - } - }, this); - Object.keys(shorthand_for).forEach(function(subprop) { - if (!obj.hasOwnProperty(subprop)) { - this.removeProperty(subprop); - delete this._values[subprop]; - } - }, this); - // in case the value is something like 'none' that removes all values, - // check that the generated one is not empty, first remove the property - // if it already exists, then call the shorthandGetter, if it's an empty - // string, don't set the property - this.removeProperty(property); - var calculated = exports.shorthandGetter(property, shorthand_for).call(this); - if (calculated !== '') { - this._setProperty(property, calculated); - } - }; -}; - -exports.shorthandGetter = function(property, shorthand_for) { - return function() { - if (this._values[property] !== undefined) { - return this.getPropertyValue(property); - } - return Object.keys(shorthand_for) - .map(function(subprop) { - return this.getPropertyValue(subprop); - }, this) - .filter(function(value) { - return value !== ''; - }) - .join(' '); - }; -}; - -// isValid(){1,4} | inherit -// if one, it applies to all -// if two, the first applies to the top and bottom, and the second to left and right -// if three, the first applies to the top, the second to left and right, the third bottom -// if four, top, right, bottom, left -exports.implicitSetter = function(property_before, property_after, isValid, parser) { - property_after = property_after || ''; - if (property_after !== '') { - property_after = '-' + property_after; - } - var part_names = ['top', 'right', 'bottom', 'left']; - - return function(v) { - if (typeof v === 'number') { - v = v.toString(); - } - if (typeof v !== 'string') { - return undefined; - } - var parts; - if (v.toLowerCase() === 'inherit' || v === '') { - parts = [v]; - } else { - parts = getParts(v); - } - if (parts.length < 1 || parts.length > 4) { - return undefined; - } - - if (!parts.every(isValid)) { - return undefined; - } - - parts = parts.map(function(part) { - return parser(part); - }); - this._setProperty(property_before + property_after, parts.join(' ')); - if (parts.length === 1) { - parts[1] = parts[0]; - } - if (parts.length === 2) { - parts[2] = parts[0]; - } - if (parts.length === 3) { - parts[3] = parts[1]; - } - - for (var i = 0; i < 4; i++) { - var property = property_before + '-' + part_names[i] + property_after; - this.removeProperty(property); - if (parts[i] !== '') { - this._values[property] = parts[i]; - } - } - return v; - }; -}; - -// -// Companion to implicitSetter, but for the individual parts. -// This sets the individual value, and checks to see if all four -// sub-parts are set. If so, it sets the shorthand version and removes -// the individual parts from the cssText. -// -exports.subImplicitSetter = function(prefix, part, isValid, parser) { - var property = prefix + '-' + part; - var subparts = [prefix + '-top', prefix + '-right', prefix + '-bottom', prefix + '-left']; - - return function(v) { - if (typeof v === 'number') { - v = v.toString(); - } - if (typeof v !== 'string') { - return undefined; - } - if (!isValid(v)) { - return undefined; - } - v = parser(v); - this._setProperty(property, v); - var parts = []; - for (var i = 0; i < 4; i++) { - if (this._values[subparts[i]] == null || this._values[subparts[i]] === '') { - break; - } - parts.push(this._values[subparts[i]]); - } - if (parts.length === 4) { - for (i = 0; i < 4; i++) { - this.removeProperty(subparts[i]); - this._values[subparts[i]] = parts[i]; - } - this._setProperty(prefix, parts.join(' ')); - } - return v; - }; -}; - -var camel_to_dashed = /[A-Z]/g; -var first_segment = /^\([^-]\)-/; -var vendor_prefixes = ['o', 'moz', 'ms', 'webkit']; -exports.camelToDashed = function(camel_case) { - var match; - var dashed = camel_case.replace(camel_to_dashed, '-$&').toLowerCase(); - match = dashed.match(first_segment); - if (match && vendor_prefixes.indexOf(match[1]) !== -1) { - dashed = '-' + dashed; - } - return dashed; -}; - - -/***/ }), - -/***/ 13480: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// autogenerated - 4/29/2020 - -/* - * - * https://www.w3.org/Style/CSS/all-properties.en.html - */ - -var external_dependency_parsers_0 = __nccwpck_require__(37032); - -var external_dependency_constants_1 = __nccwpck_require__(39139); - -var azimuth_export_definition; -azimuth_export_definition = { - set: function (v) { - var valueType = external_dependency_parsers_0.valueType(v); - - if (valueType === external_dependency_parsers_0.TYPES.ANGLE) { - return this._setProperty('azimuth', external_dependency_parsers_0.parseAngle(v)); - } - - if (valueType === external_dependency_parsers_0.TYPES.KEYWORD) { - var keywords = v.toLowerCase().trim().split(/\s+/); - var hasBehind = false; - - if (keywords.length > 2) { - return; - } - - var behindIndex = keywords.indexOf('behind'); - hasBehind = behindIndex !== -1; - - if (keywords.length === 2) { - if (!hasBehind) { - return; - } - - keywords.splice(behindIndex, 1); - } - - if (keywords[0] === 'leftwards' || keywords[0] === 'rightwards') { - if (hasBehind) { - return; - } - - return this._setProperty('azimuth', keywords[0]); - } - - if (keywords[0] === 'behind') { - return this._setProperty('azimuth', '180deg'); - } - - switch (keywords[0]) { - case 'left-side': - return this._setProperty('azimuth', '270deg'); - - case 'far-left': - return this._setProperty('azimuth', (hasBehind ? 240 : 300) + 'deg'); - - case 'left': - return this._setProperty('azimuth', (hasBehind ? 220 : 320) + 'deg'); - - case 'center-left': - return this._setProperty('azimuth', (hasBehind ? 200 : 340) + 'deg'); - - case 'center': - return this._setProperty('azimuth', (hasBehind ? 180 : 0) + 'deg'); - - case 'center-right': - return this._setProperty('azimuth', (hasBehind ? 160 : 20) + 'deg'); - - case 'right': - return this._setProperty('azimuth', (hasBehind ? 140 : 40) + 'deg'); - - case 'far-right': - return this._setProperty('azimuth', (hasBehind ? 120 : 60) + 'deg'); - - case 'right-side': - return this._setProperty('azimuth', '90deg'); - - default: - return; - } - } - }, - get: function () { - return this.getPropertyValue('azimuth'); - }, - enumerable: true, - configurable: true -}; -var backgroundColor_export_isValid, backgroundColor_export_definition; - -var backgroundColor_local_var_parse = function parse(v) { - var parsed = external_dependency_parsers_0.parseColor(v); - - if (parsed !== undefined) { - return parsed; - } - - if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'transparent' || v.toLowerCase() === 'inherit')) { - return v; - } - - return undefined; -}; - -backgroundColor_export_isValid = function isValid(v) { - return backgroundColor_local_var_parse(v) !== undefined; -}; - -backgroundColor_export_definition = { - set: function (v) { - var parsed = backgroundColor_local_var_parse(v); - - if (parsed === undefined) { - return; - } - - this._setProperty('background-color', parsed); - }, - get: function () { - return this.getPropertyValue('background-color'); - }, - enumerable: true, - configurable: true -}; -var backgroundImage_export_isValid, backgroundImage_export_definition; - -var backgroundImage_local_var_parse = function parse(v) { - var parsed = external_dependency_parsers_0.parseUrl(v); - - if (parsed !== undefined) { - return parsed; - } - - if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'none' || v.toLowerCase() === 'inherit')) { - return v; - } - - return undefined; -}; - -backgroundImage_export_isValid = function isValid(v) { - return backgroundImage_local_var_parse(v) !== undefined; -}; - -backgroundImage_export_definition = { - set: function (v) { - this._setProperty('background-image', backgroundImage_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('background-image'); - }, - enumerable: true, - configurable: true -}; -var backgroundRepeat_export_isValid, backgroundRepeat_export_definition; - -var backgroundRepeat_local_var_parse = function parse(v) { - if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'repeat' || v.toLowerCase() === 'repeat-x' || v.toLowerCase() === 'repeat-y' || v.toLowerCase() === 'no-repeat' || v.toLowerCase() === 'inherit')) { - return v; - } - - return undefined; -}; - -backgroundRepeat_export_isValid = function isValid(v) { - return backgroundRepeat_local_var_parse(v) !== undefined; -}; - -backgroundRepeat_export_definition = { - set: function (v) { - this._setProperty('background-repeat', backgroundRepeat_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('background-repeat'); - }, - enumerable: true, - configurable: true -}; -var backgroundAttachment_export_isValid, backgroundAttachment_export_definition; - -var backgroundAttachment_local_var_isValid = backgroundAttachment_export_isValid = function isValid(v) { - return external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'scroll' || v.toLowerCase() === 'fixed' || v.toLowerCase() === 'inherit'); -}; - -backgroundAttachment_export_definition = { - set: function (v) { - if (!backgroundAttachment_local_var_isValid(v)) { - return; - } - - this._setProperty('background-attachment', v); - }, - get: function () { - return this.getPropertyValue('background-attachment'); - }, - enumerable: true, - configurable: true -}; -var backgroundPosition_export_isValid, backgroundPosition_export_definition; -var backgroundPosition_local_var_valid_keywords = ['top', 'center', 'bottom', 'left', 'right']; - -var backgroundPosition_local_var_parse = function parse(v) { - if (v === '' || v === null) { - return undefined; - } - - var parts = v.split(/\s+/); - - if (parts.length > 2 || parts.length < 1) { - return undefined; - } - - var types = []; - parts.forEach(function (part, index) { - types[index] = external_dependency_parsers_0.valueType(part); - }); - - if (parts.length === 1) { - if (types[0] === external_dependency_parsers_0.TYPES.LENGTH || types[0] === external_dependency_parsers_0.TYPES.PERCENT) { - return v; - } - - if (types[0] === external_dependency_parsers_0.TYPES.KEYWORD) { - if (backgroundPosition_local_var_valid_keywords.indexOf(v.toLowerCase()) !== -1 || v.toLowerCase() === 'inherit') { - return v; - } - } - - return undefined; - } - - if ((types[0] === external_dependency_parsers_0.TYPES.LENGTH || types[0] === external_dependency_parsers_0.TYPES.PERCENT) && (types[1] === external_dependency_parsers_0.TYPES.LENGTH || types[1] === external_dependency_parsers_0.TYPES.PERCENT)) { - return v; - } - - if (types[0] !== external_dependency_parsers_0.TYPES.KEYWORD || types[1] !== external_dependency_parsers_0.TYPES.KEYWORD) { - return undefined; - } - - if (backgroundPosition_local_var_valid_keywords.indexOf(parts[0]) !== -1 && backgroundPosition_local_var_valid_keywords.indexOf(parts[1]) !== -1) { - return v; - } - - return undefined; -}; - -backgroundPosition_export_isValid = function isValid(v) { - return backgroundPosition_local_var_parse(v) !== undefined; -}; - -backgroundPosition_export_definition = { - set: function (v) { - this._setProperty('background-position', backgroundPosition_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('background-position'); - }, - enumerable: true, - configurable: true -}; -var background_export_definition; -var background_local_var_shorthand_for = { - 'background-color': { - isValid: backgroundColor_export_isValid, - definition: backgroundColor_export_definition - }, - 'background-image': { - isValid: backgroundImage_export_isValid, - definition: backgroundImage_export_definition - }, - 'background-repeat': { - isValid: backgroundRepeat_export_isValid, - definition: backgroundRepeat_export_definition - }, - 'background-attachment': { - isValid: backgroundAttachment_export_isValid, - definition: backgroundAttachment_export_definition - }, - 'background-position': { - isValid: backgroundPosition_export_isValid, - definition: backgroundPosition_export_definition - } -}; -background_export_definition = { - set: external_dependency_parsers_0.shorthandSetter('background', background_local_var_shorthand_for), - get: external_dependency_parsers_0.shorthandGetter('background', background_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var borderWidth_export_isValid, borderWidth_export_definition; -// the valid border-widths: -var borderWidth_local_var_widths = ['thin', 'medium', 'thick']; - -borderWidth_export_isValid = function parse(v) { - var length = external_dependency_parsers_0.parseLength(v); - - if (length !== undefined) { - return true; - } - - if (typeof v !== 'string') { - return false; - } - - if (v === '') { - return true; - } - - v = v.toLowerCase(); - - if (borderWidth_local_var_widths.indexOf(v) === -1) { - return false; - } - - return true; -}; - -var borderWidth_local_var_isValid = borderWidth_export_isValid; - -var borderWidth_local_var_parser = function (v) { - var length = external_dependency_parsers_0.parseLength(v); - - if (length !== undefined) { - return length; - } - - if (borderWidth_local_var_isValid(v)) { - return v.toLowerCase(); - } - - return undefined; -}; - -borderWidth_export_definition = { - set: external_dependency_parsers_0.implicitSetter('border', 'width', borderWidth_local_var_isValid, borderWidth_local_var_parser), - get: function () { - return this.getPropertyValue('border-width'); - }, - enumerable: true, - configurable: true -}; -var borderStyle_export_isValid, borderStyle_export_definition; -// the valid border-styles: -var borderStyle_local_var_styles = ['none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset']; - -borderStyle_export_isValid = function parse(v) { - return typeof v === 'string' && (v === '' || borderStyle_local_var_styles.indexOf(v) !== -1); -}; - -var borderStyle_local_var_isValid = borderStyle_export_isValid; - -var borderStyle_local_var_parser = function (v) { - if (borderStyle_local_var_isValid(v)) { - return v.toLowerCase(); - } - - return undefined; -}; - -borderStyle_export_definition = { - set: external_dependency_parsers_0.implicitSetter('border', 'style', borderStyle_local_var_isValid, borderStyle_local_var_parser), - get: function () { - return this.getPropertyValue('border-style'); - }, - enumerable: true, - configurable: true -}; -var borderColor_export_isValid, borderColor_export_definition; - -borderColor_export_isValid = function parse(v) { - if (typeof v !== 'string') { - return false; - } - - return v === '' || v.toLowerCase() === 'transparent' || external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.COLOR; -}; - -var borderColor_local_var_isValid = borderColor_export_isValid; - -var borderColor_local_var_parser = function (v) { - if (borderColor_local_var_isValid(v)) { - return v.toLowerCase(); - } - - return undefined; -}; - -borderColor_export_definition = { - set: external_dependency_parsers_0.implicitSetter('border', 'color', borderColor_local_var_isValid, borderColor_local_var_parser), - get: function () { - return this.getPropertyValue('border-color'); - }, - enumerable: true, - configurable: true -}; -var border_export_definition; -var border_local_var_shorthand_for = { - 'border-width': { - isValid: borderWidth_export_isValid, - definition: borderWidth_export_definition - }, - 'border-style': { - isValid: borderStyle_export_isValid, - definition: borderStyle_export_definition - }, - 'border-color': { - isValid: borderColor_export_isValid, - definition: borderColor_export_definition - } -}; -var border_local_var_myShorthandSetter = external_dependency_parsers_0.shorthandSetter('border', border_local_var_shorthand_for); -var border_local_var_myShorthandGetter = external_dependency_parsers_0.shorthandGetter('border', border_local_var_shorthand_for); -border_export_definition = { - set: function (v) { - if (v.toString().toLowerCase() === 'none') { - v = ''; - } - - border_local_var_myShorthandSetter.call(this, v); - this.removeProperty('border-top'); - this.removeProperty('border-left'); - this.removeProperty('border-right'); - this.removeProperty('border-bottom'); - this._values['border-top'] = this._values.border; - this._values['border-left'] = this._values.border; - this._values['border-right'] = this._values.border; - this._values['border-bottom'] = this._values.border; - }, - get: border_local_var_myShorthandGetter, - enumerable: true, - configurable: true -}; -var borderBottomWidth_export_isValid, borderBottomWidth_export_definition; -var borderBottomWidth_local_var_isValid = borderBottomWidth_export_isValid = borderWidth_export_isValid; -borderBottomWidth_export_definition = { - set: function (v) { - if (borderBottomWidth_local_var_isValid(v)) { - this._setProperty('border-bottom-width', v); - } - }, - get: function () { - return this.getPropertyValue('border-bottom-width'); - }, - enumerable: true, - configurable: true -}; -var borderBottomStyle_export_isValid, borderBottomStyle_export_definition; -borderBottomStyle_export_isValid = borderStyle_export_isValid; -borderBottomStyle_export_definition = { - set: function (v) { - if (borderStyle_export_isValid(v)) { - if (v.toLowerCase() === 'none') { - v = ''; - this.removeProperty('border-bottom-width'); - } - - this._setProperty('border-bottom-style', v); - } - }, - get: function () { - return this.getPropertyValue('border-bottom-style'); - }, - enumerable: true, - configurable: true -}; -var borderBottomColor_export_isValid, borderBottomColor_export_definition; -var borderBottomColor_local_var_isValid = borderBottomColor_export_isValid = borderColor_export_isValid; -borderBottomColor_export_definition = { - set: function (v) { - if (borderBottomColor_local_var_isValid(v)) { - this._setProperty('border-bottom-color', v); - } - }, - get: function () { - return this.getPropertyValue('border-bottom-color'); - }, - enumerable: true, - configurable: true -}; -var borderBottom_export_definition; -var borderBottom_local_var_shorthand_for = { - 'border-bottom-width': { - isValid: borderBottomWidth_export_isValid, - definition: borderBottomWidth_export_definition - }, - 'border-bottom-style': { - isValid: borderBottomStyle_export_isValid, - definition: borderBottomStyle_export_definition - }, - 'border-bottom-color': { - isValid: borderBottomColor_export_isValid, - definition: borderBottomColor_export_definition - } -}; -borderBottom_export_definition = { - set: external_dependency_parsers_0.shorthandSetter('border-bottom', borderBottom_local_var_shorthand_for), - get: external_dependency_parsers_0.shorthandGetter('border-bottom', borderBottom_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var borderCollapse_export_definition; - -var borderCollapse_local_var_parse = function parse(v) { - if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && (v.toLowerCase() === 'collapse' || v.toLowerCase() === 'separate' || v.toLowerCase() === 'inherit')) { - return v; - } - - return undefined; -}; - -borderCollapse_export_definition = { - set: function (v) { - this._setProperty('border-collapse', borderCollapse_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('border-collapse'); - }, - enumerable: true, - configurable: true -}; -var borderLeftWidth_export_isValid, borderLeftWidth_export_definition; -var borderLeftWidth_local_var_isValid = borderLeftWidth_export_isValid = borderWidth_export_isValid; -borderLeftWidth_export_definition = { - set: function (v) { - if (borderLeftWidth_local_var_isValid(v)) { - this._setProperty('border-left-width', v); - } - }, - get: function () { - return this.getPropertyValue('border-left-width'); - }, - enumerable: true, - configurable: true -}; -var borderLeftStyle_export_isValid, borderLeftStyle_export_definition; -borderLeftStyle_export_isValid = borderStyle_export_isValid; -borderLeftStyle_export_definition = { - set: function (v) { - if (borderStyle_export_isValid(v)) { - if (v.toLowerCase() === 'none') { - v = ''; - this.removeProperty('border-left-width'); - } - - this._setProperty('border-left-style', v); - } - }, - get: function () { - return this.getPropertyValue('border-left-style'); - }, - enumerable: true, - configurable: true -}; -var borderLeftColor_export_isValid, borderLeftColor_export_definition; -var borderLeftColor_local_var_isValid = borderLeftColor_export_isValid = borderColor_export_isValid; -borderLeftColor_export_definition = { - set: function (v) { - if (borderLeftColor_local_var_isValid(v)) { - this._setProperty('border-left-color', v); - } - }, - get: function () { - return this.getPropertyValue('border-left-color'); - }, - enumerable: true, - configurable: true -}; -var borderLeft_export_definition; -var borderLeft_local_var_shorthand_for = { - 'border-left-width': { - isValid: borderLeftWidth_export_isValid, - definition: borderLeftWidth_export_definition - }, - 'border-left-style': { - isValid: borderLeftStyle_export_isValid, - definition: borderLeftStyle_export_definition - }, - 'border-left-color': { - isValid: borderLeftColor_export_isValid, - definition: borderLeftColor_export_definition - } -}; -borderLeft_export_definition = { - set: external_dependency_parsers_0.shorthandSetter('border-left', borderLeft_local_var_shorthand_for), - get: external_dependency_parsers_0.shorthandGetter('border-left', borderLeft_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var borderRightWidth_export_isValid, borderRightWidth_export_definition; -var borderRightWidth_local_var_isValid = borderRightWidth_export_isValid = borderWidth_export_isValid; -borderRightWidth_export_definition = { - set: function (v) { - if (borderRightWidth_local_var_isValid(v)) { - this._setProperty('border-right-width', v); - } - }, - get: function () { - return this.getPropertyValue('border-right-width'); - }, - enumerable: true, - configurable: true -}; -var borderRightStyle_export_isValid, borderRightStyle_export_definition; -borderRightStyle_export_isValid = borderStyle_export_isValid; -borderRightStyle_export_definition = { - set: function (v) { - if (borderStyle_export_isValid(v)) { - if (v.toLowerCase() === 'none') { - v = ''; - this.removeProperty('border-right-width'); - } - - this._setProperty('border-right-style', v); - } - }, - get: function () { - return this.getPropertyValue('border-right-style'); - }, - enumerable: true, - configurable: true -}; -var borderRightColor_export_isValid, borderRightColor_export_definition; -var borderRightColor_local_var_isValid = borderRightColor_export_isValid = borderColor_export_isValid; -borderRightColor_export_definition = { - set: function (v) { - if (borderRightColor_local_var_isValid(v)) { - this._setProperty('border-right-color', v); - } - }, - get: function () { - return this.getPropertyValue('border-right-color'); - }, - enumerable: true, - configurable: true -}; -var borderRight_export_definition; -var borderRight_local_var_shorthand_for = { - 'border-right-width': { - isValid: borderRightWidth_export_isValid, - definition: borderRightWidth_export_definition - }, - 'border-right-style': { - isValid: borderRightStyle_export_isValid, - definition: borderRightStyle_export_definition - }, - 'border-right-color': { - isValid: borderRightColor_export_isValid, - definition: borderRightColor_export_definition - } -}; -borderRight_export_definition = { - set: external_dependency_parsers_0.shorthandSetter('border-right', borderRight_local_var_shorthand_for), - get: external_dependency_parsers_0.shorthandGetter('border-right', borderRight_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var borderSpacing_export_definition; - -// ? | inherit -// if one, it applies to both horizontal and verical spacing -// if two, the first applies to the horizontal and the second applies to vertical spacing -var borderSpacing_local_var_parse = function parse(v) { - if (v === '' || v === null) { - return undefined; - } - - if (v === 0) { - return '0px'; - } - - if (v.toLowerCase() === 'inherit') { - return v; - } - - var parts = v.split(/\s+/); - - if (parts.length !== 1 && parts.length !== 2) { - return undefined; - } - - parts.forEach(function (part) { - if (external_dependency_parsers_0.valueType(part) !== external_dependency_parsers_0.TYPES.LENGTH) { - return undefined; - } - }); - return v; -}; - -borderSpacing_export_definition = { - set: function (v) { - this._setProperty('border-spacing', borderSpacing_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('border-spacing'); - }, - enumerable: true, - configurable: true -}; -var borderTopWidth_export_isValid, borderTopWidth_export_definition; -borderTopWidth_export_isValid = borderWidth_export_isValid; -borderTopWidth_export_definition = { - set: function (v) { - if (borderWidth_export_isValid(v)) { - this._setProperty('border-top-width', v); - } - }, - get: function () { - return this.getPropertyValue('border-top-width'); - }, - enumerable: true, - configurable: true -}; -var borderTopStyle_export_isValid, borderTopStyle_export_definition; -borderTopStyle_export_isValid = borderStyle_export_isValid; -borderTopStyle_export_definition = { - set: function (v) { - if (borderStyle_export_isValid(v)) { - if (v.toLowerCase() === 'none') { - v = ''; - this.removeProperty('border-top-width'); - } - - this._setProperty('border-top-style', v); - } - }, - get: function () { - return this.getPropertyValue('border-top-style'); - }, - enumerable: true, - configurable: true -}; -var borderTopColor_export_isValid, borderTopColor_export_definition; -var borderTopColor_local_var_isValid = borderTopColor_export_isValid = borderColor_export_isValid; -borderTopColor_export_definition = { - set: function (v) { - if (borderTopColor_local_var_isValid(v)) { - this._setProperty('border-top-color', v); - } - }, - get: function () { - return this.getPropertyValue('border-top-color'); - }, - enumerable: true, - configurable: true -}; -var borderTop_export_definition; -var borderTop_local_var_shorthand_for = { - 'border-top-width': { - isValid: borderTopWidth_export_isValid, - definition: borderTopWidth_export_definition - }, - 'border-top-style': { - isValid: borderTopStyle_export_isValid, - definition: borderTopStyle_export_definition - }, - 'border-top-color': { - isValid: borderTopColor_export_isValid, - definition: borderTopColor_export_definition - } -}; -borderTop_export_definition = { - set: external_dependency_parsers_0.shorthandSetter('border-top', borderTop_local_var_shorthand_for), - get: external_dependency_parsers_0.shorthandGetter('border-top', borderTop_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var bottom_export_definition; -bottom_export_definition = { - set: function (v) { - this._setProperty('bottom', external_dependency_parsers_0.parseMeasurement(v)); - }, - get: function () { - return this.getPropertyValue('bottom'); - }, - enumerable: true, - configurable: true -}; -var clear_export_definition; -var clear_local_var_clear_keywords = ['none', 'left', 'right', 'both', 'inherit']; -clear_export_definition = { - set: function (v) { - this._setProperty('clear', external_dependency_parsers_0.parseKeyword(v, clear_local_var_clear_keywords)); - }, - get: function () { - return this.getPropertyValue('clear'); - }, - enumerable: true, - configurable: true -}; -var clip_export_definition; -var clip_local_var_shape_regex = /^rect\((.*)\)$/i; - -var clip_local_var_parse = function (val) { - if (val === '' || val === null) { - return val; - } - - if (typeof val !== 'string') { - return undefined; - } - - val = val.toLowerCase(); - - if (val === 'auto' || val === 'inherit') { - return val; - } - - var matches = val.match(clip_local_var_shape_regex); - - if (!matches) { - return undefined; - } - - var parts = matches[1].split(/\s*,\s*/); - - if (parts.length !== 4) { - return undefined; - } - - var valid = parts.every(function (part, index) { - var measurement = external_dependency_parsers_0.parseMeasurement(part); - parts[index] = measurement; - return measurement !== undefined; - }); - - if (!valid) { - return undefined; - } - - parts = parts.join(', '); - return val.replace(matches[1], parts); -}; - -clip_export_definition = { - set: function (v) { - this._setProperty('clip', clip_local_var_parse(v)); - }, - get: function () { - return this.getPropertyValue('clip'); - }, - enumerable: true, - configurable: true -}; -var color_export_definition; -color_export_definition = { - set: function (v) { - this._setProperty('color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('color'); - }, - enumerable: true, - configurable: true -}; -var cssFloat_export_definition; -cssFloat_export_definition = { - set: function (v) { - this._setProperty('float', v); - }, - get: function () { - return this.getPropertyValue('float'); - }, - enumerable: true, - configurable: true -}; -var flexGrow_export_isValid, flexGrow_export_definition; - -flexGrow_export_isValid = function isValid(v, positionAtFlexShorthand) { - return external_dependency_parsers_0.parseNumber(v) !== undefined && positionAtFlexShorthand === external_dependency_constants_1.POSITION_AT_SHORTHAND.first; -}; - -flexGrow_export_definition = { - set: function (v) { - this._setProperty('flex-grow', external_dependency_parsers_0.parseNumber(v)); - }, - get: function () { - return this.getPropertyValue('flex-grow'); - }, - enumerable: true, - configurable: true -}; -var flexShrink_export_isValid, flexShrink_export_definition; - -flexShrink_export_isValid = function isValid(v, positionAtFlexShorthand) { - return external_dependency_parsers_0.parseNumber(v) !== undefined && positionAtFlexShorthand === external_dependency_constants_1.POSITION_AT_SHORTHAND.second; -}; - -flexShrink_export_definition = { - set: function (v) { - this._setProperty('flex-shrink', external_dependency_parsers_0.parseNumber(v)); - }, - get: function () { - return this.getPropertyValue('flex-shrink'); - }, - enumerable: true, - configurable: true -}; -var flexBasis_export_isValid, flexBasis_export_definition; - -function flexBasis_local_fn_parse(v) { - if (String(v).toLowerCase() === 'auto') { - return 'auto'; - } - - if (String(v).toLowerCase() === 'inherit') { - return 'inherit'; - } - - return external_dependency_parsers_0.parseMeasurement(v); -} - -flexBasis_export_isValid = function isValid(v) { - return flexBasis_local_fn_parse(v) !== undefined; -}; - -flexBasis_export_definition = { - set: function (v) { - this._setProperty('flex-basis', flexBasis_local_fn_parse(v)); - }, - get: function () { - return this.getPropertyValue('flex-basis'); - }, - enumerable: true, - configurable: true -}; -var flex_export_isValid, flex_export_definition; -var flex_local_var_shorthand_for = { - 'flex-grow': { - isValid: flexGrow_export_isValid, - definition: flexGrow_export_definition - }, - 'flex-shrink': { - isValid: flexShrink_export_isValid, - definition: flexShrink_export_definition - }, - 'flex-basis': { - isValid: flexBasis_export_isValid, - definition: flexBasis_export_definition - } -}; -var flex_local_var_myShorthandSetter = external_dependency_parsers_0.shorthandSetter('flex', flex_local_var_shorthand_for); - -flex_export_isValid = function isValid(v) { - return external_dependency_parsers_0.shorthandParser(v, flex_local_var_shorthand_for) !== undefined; -}; - -flex_export_definition = { - set: function (v) { - var normalizedValue = String(v).trim().toLowerCase(); - - if (normalizedValue === 'none') { - flex_local_var_myShorthandSetter.call(this, '0 0 auto'); - return; - } - - if (normalizedValue === 'initial') { - flex_local_var_myShorthandSetter.call(this, '0 1 auto'); - return; - } - - if (normalizedValue === 'auto') { - this.removeProperty('flex-grow'); - this.removeProperty('flex-shrink'); - this.setProperty('flex-basis', normalizedValue); - return; - } - - flex_local_var_myShorthandSetter.call(this, v); - }, - get: external_dependency_parsers_0.shorthandGetter('flex', flex_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var float_export_definition; -float_export_definition = { - set: function (v) { - this._setProperty('float', v); - }, - get: function () { - return this.getPropertyValue('float'); - }, - enumerable: true, - configurable: true -}; -var floodColor_export_definition; -floodColor_export_definition = { - set: function (v) { - this._setProperty('flood-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('flood-color'); - }, - enumerable: true, - configurable: true -}; -var fontFamily_export_isValid, fontFamily_export_definition; -var fontFamily_local_var_partsRegEx = /\s*,\s*/; - -fontFamily_export_isValid = function isValid(v) { - if (v === '' || v === null) { - return true; - } - - var parts = v.split(fontFamily_local_var_partsRegEx); - var len = parts.length; - var i; - var type; - - for (i = 0; i < len; i++) { - type = external_dependency_parsers_0.valueType(parts[i]); - - if (type === external_dependency_parsers_0.TYPES.STRING || type === external_dependency_parsers_0.TYPES.KEYWORD) { - return true; - } - } - - return false; -}; - -fontFamily_export_definition = { - set: function (v) { - this._setProperty('font-family', v); - }, - get: function () { - return this.getPropertyValue('font-family'); - }, - enumerable: true, - configurable: true -}; -var fontSize_export_isValid, fontSize_export_definition; -var fontSize_local_var_absoluteSizes = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large']; -var fontSize_local_var_relativeSizes = ['larger', 'smaller']; - -fontSize_export_isValid = function (v) { - var type = external_dependency_parsers_0.valueType(v.toLowerCase()); - return type === external_dependency_parsers_0.TYPES.LENGTH || type === external_dependency_parsers_0.TYPES.PERCENT || type === external_dependency_parsers_0.TYPES.KEYWORD && fontSize_local_var_absoluteSizes.indexOf(v.toLowerCase()) !== -1 || type === external_dependency_parsers_0.TYPES.KEYWORD && fontSize_local_var_relativeSizes.indexOf(v.toLowerCase()) !== -1; -}; - -function fontSize_local_fn_parse(v) { - const valueAsString = String(v).toLowerCase(); - const optionalArguments = fontSize_local_var_absoluteSizes.concat(fontSize_local_var_relativeSizes); - const isOptionalArgument = optionalArguments.some(stringValue => stringValue.toLowerCase() === valueAsString); - return isOptionalArgument ? valueAsString : external_dependency_parsers_0.parseMeasurement(v); -} - -fontSize_export_definition = { - set: function (v) { - this._setProperty('font-size', fontSize_local_fn_parse(v)); - }, - get: function () { - return this.getPropertyValue('font-size'); - }, - enumerable: true, - configurable: true -}; -var fontStyle_export_isValid, fontStyle_export_definition; -var fontStyle_local_var_valid_styles = ['normal', 'italic', 'oblique', 'inherit']; - -fontStyle_export_isValid = function (v) { - return fontStyle_local_var_valid_styles.indexOf(v.toLowerCase()) !== -1; -}; - -fontStyle_export_definition = { - set: function (v) { - this._setProperty('font-style', v); - }, - get: function () { - return this.getPropertyValue('font-style'); - }, - enumerable: true, - configurable: true -}; -var fontVariant_export_isValid, fontVariant_export_definition; -var fontVariant_local_var_valid_variants = ['normal', 'small-caps', 'inherit']; - -fontVariant_export_isValid = function isValid(v) { - return fontVariant_local_var_valid_variants.indexOf(v.toLowerCase()) !== -1; -}; - -fontVariant_export_definition = { - set: function (v) { - this._setProperty('font-variant', v); - }, - get: function () { - return this.getPropertyValue('font-variant'); - }, - enumerable: true, - configurable: true -}; -var fontWeight_export_isValid, fontWeight_export_definition; -var fontWeight_local_var_valid_weights = ['normal', 'bold', 'bolder', 'lighter', '100', '200', '300', '400', '500', '600', '700', '800', '900', 'inherit']; - -fontWeight_export_isValid = function isValid(v) { - return fontWeight_local_var_valid_weights.indexOf(v.toLowerCase()) !== -1; -}; - -fontWeight_export_definition = { - set: function (v) { - this._setProperty('font-weight', v); - }, - get: function () { - return this.getPropertyValue('font-weight'); - }, - enumerable: true, - configurable: true -}; -var lineHeight_export_isValid, lineHeight_export_definition; - -lineHeight_export_isValid = function isValid(v) { - var type = external_dependency_parsers_0.valueType(v); - return type === external_dependency_parsers_0.TYPES.KEYWORD && v.toLowerCase() === 'normal' || v.toLowerCase() === 'inherit' || type === external_dependency_parsers_0.TYPES.NUMBER || type === external_dependency_parsers_0.TYPES.LENGTH || type === external_dependency_parsers_0.TYPES.PERCENT; -}; - -lineHeight_export_definition = { - set: function (v) { - this._setProperty('line-height', v); - }, - get: function () { - return this.getPropertyValue('line-height'); - }, - enumerable: true, - configurable: true -}; -var font_export_definition; -var font_local_var_shorthand_for = { - 'font-family': { - isValid: fontFamily_export_isValid, - definition: fontFamily_export_definition - }, - 'font-size': { - isValid: fontSize_export_isValid, - definition: fontSize_export_definition - }, - 'font-style': { - isValid: fontStyle_export_isValid, - definition: fontStyle_export_definition - }, - 'font-variant': { - isValid: fontVariant_export_isValid, - definition: fontVariant_export_definition - }, - 'font-weight': { - isValid: fontWeight_export_isValid, - definition: fontWeight_export_definition - }, - 'line-height': { - isValid: lineHeight_export_isValid, - definition: lineHeight_export_definition - } -}; -var font_local_var_static_fonts = ['caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', 'inherit']; -var font_local_var_setter = external_dependency_parsers_0.shorthandSetter('font', font_local_var_shorthand_for); -font_export_definition = { - set: function (v) { - var short = external_dependency_parsers_0.shorthandParser(v, font_local_var_shorthand_for); - - if (short !== undefined) { - return font_local_var_setter.call(this, v); - } - - if (external_dependency_parsers_0.valueType(v) === external_dependency_parsers_0.TYPES.KEYWORD && font_local_var_static_fonts.indexOf(v.toLowerCase()) !== -1) { - this._setProperty('font', v); - } - }, - get: external_dependency_parsers_0.shorthandGetter('font', font_local_var_shorthand_for), - enumerable: true, - configurable: true -}; -var height_export_definition; - -function height_local_fn_parse(v) { - if (String(v).toLowerCase() === 'auto') { - return 'auto'; - } - - if (String(v).toLowerCase() === 'inherit') { - return 'inherit'; - } - - return external_dependency_parsers_0.parseMeasurement(v); -} - -height_export_definition = { - set: function (v) { - this._setProperty('height', height_local_fn_parse(v)); - }, - get: function () { - return this.getPropertyValue('height'); - }, - enumerable: true, - configurable: true -}; -var left_export_definition; -left_export_definition = { - set: function (v) { - this._setProperty('left', external_dependency_parsers_0.parseMeasurement(v)); - }, - get: function () { - return this.getPropertyValue('left'); - }, - enumerable: true, - configurable: true -}; -var lightingColor_export_definition; -lightingColor_export_definition = { - set: function (v) { - this._setProperty('lighting-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('lighting-color'); - }, - enumerable: true, - configurable: true -}; -var margin_export_definition, margin_export_isValid, margin_export_parser; -var margin_local_var_TYPES = external_dependency_parsers_0.TYPES; - -var margin_local_var_isValid = function (v) { - if (v.toLowerCase() === 'auto') { - return true; - } - - var type = external_dependency_parsers_0.valueType(v); - return type === margin_local_var_TYPES.LENGTH || type === margin_local_var_TYPES.PERCENT || type === margin_local_var_TYPES.INTEGER && (v === '0' || v === 0); -}; - -var margin_local_var_parser = function (v) { - var V = v.toLowerCase(); - - if (V === 'auto') { - return V; - } - - return external_dependency_parsers_0.parseMeasurement(v); -}; - -var margin_local_var_mySetter = external_dependency_parsers_0.implicitSetter('margin', '', margin_local_var_isValid, margin_local_var_parser); -var margin_local_var_myGlobal = external_dependency_parsers_0.implicitSetter('margin', '', function () { - return true; -}, function (v) { - return v; -}); -margin_export_definition = { - set: function (v) { - if (typeof v === 'number') { - v = String(v); - } - - if (typeof v !== 'string') { - return; - } - - var V = v.toLowerCase(); - - switch (V) { - case 'inherit': - case 'initial': - case 'unset': - case '': - margin_local_var_myGlobal.call(this, V); - break; - - default: - margin_local_var_mySetter.call(this, v); - break; - } - }, - get: function () { - return this.getPropertyValue('margin'); - }, - enumerable: true, - configurable: true -}; -margin_export_isValid = margin_local_var_isValid; -margin_export_parser = margin_local_var_parser; -var marginBottom_export_definition; -marginBottom_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('margin', 'bottom', { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.isValid, { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.parser), - get: function () { - return this.getPropertyValue('margin-bottom'); - }, - enumerable: true, - configurable: true -}; -var marginLeft_export_definition; -marginLeft_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('margin', 'left', { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.isValid, { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.parser), - get: function () { - return this.getPropertyValue('margin-left'); - }, - enumerable: true, - configurable: true -}; -var marginRight_export_definition; -marginRight_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('margin', 'right', { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.isValid, { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.parser), - get: function () { - return this.getPropertyValue('margin-right'); - }, - enumerable: true, - configurable: true -}; -var marginTop_export_definition; -marginTop_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('margin', 'top', { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.isValid, { - definition: margin_export_definition, - isValid: margin_export_isValid, - parser: margin_export_parser - }.parser), - get: function () { - return this.getPropertyValue('margin-top'); - }, - enumerable: true, - configurable: true -}; -var opacity_export_definition; -opacity_export_definition = { - set: function (v) { - this._setProperty('opacity', external_dependency_parsers_0.parseNumber(v)); - }, - get: function () { - return this.getPropertyValue('opacity'); - }, - enumerable: true, - configurable: true -}; -var outlineColor_export_definition; -outlineColor_export_definition = { - set: function (v) { - this._setProperty('outline-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('outline-color'); - }, - enumerable: true, - configurable: true -}; -var padding_export_definition, padding_export_isValid, padding_export_parser; -var padding_local_var_TYPES = external_dependency_parsers_0.TYPES; - -var padding_local_var_isValid = function (v) { - var type = external_dependency_parsers_0.valueType(v); - return type === padding_local_var_TYPES.LENGTH || type === padding_local_var_TYPES.PERCENT || type === padding_local_var_TYPES.INTEGER && (v === '0' || v === 0); -}; - -var padding_local_var_parser = function (v) { - return external_dependency_parsers_0.parseMeasurement(v); -}; - -var padding_local_var_mySetter = external_dependency_parsers_0.implicitSetter('padding', '', padding_local_var_isValid, padding_local_var_parser); -var padding_local_var_myGlobal = external_dependency_parsers_0.implicitSetter('padding', '', function () { - return true; -}, function (v) { - return v; -}); -padding_export_definition = { - set: function (v) { - if (typeof v === 'number') { - v = String(v); - } - - if (typeof v !== 'string') { - return; - } - - var V = v.toLowerCase(); - - switch (V) { - case 'inherit': - case 'initial': - case 'unset': - case '': - padding_local_var_myGlobal.call(this, V); - break; - - default: - padding_local_var_mySetter.call(this, v); - break; - } - }, - get: function () { - return this.getPropertyValue('padding'); - }, - enumerable: true, - configurable: true -}; -padding_export_isValid = padding_local_var_isValid; -padding_export_parser = padding_local_var_parser; -var paddingBottom_export_definition; -paddingBottom_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('padding', 'bottom', { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.isValid, { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.parser), - get: function () { - return this.getPropertyValue('padding-bottom'); - }, - enumerable: true, - configurable: true -}; -var paddingLeft_export_definition; -paddingLeft_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('padding', 'left', { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.isValid, { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.parser), - get: function () { - return this.getPropertyValue('padding-left'); - }, - enumerable: true, - configurable: true -}; -var paddingRight_export_definition; -paddingRight_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('padding', 'right', { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.isValid, { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.parser), - get: function () { - return this.getPropertyValue('padding-right'); - }, - enumerable: true, - configurable: true -}; -var paddingTop_export_definition; -paddingTop_export_definition = { - set: external_dependency_parsers_0.subImplicitSetter('padding', 'top', { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.isValid, { - definition: padding_export_definition, - isValid: padding_export_isValid, - parser: padding_export_parser - }.parser), - get: function () { - return this.getPropertyValue('padding-top'); - }, - enumerable: true, - configurable: true -}; -var right_export_definition; -right_export_definition = { - set: function (v) { - this._setProperty('right', external_dependency_parsers_0.parseMeasurement(v)); - }, - get: function () { - return this.getPropertyValue('right'); - }, - enumerable: true, - configurable: true -}; -var stopColor_export_definition; -stopColor_export_definition = { - set: function (v) { - this._setProperty('stop-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('stop-color'); - }, - enumerable: true, - configurable: true -}; -var textLineThroughColor_export_definition; -textLineThroughColor_export_definition = { - set: function (v) { - this._setProperty('text-line-through-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('text-line-through-color'); - }, - enumerable: true, - configurable: true -}; -var textOverlineColor_export_definition; -textOverlineColor_export_definition = { - set: function (v) { - this._setProperty('text-overline-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('text-overline-color'); - }, - enumerable: true, - configurable: true -}; -var textUnderlineColor_export_definition; -textUnderlineColor_export_definition = { - set: function (v) { - this._setProperty('text-underline-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('text-underline-color'); - }, - enumerable: true, - configurable: true -}; -var top_export_definition; -top_export_definition = { - set: function (v) { - this._setProperty('top', external_dependency_parsers_0.parseMeasurement(v)); - }, - get: function () { - return this.getPropertyValue('top'); - }, - enumerable: true, - configurable: true -}; -var webkitBorderAfterColor_export_definition; -webkitBorderAfterColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-border-after-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-border-after-color'); - }, - enumerable: true, - configurable: true -}; -var webkitBorderBeforeColor_export_definition; -webkitBorderBeforeColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-border-before-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-border-before-color'); - }, - enumerable: true, - configurable: true -}; -var webkitBorderEndColor_export_definition; -webkitBorderEndColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-border-end-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-border-end-color'); - }, - enumerable: true, - configurable: true -}; -var webkitBorderStartColor_export_definition; -webkitBorderStartColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-border-start-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-border-start-color'); - }, - enumerable: true, - configurable: true -}; -var webkitColumnRuleColor_export_definition; -webkitColumnRuleColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-column-rule-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-column-rule-color'); - }, - enumerable: true, - configurable: true -}; -var webkitMatchNearestMailBlockquoteColor_export_definition; -webkitMatchNearestMailBlockquoteColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-match-nearest-mail-blockquote-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-match-nearest-mail-blockquote-color'); - }, - enumerable: true, - configurable: true -}; -var webkitTapHighlightColor_export_definition; -webkitTapHighlightColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-tap-highlight-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-tap-highlight-color'); - }, - enumerable: true, - configurable: true -}; -var webkitTextEmphasisColor_export_definition; -webkitTextEmphasisColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-text-emphasis-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-text-emphasis-color'); - }, - enumerable: true, - configurable: true -}; -var webkitTextFillColor_export_definition; -webkitTextFillColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-text-fill-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-text-fill-color'); - }, - enumerable: true, - configurable: true -}; -var webkitTextStrokeColor_export_definition; -webkitTextStrokeColor_export_definition = { - set: function (v) { - this._setProperty('-webkit-text-stroke-color', external_dependency_parsers_0.parseColor(v)); - }, - get: function () { - return this.getPropertyValue('-webkit-text-stroke-color'); - }, - enumerable: true, - configurable: true -}; -var width_export_definition; - -function width_local_fn_parse(v) { - if (String(v).toLowerCase() === 'auto') { - return 'auto'; - } - - if (String(v).toLowerCase() === 'inherit') { - return 'inherit'; - } - - return external_dependency_parsers_0.parseMeasurement(v); -} - -width_export_definition = { - set: function (v) { - this._setProperty('width', width_local_fn_parse(v)); - }, - get: function () { - return this.getPropertyValue('width'); - }, - enumerable: true, - configurable: true -}; - -module.exports = function (prototype) { - Object.defineProperties(prototype, { - azimuth: azimuth_export_definition, - backgroundColor: backgroundColor_export_definition, - "background-color": backgroundColor_export_definition, - backgroundImage: backgroundImage_export_definition, - "background-image": backgroundImage_export_definition, - backgroundRepeat: backgroundRepeat_export_definition, - "background-repeat": backgroundRepeat_export_definition, - backgroundAttachment: backgroundAttachment_export_definition, - "background-attachment": backgroundAttachment_export_definition, - backgroundPosition: backgroundPosition_export_definition, - "background-position": backgroundPosition_export_definition, - background: background_export_definition, - borderWidth: borderWidth_export_definition, - "border-width": borderWidth_export_definition, - borderStyle: borderStyle_export_definition, - "border-style": borderStyle_export_definition, - borderColor: borderColor_export_definition, - "border-color": borderColor_export_definition, - border: border_export_definition, - borderBottomWidth: borderBottomWidth_export_definition, - "border-bottom-width": borderBottomWidth_export_definition, - borderBottomStyle: borderBottomStyle_export_definition, - "border-bottom-style": borderBottomStyle_export_definition, - borderBottomColor: borderBottomColor_export_definition, - "border-bottom-color": borderBottomColor_export_definition, - borderBottom: borderBottom_export_definition, - "border-bottom": borderBottom_export_definition, - borderCollapse: borderCollapse_export_definition, - "border-collapse": borderCollapse_export_definition, - borderLeftWidth: borderLeftWidth_export_definition, - "border-left-width": borderLeftWidth_export_definition, - borderLeftStyle: borderLeftStyle_export_definition, - "border-left-style": borderLeftStyle_export_definition, - borderLeftColor: borderLeftColor_export_definition, - "border-left-color": borderLeftColor_export_definition, - borderLeft: borderLeft_export_definition, - "border-left": borderLeft_export_definition, - borderRightWidth: borderRightWidth_export_definition, - "border-right-width": borderRightWidth_export_definition, - borderRightStyle: borderRightStyle_export_definition, - "border-right-style": borderRightStyle_export_definition, - borderRightColor: borderRightColor_export_definition, - "border-right-color": borderRightColor_export_definition, - borderRight: borderRight_export_definition, - "border-right": borderRight_export_definition, - borderSpacing: borderSpacing_export_definition, - "border-spacing": borderSpacing_export_definition, - borderTopWidth: borderTopWidth_export_definition, - "border-top-width": borderTopWidth_export_definition, - borderTopStyle: borderTopStyle_export_definition, - "border-top-style": borderTopStyle_export_definition, - borderTopColor: borderTopColor_export_definition, - "border-top-color": borderTopColor_export_definition, - borderTop: borderTop_export_definition, - "border-top": borderTop_export_definition, - bottom: bottom_export_definition, - clear: clear_export_definition, - clip: clip_export_definition, - color: color_export_definition, - cssFloat: cssFloat_export_definition, - "css-float": cssFloat_export_definition, - flexGrow: flexGrow_export_definition, - "flex-grow": flexGrow_export_definition, - flexShrink: flexShrink_export_definition, - "flex-shrink": flexShrink_export_definition, - flexBasis: flexBasis_export_definition, - "flex-basis": flexBasis_export_definition, - flex: flex_export_definition, - float: float_export_definition, - floodColor: floodColor_export_definition, - "flood-color": floodColor_export_definition, - fontFamily: fontFamily_export_definition, - "font-family": fontFamily_export_definition, - fontSize: fontSize_export_definition, - "font-size": fontSize_export_definition, - fontStyle: fontStyle_export_definition, - "font-style": fontStyle_export_definition, - fontVariant: fontVariant_export_definition, - "font-variant": fontVariant_export_definition, - fontWeight: fontWeight_export_definition, - "font-weight": fontWeight_export_definition, - lineHeight: lineHeight_export_definition, - "line-height": lineHeight_export_definition, - font: font_export_definition, - height: height_export_definition, - left: left_export_definition, - lightingColor: lightingColor_export_definition, - "lighting-color": lightingColor_export_definition, - margin: margin_export_definition, - marginBottom: marginBottom_export_definition, - "margin-bottom": marginBottom_export_definition, - marginLeft: marginLeft_export_definition, - "margin-left": marginLeft_export_definition, - marginRight: marginRight_export_definition, - "margin-right": marginRight_export_definition, - marginTop: marginTop_export_definition, - "margin-top": marginTop_export_definition, - opacity: opacity_export_definition, - outlineColor: outlineColor_export_definition, - "outline-color": outlineColor_export_definition, - padding: padding_export_definition, - paddingBottom: paddingBottom_export_definition, - "padding-bottom": paddingBottom_export_definition, - paddingLeft: paddingLeft_export_definition, - "padding-left": paddingLeft_export_definition, - paddingRight: paddingRight_export_definition, - "padding-right": paddingRight_export_definition, - paddingTop: paddingTop_export_definition, - "padding-top": paddingTop_export_definition, - right: right_export_definition, - stopColor: stopColor_export_definition, - "stop-color": stopColor_export_definition, - textLineThroughColor: textLineThroughColor_export_definition, - "text-line-through-color": textLineThroughColor_export_definition, - textOverlineColor: textOverlineColor_export_definition, - "text-overline-color": textOverlineColor_export_definition, - textUnderlineColor: textUnderlineColor_export_definition, - "text-underline-color": textUnderlineColor_export_definition, - top: top_export_definition, - webkitBorderAfterColor: webkitBorderAfterColor_export_definition, - "webkit-border-after-color": webkitBorderAfterColor_export_definition, - webkitBorderBeforeColor: webkitBorderBeforeColor_export_definition, - "webkit-border-before-color": webkitBorderBeforeColor_export_definition, - webkitBorderEndColor: webkitBorderEndColor_export_definition, - "webkit-border-end-color": webkitBorderEndColor_export_definition, - webkitBorderStartColor: webkitBorderStartColor_export_definition, - "webkit-border-start-color": webkitBorderStartColor_export_definition, - webkitColumnRuleColor: webkitColumnRuleColor_export_definition, - "webkit-column-rule-color": webkitColumnRuleColor_export_definition, - webkitMatchNearestMailBlockquoteColor: webkitMatchNearestMailBlockquoteColor_export_definition, - "webkit-match-nearest-mail-blockquote-color": webkitMatchNearestMailBlockquoteColor_export_definition, - webkitTapHighlightColor: webkitTapHighlightColor_export_definition, - "webkit-tap-highlight-color": webkitTapHighlightColor_export_definition, - webkitTextEmphasisColor: webkitTextEmphasisColor_export_definition, - "webkit-text-emphasis-color": webkitTextEmphasisColor_export_definition, - webkitTextFillColor: webkitTextFillColor_export_definition, - "webkit-text-fill-color": webkitTextFillColor_export_definition, - webkitTextStrokeColor: webkitTextStrokeColor_export_definition, - "webkit-text-stroke-color": webkitTextStrokeColor_export_definition, - width: width_export_definition - }); -}; - - -/***/ }), - -/***/ 90515: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -const hueToRgb = (t1, t2, hue) => { - if (hue < 0) hue += 6; - if (hue >= 6) hue -= 6; - - if (hue < 1) return (t2 - t1) * hue + t1; - else if (hue < 3) return t2; - else if (hue < 4) return (t2 - t1) * (4 - hue) + t1; - else return t1; -}; - -// https://www.w3.org/TR/css-color-4/#hsl-to-rgb -exports.hslToRgb = (hue, sat, light) => { - const t2 = light <= 0.5 ? light * (sat + 1) : light + sat - light * sat; - const t1 = light * 2 - t2; - const r = hueToRgb(t1, t2, hue + 2); - const g = hueToRgb(t1, t2, hue); - const b = hueToRgb(t1, t2, hue - 2); - return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; -}; - - -/***/ }), - -/***/ 95721: -/***/ ((module) => { - -"use strict"; - - -module.exports = function getBasicPropertyDescriptor(name) { - return { - set: function(v) { - this._setProperty(name, v); - }, - get: function() { - return this.getPropertyValue(name); - }, - enumerable: true, - configurable: true, - }; -}; - - -/***/ }), - -/***/ 57775: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule), - MatcherList: (__nccwpck_require__(81519).MatcherList) -}; -///CommonJS - - -/** - * @constructor - * @see https://developer.mozilla.org/en/CSS/@-moz-document - */ -CSSOM.CSSDocumentRule = function CSSDocumentRule() { - CSSOM.CSSRule.call(this); - this.matcher = new CSSOM.MatcherList(); - this.cssRules = []; -}; - -CSSOM.CSSDocumentRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSDocumentRule.prototype.constructor = CSSOM.CSSDocumentRule; -CSSOM.CSSDocumentRule.prototype.type = 10; -//FIXME -//CSSOM.CSSDocumentRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSDocumentRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -Object.defineProperty(CSSOM.CSSDocumentRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@-moz-document " + this.matcher.matcherText + " {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSDocumentRule = CSSOM.CSSDocumentRule; -///CommonJS - - -/***/ }), - -/***/ 934: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), - CSSRule: (__nccwpck_require__(24994).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#css-font-face-rule - */ -CSSOM.CSSFontFaceRule = function CSSFontFaceRule() { - CSSOM.CSSRule.call(this); - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSFontFaceRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSFontFaceRule.prototype.constructor = CSSOM.CSSFontFaceRule; -CSSOM.CSSFontFaceRule.prototype.type = 5; -//FIXME -//CSSOM.CSSFontFaceRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSFontFaceRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSFontFaceRule.cpp -Object.defineProperty(CSSOM.CSSFontFaceRule.prototype, "cssText", { - get: function() { - return "@font-face {" + this.style.cssText + "}"; - } -}); - - -//.CommonJS -exports.CSSFontFaceRule = CSSOM.CSSFontFaceRule; -///CommonJS - - -/***/ }), - -/***/ 80576: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/shadow-dom/#host-at-rule - */ -CSSOM.CSSHostRule = function CSSHostRule() { - CSSOM.CSSRule.call(this); - this.cssRules = []; -}; - -CSSOM.CSSHostRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSHostRule.prototype.constructor = CSSOM.CSSHostRule; -CSSOM.CSSHostRule.prototype.type = 1001; -//FIXME -//CSSOM.CSSHostRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSHostRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -Object.defineProperty(CSSOM.CSSHostRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@host {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSHostRule = CSSOM.CSSHostRule; -///CommonJS - - -/***/ }), - -/***/ 15339: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule), - CSSStyleSheet: (__nccwpck_require__(28050).CSSStyleSheet), - MediaList: (__nccwpck_require__(77326).MediaList) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssimportrule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSImportRule - */ -CSSOM.CSSImportRule = function CSSImportRule() { - CSSOM.CSSRule.call(this); - this.href = ""; - this.media = new CSSOM.MediaList(); - this.styleSheet = new CSSOM.CSSStyleSheet(); -}; - -CSSOM.CSSImportRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSImportRule.prototype.constructor = CSSOM.CSSImportRule; -CSSOM.CSSImportRule.prototype.type = 3; - -Object.defineProperty(CSSOM.CSSImportRule.prototype, "cssText", { - get: function() { - var mediaText = this.media.mediaText; - return "@import url(" + this.href + ")" + (mediaText ? " " + mediaText : "") + ";"; - }, - set: function(cssText) { - var i = 0; - - /** - * @import url(partial.css) screen, handheld; - * || | - * after-import media - * | - * url - */ - var state = ''; - - var buffer = ''; - var index; - for (var character; (character = cssText.charAt(i)); i++) { - - switch (character) { - case ' ': - case '\t': - case '\r': - case '\n': - case '\f': - if (state === 'after-import') { - state = 'url'; - } else { - buffer += character; - } - break; - - case '@': - if (!state && cssText.indexOf('@import', i) === i) { - state = 'after-import'; - i += 'import'.length; - buffer = ''; - } - break; - - case 'u': - if (state === 'url' && cssText.indexOf('url(', i) === i) { - index = cssText.indexOf(')', i + 1); - if (index === -1) { - throw i + ': ")" not found'; - } - i += 'url('.length; - var url = cssText.slice(i, index); - if (url[0] === url[url.length - 1]) { - if (url[0] === '"' || url[0] === "'") { - url = url.slice(1, -1); - } - } - this.href = url; - i = index; - state = 'media'; - } - break; - - case '"': - if (state === 'url') { - index = cssText.indexOf('"', i + 1); - if (!index) { - throw i + ": '\"' not found"; - } - this.href = cssText.slice(i + 1, index); - i = index; - state = 'media'; - } - break; - - case "'": - if (state === 'url') { - index = cssText.indexOf("'", i + 1); - if (!index) { - throw i + ': "\'" not found'; - } - this.href = cssText.slice(i + 1, index); - i = index; - state = 'media'; - } - break; - - case ';': - if (state === 'media') { - if (buffer) { - this.media.mediaText = buffer.trim(); - } - } - break; - - default: - if (state === 'media') { - buffer += character; - } - break; - } - } - } -}); - - -//.CommonJS -exports.CSSImportRule = CSSOM.CSSImportRule; -///CommonJS - - -/***/ }), - -/***/ 8308: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule), - CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframeRule - */ -CSSOM.CSSKeyframeRule = function CSSKeyframeRule() { - CSSOM.CSSRule.call(this); - this.keyText = ''; - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSKeyframeRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSKeyframeRule.prototype.constructor = CSSOM.CSSKeyframeRule; -CSSOM.CSSKeyframeRule.prototype.type = 9; -//FIXME -//CSSOM.CSSKeyframeRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSKeyframeRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframeRule.cpp -Object.defineProperty(CSSOM.CSSKeyframeRule.prototype, "cssText", { - get: function() { - return this.keyText + " {" + this.style.cssText + "} "; - } -}); - - -//.CommonJS -exports.CSSKeyframeRule = CSSOM.CSSKeyframeRule; -///CommonJS - - -/***/ }), - -/***/ 53702: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/css3-animations/#DOM-CSSKeyframesRule - */ -CSSOM.CSSKeyframesRule = function CSSKeyframesRule() { - CSSOM.CSSRule.call(this); - this.name = ''; - this.cssRules = []; -}; - -CSSOM.CSSKeyframesRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSKeyframesRule.prototype.constructor = CSSOM.CSSKeyframesRule; -CSSOM.CSSKeyframesRule.prototype.type = 8; -//FIXME -//CSSOM.CSSKeyframesRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSKeyframesRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://www.opensource.apple.com/source/WebCore/WebCore-955.66.1/css/WebKitCSSKeyframesRule.cpp -Object.defineProperty(CSSOM.CSSKeyframesRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(" " + this.cssRules[i].cssText); - } - return "@" + (this._vendorPrefix || '') + "keyframes " + this.name + " { \n" + cssTexts.join("\n") + "\n}"; - } -}); - - -//.CommonJS -exports.CSSKeyframesRule = CSSOM.CSSKeyframesRule; -///CommonJS - - -/***/ }), - -/***/ 60365: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule), - MediaList: (__nccwpck_require__(77326).MediaList) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssmediarule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSMediaRule - */ -CSSOM.CSSMediaRule = function CSSMediaRule() { - CSSOM.CSSRule.call(this); - this.media = new CSSOM.MediaList(); - this.cssRules = []; -}; - -CSSOM.CSSMediaRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSMediaRule.prototype.constructor = CSSOM.CSSMediaRule; -CSSOM.CSSMediaRule.prototype.type = 4; -//FIXME -//CSSOM.CSSMediaRule.prototype.insertRule = CSSStyleSheet.prototype.insertRule; -//CSSOM.CSSMediaRule.prototype.deleteRule = CSSStyleSheet.prototype.deleteRule; - -// http://opensource.apple.com/source/WebCore/WebCore-658.28/css/CSSMediaRule.cpp -Object.defineProperty(CSSOM.CSSMediaRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - for (var i=0, length=this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - return "@media " + this.media.mediaText + " {" + cssTexts.join("") + "}"; - } -}); - - -//.CommonJS -exports.CSSMediaRule = CSSOM.CSSMediaRule; -///CommonJS - - -/***/ }), - -/***/ 24994: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-cssrule-interface - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule - */ -CSSOM.CSSRule = function CSSRule() { - this.parentRule = null; - this.parentStyleSheet = null; -}; - -CSSOM.CSSRule.UNKNOWN_RULE = 0; // obsolete -CSSOM.CSSRule.STYLE_RULE = 1; -CSSOM.CSSRule.CHARSET_RULE = 2; // obsolete -CSSOM.CSSRule.IMPORT_RULE = 3; -CSSOM.CSSRule.MEDIA_RULE = 4; -CSSOM.CSSRule.FONT_FACE_RULE = 5; -CSSOM.CSSRule.PAGE_RULE = 6; -CSSOM.CSSRule.KEYFRAMES_RULE = 7; -CSSOM.CSSRule.KEYFRAME_RULE = 8; -CSSOM.CSSRule.MARGIN_RULE = 9; -CSSOM.CSSRule.NAMESPACE_RULE = 10; -CSSOM.CSSRule.COUNTER_STYLE_RULE = 11; -CSSOM.CSSRule.SUPPORTS_RULE = 12; -CSSOM.CSSRule.DOCUMENT_RULE = 13; -CSSOM.CSSRule.FONT_FEATURE_VALUES_RULE = 14; -CSSOM.CSSRule.VIEWPORT_RULE = 15; -CSSOM.CSSRule.REGION_STYLE_RULE = 16; - - -CSSOM.CSSRule.prototype = { - constructor: CSSOM.CSSRule - //FIXME -}; - - -//.CommonJS -exports.CSSRule = CSSOM.CSSRule; -///CommonJS - - -/***/ }), - -/***/ 21449: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration - */ -CSSOM.CSSStyleDeclaration = function CSSStyleDeclaration(){ - this.length = 0; - this.parentRule = null; - - // NON-STANDARD - this._importants = {}; -}; - - -CSSOM.CSSStyleDeclaration.prototype = { - - constructor: CSSOM.CSSStyleDeclaration, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-getPropertyValue - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set. - */ - getPropertyValue: function(name) { - return this[name] || ""; - }, - - /** - * - * @param {string} name - * @param {string} value - * @param {string} [priority=null] "important" or null - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-setProperty - */ - setProperty: function(name, value, priority) { - if (this[name]) { - // Property already exist. Overwrite it. - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - this[this.length] = name; - this.length++; - } - } else { - // New property. - this[this.length] = name; - this.length++; - } - this[name] = value + ""; - this._importants[name] = priority; - }, - - /** - * - * @param {string} name - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration-removeProperty - * @return {string} the value of the property if it has been explicitly set for this declaration block. - * Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property. - */ - removeProperty: function(name) { - if (!(name in this)) { - return ""; - } - var index = Array.prototype.indexOf.call(this, name); - if (index < 0) { - return ""; - } - var prevValue = this[name]; - this[name] = ""; - - // That's what WebKit and Opera do - Array.prototype.splice.call(this, index, 1); - - // That's what Firefox does - //this[index] = "" - - return prevValue; - }, - - getPropertyCSSValue: function() { - //FIXME - }, - - /** - * - * @param {String} name - */ - getPropertyPriority: function(name) { - return this._importants[name] || ""; - }, - - - /** - * element.style.overflow = "auto" - * element.style.getPropertyShorthand("overflow-x") - * -> "overflow" - */ - getPropertyShorthand: function() { - //FIXME - }, - - isPropertyImplicit: function() { - //FIXME - }, - - // Doesn't work in IE < 9 - get cssText(){ - var properties = []; - for (var i=0, length=this.length; i < length; ++i) { - var name = this[i]; - var value = this.getPropertyValue(name); - var priority = this.getPropertyPriority(name); - if (priority) { - priority = " !" + priority; - } - properties[i] = name + ": " + value + priority + ";"; - } - return properties.join(" "); - }, - - set cssText(text){ - var i, name; - for (i = this.length; i--;) { - name = this[i]; - this[name] = ""; - } - Array.prototype.splice.call(this, 0, this.length); - this._importants = {}; - - var dummyRule = CSSOM.parse('#bogus{' + text + '}').cssRules[0].style; - var length = dummyRule.length; - for (i = 0; i < length; ++i) { - name = dummyRule[i]; - this.setProperty(dummyRule[i], dummyRule.getPropertyValue(name), dummyRule.getPropertyPriority(name)); - } - } -}; - - -//.CommonJS -exports.CSSStyleDeclaration = CSSOM.CSSStyleDeclaration; -CSSOM.parse = (__nccwpck_require__(90268).parse); // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleDeclaration.js -///CommonJS - - -/***/ }), - -/***/ 57732: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), - CSSRule: (__nccwpck_require__(24994).CSSRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#cssstylerule - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleRule - */ -CSSOM.CSSStyleRule = function CSSStyleRule() { - CSSOM.CSSRule.call(this); - this.selectorText = ""; - this.style = new CSSOM.CSSStyleDeclaration(); - this.style.parentRule = this; -}; - -CSSOM.CSSStyleRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSStyleRule.prototype.constructor = CSSOM.CSSStyleRule; -CSSOM.CSSStyleRule.prototype.type = 1; - -Object.defineProperty(CSSOM.CSSStyleRule.prototype, "cssText", { - get: function() { - var text; - if (this.selectorText) { - text = this.selectorText + " {" + this.style.cssText + "}"; - } else { - text = ""; - } - return text; - }, - set: function(cssText) { - var rule = CSSOM.CSSStyleRule.parse(cssText); - this.style = rule.style; - this.selectorText = rule.selectorText; - } -}); - - -/** - * NON-STANDARD - * lightweight version of parse.js. - * @param {string} ruleText - * @return CSSStyleRule - */ -CSSOM.CSSStyleRule.parse = function(ruleText) { - var i = 0; - var state = "selector"; - var index; - var j = i; - var buffer = ""; - - var SIGNIFICANT_WHITESPACE = { - "selector": true, - "value": true - }; - - var styleRule = new CSSOM.CSSStyleRule(); - var name, priority=""; - - for (var character; (character = ruleText.charAt(i)); i++) { - - switch (character) { - - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - if (SIGNIFICANT_WHITESPACE[state]) { - // Squash 2 or more white-spaces in the row into 1 - switch (ruleText.charAt(i - 1)) { - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - break; - default: - buffer += " "; - break; - } - } - break; - - // String - case '"': - j = i + 1; - index = ruleText.indexOf('"', j) + 1; - if (!index) { - throw '" is missing'; - } - buffer += ruleText.slice(i, index); - i = index - 1; - break; - - case "'": - j = i + 1; - index = ruleText.indexOf("'", j) + 1; - if (!index) { - throw "' is missing"; - } - buffer += ruleText.slice(i, index); - i = index - 1; - break; - - // Comment - case "/": - if (ruleText.charAt(i + 1) === "*") { - i += 2; - index = ruleText.indexOf("*/", i); - if (index === -1) { - throw new SyntaxError("Missing */"); - } else { - i = index + 1; - } - } else { - buffer += character; - } - break; - - case "{": - if (state === "selector") { - styleRule.selectorText = buffer.trim(); - buffer = ""; - state = "name"; - } - break; - - case ":": - if (state === "name") { - name = buffer.trim(); - buffer = ""; - state = "value"; - } else { - buffer += character; - } - break; - - case "!": - if (state === "value" && ruleText.indexOf("!important", i) === i) { - priority = "important"; - i += "important".length; - } else { - buffer += character; - } - break; - - case ";": - if (state === "value") { - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - state = "name"; - } else { - buffer += character; - } - break; - - case "}": - if (state === "value") { - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - } else if (state === "name") { - break; - } else { - buffer += character; - } - state = "selector"; - break; - - default: - buffer += character; - break; - - } - } - - return styleRule; - -}; - - -//.CommonJS -exports.CSSStyleRule = CSSOM.CSSStyleRule; -///CommonJS - - -/***/ }), - -/***/ 28050: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - StyleSheet: (__nccwpck_require__(98847).StyleSheet), - CSSStyleRule: (__nccwpck_require__(57732).CSSStyleRule) -}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet - */ -CSSOM.CSSStyleSheet = function CSSStyleSheet() { - CSSOM.StyleSheet.call(this); - this.cssRules = []; -}; - - -CSSOM.CSSStyleSheet.prototype = new CSSOM.StyleSheet(); -CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet; - - -/** - * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade. - * - * sheet = new Sheet("body {margin: 0}") - * sheet.toString() - * -> "body{margin:0;}" - * sheet.insertRule("img {border: none}", 0) - * -> 0 - * sheet.toString() - * -> "img{border:none;}body{margin:0;}" - * - * @param {string} rule - * @param {number} index - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule - * @return {number} The index within the style sheet's rule collection of the newly inserted rule. - */ -CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) { - if (index < 0 || index > this.cssRules.length) { - throw new RangeError("INDEX_SIZE_ERR"); - } - var cssRule = CSSOM.parse(rule).cssRules[0]; - cssRule.parentStyleSheet = this; - this.cssRules.splice(index, 0, cssRule); - return index; -}; - - -/** - * Used to delete a rule from the style sheet. - * - * sheet = new Sheet("img{border:none} body{margin:0}") - * sheet.toString() - * -> "img{border:none;}body{margin:0;}" - * sheet.deleteRule(0) - * sheet.toString() - * -> "body{margin:0;}" - * - * @param {number} index within the style sheet's rule list of the rule to remove. - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule - */ -CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) { - if (index < 0 || index >= this.cssRules.length) { - throw new RangeError("INDEX_SIZE_ERR"); - } - this.cssRules.splice(index, 1); -}; - - -/** - * NON-STANDARD - * @return {string} serialize stylesheet - */ -CSSOM.CSSStyleSheet.prototype.toString = function() { - var result = ""; - var rules = this.cssRules; - for (var i=0; i { - -//.CommonJS -var CSSOM = { - CSSRule: (__nccwpck_require__(24994).CSSRule), -}; -///CommonJS - - -/** - * @constructor - * @see https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface - */ -CSSOM.CSSSupportsRule = function CSSSupportsRule() { - CSSOM.CSSRule.call(this); - this.conditionText = ''; - this.cssRules = []; -}; - -CSSOM.CSSSupportsRule.prototype = new CSSOM.CSSRule(); -CSSOM.CSSSupportsRule.prototype.constructor = CSSOM.CSSSupportsRule; -CSSOM.CSSSupportsRule.prototype.type = 12; - -Object.defineProperty(CSSOM.CSSSupportsRule.prototype, "cssText", { - get: function() { - var cssTexts = []; - - for (var i = 0, length = this.cssRules.length; i < length; i++) { - cssTexts.push(this.cssRules[i].cssText); - } - - return "@supports " + this.conditionText + " {" + cssTexts.join("") + "}"; - } -}); - -//.CommonJS -exports.CSSSupportsRule = CSSOM.CSSSupportsRule; -///CommonJS - - -/***/ }), - -/***/ 99880: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue - * - * TODO: add if needed - */ -CSSOM.CSSValue = function CSSValue() { -}; - -CSSOM.CSSValue.prototype = { - constructor: CSSOM.CSSValue, - - // @see: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSValue - set cssText(text) { - var name = this._getConstructorName(); - - throw new Error('DOMException: property "cssText" of "' + name + '" is readonly and can not be replaced with "' + text + '"!'); - }, - - get cssText() { - var name = this._getConstructorName(); - - throw new Error('getter "cssText" of "' + name + '" is not implemented!'); - }, - - _getConstructorName: function() { - var s = this.constructor.toString(), - c = s.match(/function\s([^\(]+)/), - name = c[1]; - - return name; - } -}; - - -//.CommonJS -exports.CSSValue = CSSOM.CSSValue; -///CommonJS - - -/***/ }), - -/***/ 56356: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSValue: (__nccwpck_require__(99880).CSSValue) -}; -///CommonJS - - -/** - * @constructor - * @see http://msdn.microsoft.com/en-us/library/ms537634(v=vs.85).aspx - * - */ -CSSOM.CSSValueExpression = function CSSValueExpression(token, idx) { - this._token = token; - this._idx = idx; -}; - -CSSOM.CSSValueExpression.prototype = new CSSOM.CSSValue(); -CSSOM.CSSValueExpression.prototype.constructor = CSSOM.CSSValueExpression; - -/** - * parse css expression() value - * - * @return {Object} - * - error: - * or - * - idx: - * - expression: - * - * Example: - * - * .selector { - * zoom: expression(documentElement.clientWidth > 1000 ? '1000px' : 'auto'); - * } - */ -CSSOM.CSSValueExpression.prototype.parse = function() { - var token = this._token, - idx = this._idx; - - var character = '', - expression = '', - error = '', - info, - paren = []; - - - for (; ; ++idx) { - character = token.charAt(idx); - - // end of token - if (character === '') { - error = 'css expression error: unfinished expression!'; - break; - } - - switch(character) { - case '(': - paren.push(character); - expression += character; - break; - - case ')': - paren.pop(character); - expression += character; - break; - - case '/': - if ((info = this._parseJSComment(token, idx))) { // comment? - if (info.error) { - error = 'css expression error: unfinished comment in expression!'; - } else { - idx = info.idx; - // ignore the comment - } - } else if ((info = this._parseJSRexExp(token, idx))) { // regexp - idx = info.idx; - expression += info.text; - } else { // other - expression += character; - } - break; - - case "'": - case '"': - info = this._parseJSString(token, idx, character); - if (info) { // string - idx = info.idx; - expression += info.text; - } else { - expression += character; - } - break; - - default: - expression += character; - break; - } - - if (error) { - break; - } - - // end of expression - if (paren.length === 0) { - break; - } - } - - var ret; - if (error) { - ret = { - error: error - }; - } else { - ret = { - idx: idx, - expression: expression - }; - } - - return ret; -}; - - -/** - * - * @return {Object|false} - * - idx: - * - text: - * or - * - error: - * or - * false - * - */ -CSSOM.CSSValueExpression.prototype._parseJSComment = function(token, idx) { - var nextChar = token.charAt(idx + 1), - text; - - if (nextChar === '/' || nextChar === '*') { - var startIdx = idx, - endIdx, - commentEndChar; - - if (nextChar === '/') { // line comment - commentEndChar = '\n'; - } else if (nextChar === '*') { // block comment - commentEndChar = '*/'; - } - - endIdx = token.indexOf(commentEndChar, startIdx + 1 + 1); - if (endIdx !== -1) { - endIdx = endIdx + commentEndChar.length - 1; - text = token.substring(idx, endIdx + 1); - return { - idx: endIdx, - text: text - }; - } else { - var error = 'css expression error: unfinished comment in expression!'; - return { - error: error - }; - } - } else { - return false; - } -}; - - -/** - * - * @return {Object|false} - * - idx: - * - text: - * or - * false - * - */ -CSSOM.CSSValueExpression.prototype._parseJSString = function(token, idx, sep) { - var endIdx = this._findMatchedIdx(token, idx, sep), - text; - - if (endIdx === -1) { - return false; - } else { - text = token.substring(idx, endIdx + sep.length); - - return { - idx: endIdx, - text: text - }; - } -}; - - -/** - * parse regexp in css expression - * - * @return {Object|false} - * - idx: - * - regExp: - * or - * false - */ - -/* - -all legal RegExp - -/a/ -(/a/) -[/a/] -[12, /a/] - -!/a/ - -+/a/ --/a/ -* /a/ -/ /a/ -%/a/ - -===/a/ -!==/a/ -==/a/ -!=/a/ ->/a/ ->=/a/ ->/a/ ->>>/a/ - -&&/a/ -||/a/ -?/a/ -=/a/ -,/a/ - - delete /a/ - in /a/ -instanceof /a/ - new /a/ - typeof /a/ - void /a/ - -*/ -CSSOM.CSSValueExpression.prototype._parseJSRexExp = function(token, idx) { - var before = token.substring(0, idx).replace(/\s+$/, ""), - legalRegx = [ - /^$/, - /\($/, - /\[$/, - /\!$/, - /\+$/, - /\-$/, - /\*$/, - /\/\s+/, - /\%$/, - /\=$/, - /\>$/, - /<$/, - /\&$/, - /\|$/, - /\^$/, - /\~$/, - /\?$/, - /\,$/, - /delete$/, - /in$/, - /instanceof$/, - /new$/, - /typeof$/, - /void$/ - ]; - - var isLegal = legalRegx.some(function(reg) { - return reg.test(before); - }); - - if (!isLegal) { - return false; - } else { - var sep = '/'; - - // same logic as string - return this._parseJSString(token, idx, sep); - } -}; - - -/** - * - * find next sep(same line) index in `token` - * - * @return {Number} - * - */ -CSSOM.CSSValueExpression.prototype._findMatchedIdx = function(token, idx, sep) { - var startIdx = idx, - endIdx; - - var NOT_FOUND = -1; - - while(true) { - endIdx = token.indexOf(sep, startIdx + 1); - - if (endIdx === -1) { // not found - endIdx = NOT_FOUND; - break; - } else { - var text = token.substring(idx + 1, endIdx), - matched = text.match(/\\+$/); - if (!matched || matched[0] % 2 === 0) { // not escaped - break; - } else { - startIdx = endIdx; - } - } - } - - // boundary must be in the same line(js sting or regexp) - var nextNewLineIdx = token.indexOf('\n', idx + 1); - if (nextNewLineIdx < endIdx) { - endIdx = NOT_FOUND; - } - - - return endIdx; -}; - - - - -//.CommonJS -exports.CSSValueExpression = CSSOM.CSSValueExpression; -///CommonJS - - -/***/ }), - -/***/ 81519: -/***/ ((__unused_webpack_module, exports) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see https://developer.mozilla.org/en/CSS/@-moz-document - */ -CSSOM.MatcherList = function MatcherList(){ - this.length = 0; -}; - -CSSOM.MatcherList.prototype = { - - constructor: CSSOM.MatcherList, - - /** - * @return {string} - */ - get matcherText() { - return Array.prototype.join.call(this, ", "); - }, - - /** - * @param {string} value - */ - set matcherText(value) { - // just a temporary solution, actually it may be wrong by just split the value with ',', because a url can include ','. - var values = value.split(","); - var length = this.length = values.length; - for (var i=0; i { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-medialist-interface - */ -CSSOM.MediaList = function MediaList(){ - this.length = 0; -}; - -CSSOM.MediaList.prototype = { - - constructor: CSSOM.MediaList, - - /** - * @return {string} - */ - get mediaText() { - return Array.prototype.join.call(this, ", "); - }, - - /** - * @param {string} value - */ - set mediaText(value) { - var values = value.split(","); - var length = this.length = values.length; - for (var i=0; i { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @constructor - * @see http://dev.w3.org/csswg/cssom/#the-stylesheet-interface - */ -CSSOM.StyleSheet = function StyleSheet() { - this.parentStyleSheet = null; -}; - - -//.CommonJS -exports.StyleSheet = CSSOM.StyleSheet; -///CommonJS - - -/***/ }), - -/***/ 13833: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = { - CSSStyleSheet: (__nccwpck_require__(28050).CSSStyleSheet), - CSSStyleRule: (__nccwpck_require__(57732).CSSStyleRule), - CSSMediaRule: (__nccwpck_require__(60365).CSSMediaRule), - CSSSupportsRule: (__nccwpck_require__(92243).CSSSupportsRule), - CSSStyleDeclaration: (__nccwpck_require__(21449).CSSStyleDeclaration), - CSSKeyframeRule: (__nccwpck_require__(8308).CSSKeyframeRule), - CSSKeyframesRule: (__nccwpck_require__(53702).CSSKeyframesRule) -}; -///CommonJS - - -/** - * Produces a deep copy of stylesheet — the instance variables of stylesheet are copied recursively. - * @param {CSSStyleSheet|CSSOM.CSSStyleSheet} stylesheet - * @nosideeffects - * @return {CSSOM.CSSStyleSheet} - */ -CSSOM.clone = function clone(stylesheet) { - - var cloned = new CSSOM.CSSStyleSheet(); - - var rules = stylesheet.cssRules; - if (!rules) { - return cloned; - } - - var RULE_TYPES = { - 1: CSSOM.CSSStyleRule, - 4: CSSOM.CSSMediaRule, - //3: CSSOM.CSSImportRule, - //5: CSSOM.CSSFontFaceRule, - //6: CSSOM.CSSPageRule, - 8: CSSOM.CSSKeyframesRule, - 9: CSSOM.CSSKeyframeRule, - 12: CSSOM.CSSSupportsRule - }; - - for (var i=0, rulesLength=rules.length; i < rulesLength; i++) { - var rule = rules[i]; - var ruleClone = cloned.cssRules[i] = new RULE_TYPES[rule.type](); - - var style = rule.style; - if (style) { - var styleClone = ruleClone.style = new CSSOM.CSSStyleDeclaration(); - for (var j=0, styleLength=style.length; j < styleLength; j++) { - var name = styleClone[j] = style[j]; - styleClone[name] = style[name]; - styleClone._importants[name] = style.getPropertyPriority(name); - } - styleClone.length = style.length; - } - - if (rule.hasOwnProperty('keyText')) { - ruleClone.keyText = rule.keyText; - } - - if (rule.hasOwnProperty('selectorText')) { - ruleClone.selectorText = rule.selectorText; - } - - if (rule.hasOwnProperty('mediaText')) { - ruleClone.mediaText = rule.mediaText; - } - - if (rule.hasOwnProperty('conditionText')) { - ruleClone.conditionText = rule.conditionText; - } - - if (rule.hasOwnProperty('cssRules')) { - ruleClone.cssRules = clone(rule).cssRules; - } - } - - return cloned; - -}; - -//.CommonJS -exports.clone = CSSOM.clone; -///CommonJS - - -/***/ }), - -/***/ 8331: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -exports.CSSStyleDeclaration = __nccwpck_require__(21449).CSSStyleDeclaration; -exports.CSSRule = __nccwpck_require__(24994).CSSRule; -exports.CSSStyleRule = __nccwpck_require__(57732).CSSStyleRule; -exports.MediaList = __nccwpck_require__(77326).MediaList; -exports.CSSMediaRule = __nccwpck_require__(60365).CSSMediaRule; -exports.CSSSupportsRule = __nccwpck_require__(92243).CSSSupportsRule; -exports.CSSImportRule = __nccwpck_require__(15339).CSSImportRule; -exports.CSSFontFaceRule = __nccwpck_require__(934).CSSFontFaceRule; -exports.CSSHostRule = __nccwpck_require__(80576).CSSHostRule; -exports.StyleSheet = __nccwpck_require__(98847).StyleSheet; -exports.CSSStyleSheet = __nccwpck_require__(28050).CSSStyleSheet; -exports.CSSKeyframesRule = __nccwpck_require__(53702).CSSKeyframesRule; -exports.CSSKeyframeRule = __nccwpck_require__(8308).CSSKeyframeRule; -exports.MatcherList = __nccwpck_require__(81519).MatcherList; -exports.CSSDocumentRule = __nccwpck_require__(57775).CSSDocumentRule; -exports.CSSValue = __nccwpck_require__(99880).CSSValue; -exports.CSSValueExpression = __nccwpck_require__(56356).CSSValueExpression; -exports.parse = __nccwpck_require__(90268).parse; -exports.clone = __nccwpck_require__(13833).clone; - - -/***/ }), - -/***/ 90268: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -//.CommonJS -var CSSOM = {}; -///CommonJS - - -/** - * @param {string} token - */ -CSSOM.parse = function parse(token) { - - var i = 0; - - /** - "before-selector" or - "selector" or - "atRule" or - "atBlock" or - "conditionBlock" or - "before-name" or - "name" or - "before-value" or - "value" - */ - var state = "before-selector"; - - var index; - var buffer = ""; - var valueParenthesisDepth = 0; - - var SIGNIFICANT_WHITESPACE = { - "selector": true, - "value": true, - "value-parenthesis": true, - "atRule": true, - "importRule-begin": true, - "importRule": true, - "atBlock": true, - "conditionBlock": true, - 'documentRule-begin': true - }; - - var styleSheet = new CSSOM.CSSStyleSheet(); - - // @type CSSStyleSheet|CSSMediaRule|CSSSupportsRule|CSSFontFaceRule|CSSKeyframesRule|CSSDocumentRule - var currentScope = styleSheet; - - // @type CSSMediaRule|CSSSupportsRule|CSSKeyframesRule|CSSDocumentRule - var parentRule; - - var ancestorRules = []; - var hasAncestors = false; - var prevScope; - - var name, priority="", styleRule, mediaRule, supportsRule, importRule, fontFaceRule, keyframesRule, documentRule, hostRule; - - var atKeyframesRegExp = /@(-(?:\w+-)+)?keyframes/g; - - var parseError = function(message) { - var lines = token.substring(0, i).split('\n'); - var lineCount = lines.length; - var charCount = lines.pop().length + 1; - var error = new Error(message + ' (line ' + lineCount + ', char ' + charCount + ')'); - error.line = lineCount; - /* jshint sub : true */ - error['char'] = charCount; - error.styleSheet = styleSheet; - throw error; - }; - - for (var character; (character = token.charAt(i)); i++) { - - switch (character) { - - case " ": - case "\t": - case "\r": - case "\n": - case "\f": - if (SIGNIFICANT_WHITESPACE[state]) { - buffer += character; - } - break; - - // String - case '"': - index = i + 1; - do { - index = token.indexOf('"', index) + 1; - if (!index) { - parseError('Unmatched "'); - } - } while (token[index - 2] === '\\'); - buffer += token.slice(i, index); - i = index - 1; - switch (state) { - case 'before-value': - state = 'value'; - break; - case 'importRule-begin': - state = 'importRule'; - break; - } - break; - - case "'": - index = i + 1; - do { - index = token.indexOf("'", index) + 1; - if (!index) { - parseError("Unmatched '"); - } - } while (token[index - 2] === '\\'); - buffer += token.slice(i, index); - i = index - 1; - switch (state) { - case 'before-value': - state = 'value'; - break; - case 'importRule-begin': - state = 'importRule'; - break; - } - break; - - // Comment - case "/": - if (token.charAt(i + 1) === "*") { - i += 2; - index = token.indexOf("*/", i); - if (index === -1) { - parseError("Missing */"); - } else { - i = index + 1; - } - } else { - buffer += character; - } - if (state === "importRule-begin") { - buffer += " "; - state = "importRule"; - } - break; - - // At-rule - case "@": - if (token.indexOf("@-moz-document", i) === i) { - state = "documentRule-begin"; - documentRule = new CSSOM.CSSDocumentRule(); - documentRule.__starts = i; - i += "-moz-document".length; - buffer = ""; - break; - } else if (token.indexOf("@media", i) === i) { - state = "atBlock"; - mediaRule = new CSSOM.CSSMediaRule(); - mediaRule.__starts = i; - i += "media".length; - buffer = ""; - break; - } else if (token.indexOf("@supports", i) === i) { - state = "conditionBlock"; - supportsRule = new CSSOM.CSSSupportsRule(); - supportsRule.__starts = i; - i += "supports".length; - buffer = ""; - break; - } else if (token.indexOf("@host", i) === i) { - state = "hostRule-begin"; - i += "host".length; - hostRule = new CSSOM.CSSHostRule(); - hostRule.__starts = i; - buffer = ""; - break; - } else if (token.indexOf("@import", i) === i) { - state = "importRule-begin"; - i += "import".length; - buffer += "@import"; - break; - } else if (token.indexOf("@font-face", i) === i) { - state = "fontFaceRule-begin"; - i += "font-face".length; - fontFaceRule = new CSSOM.CSSFontFaceRule(); - fontFaceRule.__starts = i; - buffer = ""; - break; - } else { - atKeyframesRegExp.lastIndex = i; - var matchKeyframes = atKeyframesRegExp.exec(token); - if (matchKeyframes && matchKeyframes.index === i) { - state = "keyframesRule-begin"; - keyframesRule = new CSSOM.CSSKeyframesRule(); - keyframesRule.__starts = i; - keyframesRule._vendorPrefix = matchKeyframes[1]; // Will come out as undefined if no prefix was found - i += matchKeyframes[0].length - 1; - buffer = ""; - break; - } else if (state === "selector") { - state = "atRule"; - } - } - buffer += character; - break; - - case "{": - if (state === "selector" || state === "atRule") { - styleRule.selectorText = buffer.trim(); - styleRule.style.__starts = i; - buffer = ""; - state = "before-name"; - } else if (state === "atBlock") { - mediaRule.media.mediaText = buffer.trim(); - - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = mediaRule; - mediaRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "conditionBlock") { - supportsRule.conditionText = buffer.trim(); - - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = supportsRule; - supportsRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "hostRule-begin") { - if (parentRule) { - ancestorRules.push(parentRule); - } - - currentScope = parentRule = hostRule; - hostRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } else if (state === "fontFaceRule-begin") { - if (parentRule) { - ancestorRules.push(parentRule); - fontFaceRule.parentRule = parentRule; - } - fontFaceRule.parentStyleSheet = styleSheet; - styleRule = fontFaceRule; - buffer = ""; - state = "before-name"; - } else if (state === "keyframesRule-begin") { - keyframesRule.name = buffer.trim(); - if (parentRule) { - ancestorRules.push(parentRule); - keyframesRule.parentRule = parentRule; - } - keyframesRule.parentStyleSheet = styleSheet; - currentScope = parentRule = keyframesRule; - buffer = ""; - state = "keyframeRule-begin"; - } else if (state === "keyframeRule-begin") { - styleRule = new CSSOM.CSSKeyframeRule(); - styleRule.keyText = buffer.trim(); - styleRule.__starts = i; - buffer = ""; - state = "before-name"; - } else if (state === "documentRule-begin") { - // FIXME: what if this '{' is in the url text of the match function? - documentRule.matcher.matcherText = buffer.trim(); - if (parentRule) { - ancestorRules.push(parentRule); - documentRule.parentRule = parentRule; - } - currentScope = parentRule = documentRule; - documentRule.parentStyleSheet = styleSheet; - buffer = ""; - state = "before-selector"; - } - break; - - case ":": - if (state === "name") { - name = buffer.trim(); - buffer = ""; - state = "before-value"; - } else { - buffer += character; - } - break; - - case "(": - if (state === 'value') { - // ie css expression mode - if (buffer.trim() === 'expression') { - var info = (new CSSOM.CSSValueExpression(token, i)).parse(); - - if (info.error) { - parseError(info.error); - } else { - buffer += info.expression; - i = info.idx; - } - } else { - state = 'value-parenthesis'; - //always ensure this is reset to 1 on transition - //from value to value-parenthesis - valueParenthesisDepth = 1; - buffer += character; - } - } else if (state === 'value-parenthesis') { - valueParenthesisDepth++; - buffer += character; - } else { - buffer += character; - } - break; - - case ")": - if (state === 'value-parenthesis') { - valueParenthesisDepth--; - if (valueParenthesisDepth === 0) state = 'value'; - } - buffer += character; - break; - - case "!": - if (state === "value" && token.indexOf("!important", i) === i) { - priority = "important"; - i += "important".length; - } else { - buffer += character; - } - break; - - case ";": - switch (state) { - case "value": - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - buffer = ""; - state = "before-name"; - break; - case "atRule": - buffer = ""; - state = "before-selector"; - break; - case "importRule": - importRule = new CSSOM.CSSImportRule(); - importRule.parentStyleSheet = importRule.styleSheet.parentStyleSheet = styleSheet; - importRule.cssText = buffer + character; - styleSheet.cssRules.push(importRule); - buffer = ""; - state = "before-selector"; - break; - default: - buffer += character; - break; - } - break; - - case "}": - switch (state) { - case "value": - styleRule.style.setProperty(name, buffer.trim(), priority); - priority = ""; - /* falls through */ - case "before-name": - case "name": - styleRule.__ends = i + 1; - if (parentRule) { - styleRule.parentRule = parentRule; - } - styleRule.parentStyleSheet = styleSheet; - currentScope.cssRules.push(styleRule); - buffer = ""; - if (currentScope.constructor === CSSOM.CSSKeyframesRule) { - state = "keyframeRule-begin"; - } else { - state = "before-selector"; - } - break; - case "keyframeRule-begin": - case "before-selector": - case "selector": - // End of media/supports/document rule. - if (!parentRule) { - parseError("Unexpected }"); - } - - // Handle rules nested in @media or @supports - hasAncestors = ancestorRules.length > 0; - - while (ancestorRules.length > 0) { - parentRule = ancestorRules.pop(); - - if ( - parentRule.constructor.name === "CSSMediaRule" - || parentRule.constructor.name === "CSSSupportsRule" - ) { - prevScope = currentScope; - currentScope = parentRule; - currentScope.cssRules.push(prevScope); - break; - } - - if (ancestorRules.length === 0) { - hasAncestors = false; - } - } - - if (!hasAncestors) { - currentScope.__ends = i + 1; - styleSheet.cssRules.push(currentScope); - currentScope = styleSheet; - parentRule = null; - } - - buffer = ""; - state = "before-selector"; - break; - } - break; - - default: - switch (state) { - case "before-selector": - state = "selector"; - styleRule = new CSSOM.CSSStyleRule(); - styleRule.__starts = i; - break; - case "before-name": - state = "name"; - break; - case "before-value": - state = "value"; - break; - case "importRule-begin": - state = "importRule"; - break; - } - buffer += character; - break; - } - } - - return styleSheet; -}; - - -//.CommonJS -exports.parse = CSSOM.parse; -// The following modules cannot be included sooner due to the mutual dependency with parse.js -CSSOM.CSSStyleSheet = (__nccwpck_require__(28050).CSSStyleSheet); -CSSOM.CSSStyleRule = (__nccwpck_require__(57732).CSSStyleRule); -CSSOM.CSSImportRule = (__nccwpck_require__(15339).CSSImportRule); -CSSOM.CSSMediaRule = (__nccwpck_require__(60365).CSSMediaRule); -CSSOM.CSSSupportsRule = (__nccwpck_require__(92243).CSSSupportsRule); -CSSOM.CSSFontFaceRule = (__nccwpck_require__(934).CSSFontFaceRule); -CSSOM.CSSHostRule = (__nccwpck_require__(80576).CSSHostRule); -CSSOM.CSSStyleDeclaration = (__nccwpck_require__(21449).CSSStyleDeclaration); -CSSOM.CSSKeyframeRule = (__nccwpck_require__(8308).CSSKeyframeRule); -CSSOM.CSSKeyframesRule = (__nccwpck_require__(53702).CSSKeyframesRule); -CSSOM.CSSValueExpression = (__nccwpck_require__(56356).CSSValueExpression); -CSSOM.CSSDocumentRule = (__nccwpck_require__(57775).CSSDocumentRule); -///CommonJS - - -/***/ }), - -/***/ 18326: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const MIMEType = __nccwpck_require__(59488); -const { parseURL, serializeURL } = __nccwpck_require__(66365); -const { - stripLeadingAndTrailingASCIIWhitespace, - stringPercentDecode, - isomorphicDecode, - forgivingBase64Decode -} = __nccwpck_require__(5505); - -module.exports = stringInput => { - const urlRecord = parseURL(stringInput); - - if (urlRecord === null) { - return null; - } - - return module.exports.fromURLRecord(urlRecord); -}; - -module.exports.fromURLRecord = urlRecord => { - if (urlRecord.scheme !== "data") { - return null; - } - - const input = serializeURL(urlRecord, true).substring("data:".length); - - let position = 0; - - let mimeType = ""; - while (position < input.length && input[position] !== ",") { - mimeType += input[position]; - ++position; - } - mimeType = stripLeadingAndTrailingASCIIWhitespace(mimeType); - - if (position === input.length) { - return null; - } - - ++position; - - const encodedBody = input.substring(position); - - let body = stringPercentDecode(encodedBody); - - // Can't use /i regexp flag because it isn't restricted to ASCII. - const mimeTypeBase64MatchResult = /(.*); *[Bb][Aa][Ss][Ee]64$/.exec(mimeType); - if (mimeTypeBase64MatchResult) { - const stringBody = isomorphicDecode(body); - body = forgivingBase64Decode(stringBody); - - if (body === null) { - return null; - } - mimeType = mimeTypeBase64MatchResult[1]; - } - - if (mimeType.startsWith(";")) { - mimeType = "text/plain" + mimeType; - } - - let mimeTypeRecord; - try { - mimeTypeRecord = new MIMEType(mimeType); - } catch (e) { - mimeTypeRecord = new MIMEType("text/plain;charset=US-ASCII"); - } - - return { - mimeType: mimeTypeRecord, - body - }; -}; - - -/***/ }), - -/***/ 5505: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const { percentDecode } = __nccwpck_require__(66365); -const { atob } = __nccwpck_require__(75696); - -exports.stripLeadingAndTrailingASCIIWhitespace = string => { - return string.replace(/^[ \t\n\f\r]+/, "").replace(/[ \t\n\f\r]+$/, ""); -}; - -exports.stringPercentDecode = input => { - return percentDecode(Buffer.from(input, "utf-8")); -}; - -exports.isomorphicDecode = input => { - return input.toString("binary"); -}; - -exports.forgivingBase64Decode = data => { - const asString = atob(data); - if (asString === null) { - return null; - } - return Buffer.from(asString, "binary"); -}; - - -/***/ }), - -/***/ 49458: -/***/ (function(module) { - -;(function (globalScope) { - 'use strict'; - - - /* - * decimal.js v10.2.1 - * An arbitrary-precision Decimal type for JavaScript. - * https://github.com/MikeMcl/decimal.js - * Copyright (c) 2020 Michael Mclaughlin - * MIT Licence - */ - - - // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ // - - - // The maximum exponent magnitude. - // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`. - var EXP_LIMIT = 9e15, // 0 to 9e15 - - // The limit on the value of `precision`, and on the value of the first argument to - // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`. - MAX_DIGITS = 1e9, // 0 to 1e9 - - // Base conversion alphabet. - NUMERALS = '0123456789abcdef', - - // The natural logarithm of 10 (1025 digits). - LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058', - - // Pi (1025 digits). - PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789', - - - // The initial configuration properties of the Decimal constructor. - DEFAULTS = { - - // These values must be integers within the stated ranges (inclusive). - // Most of these values can be changed at run-time using the `Decimal.config` method. - - // The maximum number of significant digits of the result of a calculation or base conversion. - // E.g. `Decimal.config({ precision: 20 });` - precision: 20, // 1 to MAX_DIGITS - - // The rounding mode used when rounding to `precision`. - // - // ROUND_UP 0 Away from zero. - // ROUND_DOWN 1 Towards zero. - // ROUND_CEIL 2 Towards +Infinity. - // ROUND_FLOOR 3 Towards -Infinity. - // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up. - // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. - // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. - // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. - // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. - // - // E.g. - // `Decimal.rounding = 4;` - // `Decimal.rounding = Decimal.ROUND_HALF_UP;` - rounding: 4, // 0 to 8 - - // The modulo mode used when calculating the modulus: a mod n. - // The quotient (q = a / n) is calculated according to the corresponding rounding mode. - // The remainder (r) is calculated as: r = a - n * q. - // - // UP 0 The remainder is positive if the dividend is negative, else is negative. - // DOWN 1 The remainder has the same sign as the dividend (JavaScript %). - // FLOOR 3 The remainder has the same sign as the divisor (Python %). - // HALF_EVEN 6 The IEEE 754 remainder function. - // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive. - // - // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian - // division (9) are commonly used for the modulus operation. The other rounding modes can also - // be used, but they may not give useful results. - modulo: 1, // 0 to 9 - - // The exponent value at and beneath which `toString` returns exponential notation. - // JavaScript numbers: -7 - toExpNeg: -7, // 0 to -EXP_LIMIT - - // The exponent value at and above which `toString` returns exponential notation. - // JavaScript numbers: 21 - toExpPos: 21, // 0 to EXP_LIMIT - - // The minimum exponent value, beneath which underflow to zero occurs. - // JavaScript numbers: -324 (5e-324) - minE: -EXP_LIMIT, // -1 to -EXP_LIMIT - - // The maximum exponent value, above which overflow to Infinity occurs. - // JavaScript numbers: 308 (1.7976931348623157e+308) - maxE: EXP_LIMIT, // 1 to EXP_LIMIT - - // Whether to use cryptographically-secure random number generation, if available. - crypto: false // true/false - }, - - - // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- // - - - Decimal, inexact, noConflict, quadrant, - external = true, - - decimalError = '[DecimalError] ', - invalidArgument = decimalError + 'Invalid argument: ', - precisionLimitExceeded = decimalError + 'Precision limit exceeded', - cryptoUnavailable = decimalError + 'crypto unavailable', - - mathfloor = Math.floor, - mathpow = Math.pow, - - isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i, - isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i, - isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i, - isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, - - BASE = 1e7, - LOG_BASE = 7, - MAX_SAFE_INTEGER = 9007199254740991, - - LN10_PRECISION = LN10.length - 1, - PI_PRECISION = PI.length - 1, - - // Decimal.prototype object - P = { name: '[object Decimal]' }; - - - // Decimal prototype methods - - - /* - * absoluteValue abs - * ceil - * comparedTo cmp - * cosine cos - * cubeRoot cbrt - * decimalPlaces dp - * dividedBy div - * dividedToIntegerBy divToInt - * equals eq - * floor - * greaterThan gt - * greaterThanOrEqualTo gte - * hyperbolicCosine cosh - * hyperbolicSine sinh - * hyperbolicTangent tanh - * inverseCosine acos - * inverseHyperbolicCosine acosh - * inverseHyperbolicSine asinh - * inverseHyperbolicTangent atanh - * inverseSine asin - * inverseTangent atan - * isFinite - * isInteger isInt - * isNaN - * isNegative isNeg - * isPositive isPos - * isZero - * lessThan lt - * lessThanOrEqualTo lte - * logarithm log - * [maximum] [max] - * [minimum] [min] - * minus sub - * modulo mod - * naturalExponential exp - * naturalLogarithm ln - * negated neg - * plus add - * precision sd - * round - * sine sin - * squareRoot sqrt - * tangent tan - * times mul - * toBinary - * toDecimalPlaces toDP - * toExponential - * toFixed - * toFraction - * toHexadecimal toHex - * toNearest - * toNumber - * toOctal - * toPower pow - * toPrecision - * toSignificantDigits toSD - * toString - * truncated trunc - * valueOf toJSON - */ - - - /* - * Return a new Decimal whose value is the absolute value of this Decimal. - * - */ - P.absoluteValue = P.abs = function () { - var x = new this.constructor(this); - if (x.s < 0) x.s = 1; - return finalise(x); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of positive Infinity. - * - */ - P.ceil = function () { - return finalise(new this.constructor(this), this.e + 1, 2); - }; - - - /* - * Return - * 1 if the value of this Decimal is greater than the value of `y`, - * -1 if the value of this Decimal is less than the value of `y`, - * 0 if they have the same value, - * NaN if the value of either Decimal is NaN. - * - */ - P.comparedTo = P.cmp = function (y) { - var i, j, xdL, ydL, - x = this, - xd = x.d, - yd = (y = new x.constructor(y)).d, - xs = x.s, - ys = y.s; - - // Either NaN or ±Infinity? - if (!xd || !yd) { - return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; - } - - // Either zero? - if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; - - // Signs differ? - if (xs !== ys) return xs; - - // Compare exponents. - if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; - - xdL = xd.length; - ydL = yd.length; - - // Compare digit by digit. - for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { - if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; - } - - // Compare lengths. - return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; - }; - - - /* - * Return a new Decimal whose value is the cosine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * cos(0) = 1 - * cos(-0) = 1 - * cos(Infinity) = NaN - * cos(-Infinity) = NaN - * cos(NaN) = NaN - * - */ - P.cosine = P.cos = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.d) return new Ctor(NaN); - - // cos(0) = cos(-0) = 1 - if (!x.d[0]) return new Ctor(1); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); - }; - - - /* - * - * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * cbrt(0) = 0 - * cbrt(-0) = -0 - * cbrt(1) = 1 - * cbrt(-1) = -1 - * cbrt(N) = N - * cbrt(-I) = -I - * cbrt(I) = I - * - * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3)) - * - */ - P.cubeRoot = P.cbrt = function () { - var e, m, n, r, rep, s, sd, t, t3, t3plusx, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - external = false; - - // Initial estimate. - s = x.s * mathpow(x.s * x, 1 / 3); - - // Math.cbrt underflow/overflow? - // Pass x to Math.pow as integer, then adjust the exponent of the result. - if (!s || Math.abs(s) == 1 / 0) { - n = digitsToString(x.d); - e = x.e; - - // Adjust n exponent so it is a multiple of 3 away from x exponent. - if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); - s = mathpow(n, 1 / 3); - - // Rarely, e may be one less than the result exponent value. - e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - r.s = x.s; - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Halley's method. - // TODO? Compare Newton's method. - for (;;) { - t = r; - t3 = t.times(t).times(t); - t3plusx = t3.plus(x); - r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 - // , i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return the number of decimal places of the value of this Decimal. - * - */ - P.decimalPlaces = P.dp = function () { - var w, - d = this.d, - n = NaN; - - if (d) { - w = d.length - 1; - n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; - - // Subtract the number of trailing zeros of the last word. - w = d[w]; - if (w) for (; w % 10 == 0; w /= 10) n--; - if (n < 0) n = 0; - } - - return n; - }; - - - /* - * n / 0 = I - * n / N = N - * n / I = 0 - * 0 / n = 0 - * 0 / 0 = N - * 0 / N = N - * 0 / I = 0 - * N / n = N - * N / 0 = N - * N / N = N - * N / I = N - * I / n = I - * I / 0 = I - * I / N = N - * I / I = N - * - * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedBy = P.div = function (y) { - return divide(this, new this.constructor(y)); - }; - - - /* - * Return a new Decimal whose value is the integer part of dividing the value of this Decimal - * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.dividedToIntegerBy = P.divToInt = function (y) { - var x = this, - Ctor = x.constructor; - return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); - }; - - - /* - * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false. - * - */ - P.equals = P.eq = function (y) { - return this.cmp(y) === 0; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the - * direction of negative Infinity. - * - */ - P.floor = function () { - return finalise(new this.constructor(this), this.e + 1, 3); - }; - - - /* - * Return true if the value of this Decimal is greater than the value of `y`, otherwise return - * false. - * - */ - P.greaterThan = P.gt = function (y) { - return this.cmp(y) > 0; - }; - - - /* - * Return true if the value of this Decimal is greater than or equal to the value of `y`, - * otherwise return false. - * - */ - P.greaterThanOrEqualTo = P.gte = function (y) { - var k = this.cmp(y); - return k == 1 || k === 0; - }; - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [1, Infinity] - * - * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ... - * - * cosh(0) = 1 - * cosh(-0) = 1 - * cosh(Infinity) = Infinity - * cosh(-Infinity) = Infinity - * cosh(NaN) = NaN - * - * x time taken (ms) result - * 1000 9 9.8503555700852349694e+433 - * 10000 25 4.4034091128314607936e+4342 - * 100000 171 1.4033316802130615897e+43429 - * 1000000 3817 1.5166076984010437725e+434294 - * 10000000 abandoned after 2 minute wait - * - * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x)) - * - */ - P.hyperbolicCosine = P.cosh = function () { - var k, n, pr, rm, len, - x = this, - Ctor = x.constructor, - one = new Ctor(1); - - if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); - if (x.isZero()) return one; - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 - // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) - - // Estimate the optimum number of times to use the argument reduction. - // TODO? Estimation reused from cosine() and may not be optimal here. - if (len < 32) { - k = Math.ceil(len / 3); - n = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - n = '2.3283064365386962890625e-10'; - } - - x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); - - // Reverse argument reduction - var cosh2_x, - i = k, - d8 = new Ctor(8); - for (; i--;) { - cosh2_x = x.times(x); - x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); - } - - return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ... - * - * sinh(0) = 0 - * sinh(-0) = -0 - * sinh(Infinity) = Infinity - * sinh(-Infinity) = -Infinity - * sinh(NaN) = NaN - * - * x time taken (ms) - * 10 2 ms - * 100 5 ms - * 1000 14 ms - * 10000 82 ms - * 100000 886 ms 1.4033316802130615897e+43429 - * 200000 2613 ms - * 300000 5407 ms - * 400000 8824 ms - * 500000 13026 ms 8.7080643612718084129e+217146 - * 1000000 48543 ms - * - * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x)) - * - */ - P.hyperbolicSine = P.sinh = function () { - var k, pr, rm, len, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; - Ctor.rounding = 1; - len = x.d.length; - - if (len < 3) { - x = taylorSeries(Ctor, 2, x, x, true); - } else { - - // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) - // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) - // 3 multiplications and 1 addition - - // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) - // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) - // 4 multiplications and 2 additions - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x, true); - - // Reverse argument reduction - var sinh2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sinh2_x = x.times(x); - x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); - } - } - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * tanh(x) = sinh(x) / cosh(x) - * - * tanh(0) = 0 - * tanh(-0) = -0 - * tanh(Infinity) = 1 - * tanh(-Infinity) = -1 - * tanh(NaN) = NaN - * - */ - P.hyperbolicTangent = P.tanh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(x.s); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 7; - Ctor.rounding = 1; - - return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); - }; - - - /* - * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of - * this Decimal. - * - * Domain: [-1, 1] - * Range: [0, pi] - * - * acos(x) = pi/2 - asin(x) - * - * acos(0) = pi/2 - * acos(-0) = pi/2 - * acos(1) = 0 - * acos(-1) = pi - * acos(1/2) = pi/3 - * acos(-1/2) = 2*pi/3 - * acos(|x| > 1) = NaN - * acos(NaN) = NaN - * - */ - P.inverseCosine = P.acos = function () { - var halfPi, - x = this, - Ctor = x.constructor, - k = x.abs().cmp(1), - pr = Ctor.precision, - rm = Ctor.rounding; - - if (k !== -1) { - return k === 0 - // |x| is 1 - ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) - // |x| > 1 or x is NaN - : new Ctor(NaN); - } - - if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); - - // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.asin(); - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return halfPi.minus(x); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the - * value of this Decimal. - * - * Domain: [1, Infinity] - * Range: [0, Infinity] - * - * acosh(x) = ln(x + sqrt(x^2 - 1)) - * - * acosh(x < 1) = NaN - * acosh(NaN) = NaN - * acosh(Infinity) = Infinity - * acosh(-Infinity) = NaN - * acosh(0) = NaN - * acosh(-0) = NaN - * acosh(1) = 0 - * acosh(-1) = NaN - * - */ - P.inverseHyperbolicCosine = P.acosh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); - if (!x.isFinite()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; - Ctor.rounding = 1; - external = false; - - x = x.times(x).minus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * asinh(x) = ln(x + sqrt(x^2 + 1)) - * - * asinh(NaN) = NaN - * asinh(Infinity) = Infinity - * asinh(-Infinity) = -Infinity - * asinh(0) = 0 - * asinh(-0) = -0 - * - */ - P.inverseHyperbolicSine = P.asinh = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite() || x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; - Ctor.rounding = 1; - external = false; - - x = x.times(x).plus(1).sqrt().plus(x); - - external = true; - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.ln(); - }; - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the - * value of this Decimal. - * - * Domain: [-1, 1] - * Range: [-Infinity, Infinity] - * - * atanh(x) = 0.5 * ln((1 + x) / (1 - x)) - * - * atanh(|x| > 1) = NaN - * atanh(NaN) = NaN - * atanh(Infinity) = NaN - * atanh(-Infinity) = NaN - * atanh(0) = 0 - * atanh(-0) = -0 - * atanh(1) = Infinity - * atanh(-1) = -Infinity - * - */ - P.inverseHyperbolicTangent = P.atanh = function () { - var pr, rm, wpr, xsd, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); - - pr = Ctor.precision; - rm = Ctor.rounding; - xsd = x.sd(); - - if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); - - Ctor.precision = wpr = xsd - x.e; - - x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); - - Ctor.precision = pr + 4; - Ctor.rounding = 1; - - x = x.ln(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(0.5); - }; - - - /* - * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this - * Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2))) - * - * asin(0) = 0 - * asin(-0) = -0 - * asin(1/2) = pi/6 - * asin(-1/2) = -pi/6 - * asin(1) = pi/2 - * asin(-1) = -pi/2 - * asin(|x| > 1) = NaN - * asin(NaN) = NaN - * - * TODO? Compare performance of Taylor series. - * - */ - P.inverseSine = P.asin = function () { - var halfPi, k, - pr, rm, - x = this, - Ctor = x.constructor; - - if (x.isZero()) return new Ctor(x); - - k = x.abs().cmp(1); - pr = Ctor.precision; - rm = Ctor.rounding; - - if (k !== -1) { - - // |x| is 1 - if (k === 0) { - halfPi = getPi(Ctor, pr + 4, rm).times(0.5); - halfPi.s = x.s; - return halfPi; - } - - // |x| > 1 or x is NaN - return new Ctor(NaN); - } - - // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 - - Ctor.precision = pr + 6; - Ctor.rounding = 1; - - x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return x.times(2); - }; - - - /* - * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value - * of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi/2, pi/2] - * - * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - * - * atan(0) = 0 - * atan(-0) = -0 - * atan(1) = pi/4 - * atan(-1) = -pi/4 - * atan(Infinity) = pi/2 - * atan(-Infinity) = -pi/2 - * atan(NaN) = NaN - * - */ - P.inverseTangent = P.atan = function () { - var i, j, k, n, px, t, r, wpr, x2, - x = this, - Ctor = x.constructor, - pr = Ctor.precision, - rm = Ctor.rounding; - - if (!x.isFinite()) { - if (!x.s) return new Ctor(NaN); - if (pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.5); - r.s = x.s; - return r; - } - } else if (x.isZero()) { - return new Ctor(x); - } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { - r = getPi(Ctor, pr + 4, rm).times(0.25); - r.s = x.s; - return r; - } - - Ctor.precision = wpr = pr + 10; - Ctor.rounding = 1; - - // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); - - // Argument reduction - // Ensure |x| < 0.42 - // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) - - k = Math.min(28, wpr / LOG_BASE + 2 | 0); - - for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); - - external = false; - - j = Math.ceil(wpr / LOG_BASE); - n = 1; - x2 = x.times(x); - r = new Ctor(x); - px = x; - - // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... - for (; i !== -1;) { - px = px.times(x2); - t = r.minus(px.div(n += 2)); - - px = px.times(x2); - r = t.plus(px.div(n += 2)); - - if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); - } - - if (k) r = r.times(2 << (k - 1)); - - external = true; - - return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); - }; - - - /* - * Return true if the value of this Decimal is a finite number, otherwise return false. - * - */ - P.isFinite = function () { - return !!this.d; - }; - - - /* - * Return true if the value of this Decimal is an integer, otherwise return false. - * - */ - P.isInteger = P.isInt = function () { - return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; - }; - - - /* - * Return true if the value of this Decimal is NaN, otherwise return false. - * - */ - P.isNaN = function () { - return !this.s; - }; - - - /* - * Return true if the value of this Decimal is negative, otherwise return false. - * - */ - P.isNegative = P.isNeg = function () { - return this.s < 0; - }; - - - /* - * Return true if the value of this Decimal is positive, otherwise return false. - * - */ - P.isPositive = P.isPos = function () { - return this.s > 0; - }; - - - /* - * Return true if the value of this Decimal is 0 or -0, otherwise return false. - * - */ - P.isZero = function () { - return !!this.d && this.d[0] === 0; - }; - - - /* - * Return true if the value of this Decimal is less than `y`, otherwise return false. - * - */ - P.lessThan = P.lt = function (y) { - return this.cmp(y) < 0; - }; - - - /* - * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false. - * - */ - P.lessThanOrEqualTo = P.lte = function (y) { - return this.cmp(y) < 1; - }; - - - /* - * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * If no base is specified, return log[10](arg). - * - * log[base](arg) = ln(arg) / ln(base) - * - * The result will always be correctly rounded if the base of the log is 10, and 'almost always' - * otherwise: - * - * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen - * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error - * between the result and the correctly rounded result will be one ulp (unit in the last place). - * - * log[-b](a) = NaN - * log[0](a) = NaN - * log[1](a) = NaN - * log[NaN](a) = NaN - * log[Infinity](a) = NaN - * log[b](0) = -Infinity - * log[b](-0) = -Infinity - * log[b](-a) = NaN - * log[b](1) = 0 - * log[b](Infinity) = Infinity - * log[b](NaN) = NaN - * - * [base] {number|string|Decimal} The base of the logarithm. - * - */ - P.logarithm = P.log = function (base) { - var isBase10, d, denominator, k, inf, num, sd, r, - arg = this, - Ctor = arg.constructor, - pr = Ctor.precision, - rm = Ctor.rounding, - guard = 5; - - // Default base is 10. - if (base == null) { - base = new Ctor(10); - isBase10 = true; - } else { - base = new Ctor(base); - d = base.d; - - // Return NaN if base is negative, or non-finite, or is 0 or 1. - if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); - - isBase10 = base.eq(10); - } - - d = arg.d; - - // Is arg negative, non-finite, 0 or 1? - if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { - return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); - } - - // The result will have a non-terminating decimal expansion if base is 10 and arg is not an - // integer power of 10. - if (isBase10) { - if (d.length > 1) { - inf = true; - } else { - for (k = d[0]; k % 10 === 0;) k /= 10; - inf = k !== 1; - } - } - - external = false; - sd = pr + guard; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - - // The result will have 5 rounding digits. - r = divide(num, denominator, sd, 1); - - // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, - // calculate 10 further digits. - // - // If the result is known to have an infinite decimal expansion, repeat this until it is clear - // that the result is above or below the boundary. Otherwise, if after calculating the 10 - // further digits, the last 14 are nines, round up and assume the result is exact. - // Also assume the result is exact if the last 14 are zero. - // - // Example of a result that will be incorrectly rounded: - // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... - // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it - // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so - // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal - // place is still 2.6. - if (checkRoundingDigits(r.d, k = pr, rm)) { - - do { - sd += 10; - num = naturalLogarithm(arg, sd); - denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); - r = divide(num, denominator, sd, 1); - - if (!inf) { - - // Check for 14 nines from the 2nd rounding digit, as the first may be 4. - if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - - break; - } - } while (checkRoundingDigits(r.d, k += 10, rm)); - } - - external = true; - - return finalise(r, pr, rm); - }; - - - /* - * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.max = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'lt'); - }; - */ - - - /* - * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal. - * - * arguments {number|string|Decimal} - * - P.min = function () { - Array.prototype.push.call(arguments, this); - return maxOrMin(this.constructor, arguments, 'gt'); - }; - */ - - - /* - * n - 0 = n - * n - N = N - * n - I = -I - * 0 - n = -n - * 0 - 0 = 0 - * 0 - N = N - * 0 - I = -I - * N - n = N - * N - 0 = N - * N - N = N - * N - I = N - * I - n = I - * I - 0 = I - * I - N = N - * I - I = N - * - * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.minus = P.sub = function (y) { - var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return y negated if x is finite and y is ±Infinity. - else if (x.d) y.s = -y.s; - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with different signs. - // Return NaN if both are ±Infinity with the same sign. - else y = new Ctor(y.d || x.s !== y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.plus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return y negated if x is zero and y is non-zero. - if (yd[0]) y.s = -y.s; - - // Return x if y is zero and x is non-zero. - else if (xd[0]) y = new Ctor(x); - - // Return zero if both are zero. - // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. - else return new Ctor(rm === 3 ? -0 : 0); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - e = mathfloor(y.e / LOG_BASE); - xe = mathfloor(x.e / LOG_BASE); - - xd = xd.slice(); - k = xe - e; - - // If base 1e7 exponents differ... - if (k) { - xLTy = k < 0; - - if (xLTy) { - d = xd; - k = -k; - len = yd.length; - } else { - d = yd; - e = xe; - len = xd.length; - } - - // Numbers with massively different exponents would result in a very high number of - // zeros needing to be prepended, but this can be avoided while still ensuring correct - // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. - i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; - - if (k > i) { - k = i; - d.length = 1; - } - - // Prepend zeros to equalise exponents. - d.reverse(); - for (i = k; i--;) d.push(0); - d.reverse(); - - // Base 1e7 exponents equal. - } else { - - // Check digits to determine which is the bigger number. - - i = xd.length; - len = yd.length; - xLTy = i < len; - if (xLTy) len = i; - - for (i = 0; i < len; i++) { - if (xd[i] != yd[i]) { - xLTy = xd[i] < yd[i]; - break; - } - } - - k = 0; - } - - if (xLTy) { - d = xd; - xd = yd; - yd = d; - y.s = -y.s; - } - - len = xd.length; - - // Append zeros to `xd` if shorter. - // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. - for (i = yd.length - len; i > 0; --i) xd[len++] = 0; - - // Subtract yd from xd. - for (i = yd.length; i > k;) { - - if (xd[--i] < yd[i]) { - for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; - --xd[j]; - xd[i] += BASE; - } - - xd[i] -= yd[i]; - } - - // Remove trailing zeros. - for (; xd[--len] === 0;) xd.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xd[0] === 0; xd.shift()) --e; - - // Zero? - if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * n % 0 = N - * n % N = N - * n % I = n - * 0 % n = 0 - * -0 % n = -0 - * 0 % 0 = N - * 0 % N = N - * 0 % I = 0 - * N % n = N - * N % 0 = N - * N % N = N - * N % I = N - * I % n = N - * I % 0 = N - * I % N = N - * I % I = N - * - * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * The result depends on the modulo mode. - * - */ - P.modulo = P.mod = function (y) { - var q, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. - if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); - - // Return x if y is ±Infinity or x is ±0. - if (!y.d || x.d && !x.d[0]) { - return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); - } - - // Prevent rounding of intermediate calculations. - external = false; - - if (Ctor.modulo == 9) { - - // Euclidian division: q = sign(y) * floor(x / abs(y)) - // result = x - q * y where 0 <= result < abs(y) - q = divide(x, y.abs(), 0, 3, 1); - q.s *= y.s; - } else { - q = divide(x, y, 0, Ctor.modulo, 1); - } - - q = q.times(y); - - external = true; - - return x.minus(q); - }; - - - /* - * Return a new Decimal whose value is the natural exponential of the value of this Decimal, - * i.e. the base e raised to the power the value of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.naturalExponential = P.exp = function () { - return naturalExponential(this); - }; - - - /* - * Return a new Decimal whose value is the natural logarithm of the value of this Decimal, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - */ - P.naturalLogarithm = P.ln = function () { - return naturalLogarithm(this); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by - * -1. - * - */ - P.negated = P.neg = function () { - var x = new this.constructor(this); - x.s = -x.s; - return finalise(x); - }; - - - /* - * n + 0 = n - * n + N = N - * n + I = I - * 0 + n = n - * 0 + 0 = 0 - * 0 + N = N - * 0 + I = I - * N + n = N - * N + 0 = N - * N + N = N - * N + I = N - * I + n = I - * I + 0 = I - * I + N = N - * I + I = I - * - * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - */ - P.plus = P.add = function (y) { - var carry, d, e, i, k, len, pr, rm, xd, yd, - x = this, - Ctor = x.constructor; - - y = new Ctor(y); - - // If either is not finite... - if (!x.d || !y.d) { - - // Return NaN if either is NaN. - if (!x.s || !y.s) y = new Ctor(NaN); - - // Return x if y is finite and x is ±Infinity. - // Return x if both are ±Infinity with the same sign. - // Return NaN if both are ±Infinity with different signs. - // Return y if x is finite and y is ±Infinity. - else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); - - return y; - } - - // If signs differ... - if (x.s != y.s) { - y.s = -y.s; - return x.minus(y); - } - - xd = x.d; - yd = y.d; - pr = Ctor.precision; - rm = Ctor.rounding; - - // If either is zero... - if (!xd[0] || !yd[0]) { - - // Return x if y is zero. - // Return y if y is non-zero. - if (!yd[0]) y = new Ctor(x); - - return external ? finalise(y, pr, rm) : y; - } - - // x and y are finite, non-zero numbers with the same sign. - - // Calculate base 1e7 exponents. - k = mathfloor(x.e / LOG_BASE); - e = mathfloor(y.e / LOG_BASE); - - xd = xd.slice(); - i = k - e; - - // If base 1e7 exponents differ... - if (i) { - - if (i < 0) { - d = xd; - i = -i; - len = yd.length; - } else { - d = yd; - e = k; - len = xd.length; - } - - // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. - k = Math.ceil(pr / LOG_BASE); - len = k > len ? k + 1 : len + 1; - - if (i > len) { - i = len; - d.length = 1; - } - - // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. - d.reverse(); - for (; i--;) d.push(0); - d.reverse(); - } - - len = xd.length; - i = yd.length; - - // If yd is longer than xd, swap xd and yd so xd points to the longer array. - if (len - i < 0) { - i = len; - d = yd; - yd = xd; - xd = d; - } - - // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. - for (carry = 0; i;) { - carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; - xd[i] %= BASE; - } - - if (carry) { - xd.unshift(carry); - ++e; - } - - // Remove trailing zeros. - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - for (len = xd.length; xd[--len] == 0;) xd.pop(); - - y.d = xd; - y.e = getBase10Exponent(xd, e); - - return external ? finalise(y, pr, rm) : y; - }; - - - /* - * Return the number of significant digits of the value of this Decimal. - * - * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. - * - */ - P.precision = P.sd = function (z) { - var k, - x = this; - - if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); - - if (x.d) { - k = getPrecision(x.d); - if (z && x.e + 1 > k) k = x.e + 1; - } else { - k = NaN; - } - - return k; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using - * rounding mode `rounding`. - * - */ - P.round = function () { - var x = this, - Ctor = x.constructor; - - return finalise(new Ctor(x), x.e + 1, Ctor.rounding); - }; - - - /* - * Return a new Decimal whose value is the sine of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-1, 1] - * - * sin(x) = x - x^3/3! + x^5/5! - ... - * - * sin(0) = 0 - * sin(-0) = -0 - * sin(Infinity) = NaN - * sin(-Infinity) = NaN - * sin(NaN) = NaN - * - */ - P.sine = P.sin = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; - Ctor.rounding = 1; - - x = sine(Ctor, toLessThanHalfPi(Ctor, x)); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); - }; - - - /* - * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * sqrt(-n) = N - * sqrt(N) = N - * sqrt(-I) = N - * sqrt(I) = I - * sqrt(0) = 0 - * sqrt(-0) = -0 - * - */ - P.squareRoot = P.sqrt = function () { - var m, n, sd, r, rep, t, - x = this, - d = x.d, - e = x.e, - s = x.s, - Ctor = x.constructor; - - // Negative/NaN/Infinity/zero? - if (s !== 1 || !d || !d[0]) { - return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); - } - - external = false; - - // Initial estimate. - s = Math.sqrt(+x); - - // Math.sqrt underflow/overflow? - // Pass x to Math.sqrt as integer, then adjust the exponent of the result. - if (s == 0 || s == 1 / 0) { - n = digitsToString(d); - - if ((n.length + e) % 2 == 0) n += '0'; - s = Math.sqrt(n); - e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); - - if (s == 1 / 0) { - n = '5e' + e; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf('e') + 1) + e; - } - - r = new Ctor(n); - } else { - r = new Ctor(s.toString()); - } - - sd = (e = Ctor.precision) + 3; - - // Newton-Raphson iteration. - for (;;) { - t = r; - r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); - - // TODO? Replace with for-loop and checkRoundingDigits. - if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { - n = n.slice(sd - 3, sd + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or - // 4999, i.e. approaching a rounding boundary, continue the iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the exact result as the - // nines may infinitely repeat. - if (!rep) { - finalise(t, e + 1, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - sd += 4; - rep = 1; - } else { - - // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. - // If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - finalise(r, e + 1, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - - external = true; - - return finalise(r, e, Ctor.rounding, m); - }; - - - /* - * Return a new Decimal whose value is the tangent of the value in radians of this Decimal. - * - * Domain: [-Infinity, Infinity] - * Range: [-Infinity, Infinity] - * - * tan(0) = 0 - * tan(-0) = -0 - * tan(Infinity) = NaN - * tan(-Infinity) = NaN - * tan(NaN) = NaN - * - */ - P.tangent = P.tan = function () { - var pr, rm, - x = this, - Ctor = x.constructor; - - if (!x.isFinite()) return new Ctor(NaN); - if (x.isZero()) return new Ctor(x); - - pr = Ctor.precision; - rm = Ctor.rounding; - Ctor.precision = pr + 10; - Ctor.rounding = 1; - - x = x.sin(); - x.s = 1; - x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); - - Ctor.precision = pr; - Ctor.rounding = rm; - - return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); - }; - - - /* - * n * 0 = 0 - * n * N = N - * n * I = I - * 0 * n = 0 - * 0 * 0 = 0 - * 0 * N = N - * 0 * I = N - * N * n = N - * N * 0 = N - * N * N = N - * N * I = N - * I * n = I - * I * 0 = N - * I * N = N - * I * I = I - * - * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - */ - P.times = P.mul = function (y) { - var carry, e, i, k, r, rL, t, xdL, ydL, - x = this, - Ctor = x.constructor, - xd = x.d, - yd = (y = new Ctor(y)).d; - - y.s *= x.s; - - // If either is NaN, ±Infinity or ±0... - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd - - // Return NaN if either is NaN. - // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. - ? NaN - - // Return ±Infinity if either is ±Infinity. - // Return ±0 if either is ±0. - : !xd || !yd ? y.s / 0 : y.s * 0); - } - - e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); - xdL = xd.length; - ydL = yd.length; - - // Ensure xd points to the longer array. - if (xdL < ydL) { - r = xd; - xd = yd; - yd = r; - rL = xdL; - xdL = ydL; - ydL = rL; - } - - // Initialise the result array with zeros. - r = []; - rL = xdL + ydL; - for (i = rL; i--;) r.push(0); - - // Multiply! - for (i = ydL; --i >= 0;) { - carry = 0; - for (k = xdL + i; k > i;) { - t = r[k] + yd[i] * xd[k - i - 1] + carry; - r[k--] = t % BASE | 0; - carry = t / BASE | 0; - } - - r[k] = (r[k] + carry) % BASE | 0; - } - - // Remove trailing zeros. - for (; !r[--rL];) r.pop(); - - if (carry) ++e; - else r.shift(); - - y.d = r; - y.e = getBase10Exponent(r, e); - - return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; - }; - - - /* - * Return a string representing the value of this Decimal in base 2, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toBinary = function (sd, rm) { - return toStringBinary(this, 2, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp` - * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted. - * - * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toDecimalPlaces = P.toDP = function (dp, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - if (dp === void 0) return x; - - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - return finalise(x, dp + x.e + 1, rm); - }; - - - /* - * Return a string representing the value of this Decimal in exponential notation rounded to - * `dp` fixed decimal places using rounding mode `rounding`. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toExponential = function (dp, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x, true); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), dp + 1, rm); - str = finiteToString(x, true, dp + 1); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a string representing the value of this Decimal in normal (fixed-point) notation to - * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is - * omitted. - * - * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - * (-0).toFixed(3) is '0.000'. - * (-0.5).toFixed(0) is '-0'. - * - */ - P.toFixed = function (dp, rm) { - var str, y, - x = this, - Ctor = x.constructor; - - if (dp === void 0) { - str = finiteToString(x); - } else { - checkInt32(dp, 0, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - y = finalise(new Ctor(x), dp + x.e + 1, rm); - str = finiteToString(y, false, dp + y.e + 1); - } - - // To determine whether to add the minus sign look at the value before it was rounded, - // i.e. look at `x` rather than `y`. - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return an array representing the value of this Decimal as a simple fraction with an integer - * numerator and an integer denominator. - * - * The denominator will be a positive non-zero value less than or equal to the specified maximum - * denominator. If a maximum denominator is not specified, the denominator will be the lowest - * value necessary to represent the number exactly. - * - * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity. - * - */ - P.toFraction = function (maxD) { - var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, - x = this, - xd = x.d, - Ctor = x.constructor; - - if (!xd) return new Ctor(x); - - n1 = d0 = new Ctor(1); - d1 = n0 = new Ctor(0); - - d = new Ctor(d1); - e = d.e = getPrecision(xd) - x.e - 1; - k = e % LOG_BASE; - d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); - - if (maxD == null) { - - // d is 10**e, the minimum max-denominator needed. - maxD = e > 0 ? d : n1; - } else { - n = new Ctor(maxD); - if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); - maxD = n.gt(d) ? (e > 0 ? d : n1) : n; - } - - external = false; - n = new Ctor(digitsToString(xd)); - pr = Ctor.precision; - Ctor.precision = e = xd.length * LOG_BASE * 2; - - for (;;) { - q = divide(n, d, 0, 1, 1); - d2 = d0.plus(q.times(d1)); - if (d2.cmp(maxD) == 1) break; - d0 = d1; - d1 = d2; - d2 = n1; - n1 = n0.plus(q.times(d2)); - n0 = d2; - d2 = d; - d = n.minus(q.times(d2)); - n = d2; - } - - d2 = divide(maxD.minus(d0), d1, 0, 1, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - - // Determine which fraction is closer to x, n0/d0 or n1/d1? - r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 - ? [n1, d1] : [n0, d0]; - - Ctor.precision = pr; - external = true; - - return r; - }; - - - /* - * Return a string representing the value of this Decimal in base 16, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toHexadecimal = P.toHex = function (sd, rm) { - return toStringBinary(this, 16, sd, rm); - }; - - - /* - * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding - * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal. - * - * The return value will always have the same sign as this Decimal, unless either this Decimal - * or `y` is NaN, in which case the return value will be also be NaN. - * - * The return value is not affected by the value of `precision`. - * - * y {number|string|Decimal} The magnitude to round to a multiple of. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toNearest() rounding mode not an integer: {rm}' - * 'toNearest() rounding mode out of range: {rm}' - * - */ - P.toNearest = function (y, rm) { - var x = this, - Ctor = x.constructor; - - x = new Ctor(x); - - if (y == null) { - - // If x is not finite, return x. - if (!x.d) return x; - - y = new Ctor(1); - rm = Ctor.rounding; - } else { - y = new Ctor(y); - if (rm === void 0) { - rm = Ctor.rounding; - } else { - checkInt32(rm, 0, 8); - } - - // If x is not finite, return x if y is not NaN, else NaN. - if (!x.d) return y.s ? x : y; - - // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. - if (!y.d) { - if (y.s) y.s = x.s; - return y; - } - } - - // If y is not zero, calculate the nearest multiple of y to x. - if (y.d[0]) { - external = false; - x = divide(x, y, 0, rm, 1).times(y); - external = true; - finalise(x); - - // If y is zero, return zero with the sign of x. - } else { - y.s = x.s; - x = y; - } - - return x; - }; - - - /* - * Return the value of this Decimal converted to a number primitive. - * Zero keeps its sign. - * - */ - P.toNumber = function () { - return +this; - }; - - - /* - * Return a string representing the value of this Decimal in base 8, round to `sd` significant - * digits using rounding mode `rm`. - * - * If the optional `sd` argument is present then return binary exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toOctal = function (sd, rm) { - return toStringBinary(this, 8, sd, rm); - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded - * to `precision` significant digits using rounding mode `rounding`. - * - * ECMAScript compliant. - * - * pow(x, NaN) = NaN - * pow(x, ±0) = 1 - - * pow(NaN, non-zero) = NaN - * pow(abs(x) > 1, +Infinity) = +Infinity - * pow(abs(x) > 1, -Infinity) = +0 - * pow(abs(x) == 1, ±Infinity) = NaN - * pow(abs(x) < 1, +Infinity) = +0 - * pow(abs(x) < 1, -Infinity) = +Infinity - * pow(+Infinity, y > 0) = +Infinity - * pow(+Infinity, y < 0) = +0 - * pow(-Infinity, odd integer > 0) = -Infinity - * pow(-Infinity, even integer > 0) = +Infinity - * pow(-Infinity, odd integer < 0) = -0 - * pow(-Infinity, even integer < 0) = +0 - * pow(+0, y > 0) = +0 - * pow(+0, y < 0) = +Infinity - * pow(-0, odd integer > 0) = -0 - * pow(-0, even integer > 0) = +0 - * pow(-0, odd integer < 0) = -Infinity - * pow(-0, even integer < 0) = +Infinity - * pow(finite x < 0, finite non-integer) = NaN - * - * For non-integer or very large exponents pow(x, y) is calculated using - * - * x^y = exp(y*ln(x)) - * - * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the - * probability of an incorrectly rounded result - * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14 - * i.e. 1 in 250,000,000,000,000 - * - * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place). - * - * y {number|string|Decimal} The power to which to raise this Decimal. - * - */ - P.toPower = P.pow = function (y) { - var e, k, pr, r, rm, s, - x = this, - Ctor = x.constructor, - yn = +(y = new Ctor(y)); - - // Either ±Infinity, NaN or ±0? - if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); - - x = new Ctor(x); - - if (x.eq(1)) return x; - - pr = Ctor.precision; - rm = Ctor.rounding; - - if (y.eq(1)) return finalise(x, pr, rm); - - // y exponent - e = mathfloor(y.e / LOG_BASE); - - // If y is a small integer use the 'exponentiation by squaring' algorithm. - if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { - r = intPow(Ctor, x, k, pr); - return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); - } - - s = x.s; - - // if x is negative - if (s < 0) { - - // if y is not an integer - if (e < y.d.length - 1) return new Ctor(NaN); - - // Result is positive if x is negative and the last digit of integer y is even. - if ((y.d[e] & 1) == 0) s = 1; - - // if x.eq(-1) - if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) { - x.s = s; - return x; - } - } - - // Estimate result exponent. - // x^y = 10^e, where e = y * log10(x) - // log10(x) = log10(x_significand) + x_exponent - // log10(x_significand) = ln(x_significand) / ln(10) - k = mathpow(+x, yn); - e = k == 0 || !isFinite(k) - ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) - : new Ctor(k + '').e; - - // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. - - // Overflow/underflow? - if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0); - - external = false; - Ctor.rounding = x.s = 1; - - // Estimate the extra guard digits needed to ensure five correct rounding digits from - // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): - // new Decimal(2.32456).pow('2087987436534566.46411') - // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 - k = Math.min(12, (e + '').length); - - // r = x^y = exp(y*ln(x)) - r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); - - // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40) - if (r.d) { - - // Truncate to the required precision plus five rounding digits. - r = finalise(r, pr + 5, 1); - - // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate - // the result. - if (checkRoundingDigits(r.d, pr, rm)) { - e = pr + 10; - - // Truncate to the increased precision plus five rounding digits. - r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); - - // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). - if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { - r = finalise(r, pr + 1, 0); - } - } - } - - r.s = s; - external = true; - Ctor.rounding = rm; - - return finalise(r, pr, rm); - }; - - - /* - * Return a string representing the value of this Decimal rounded to `sd` significant digits - * using rounding mode `rounding`. - * - * Return exponential notation if `sd` is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - */ - P.toPrecision = function (sd, rm) { - var str, - x = this, - Ctor = x.constructor; - - if (sd === void 0) { - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - - x = finalise(new Ctor(x), sd, rm); - str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); - } - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd` - * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if - * omitted. - * - * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * 'toSD() digits out of range: {sd}' - * 'toSD() digits not an integer: {sd}' - * 'toSD() rounding mode not an integer: {rm}' - * 'toSD() rounding mode out of range: {rm}' - * - */ - P.toSignificantDigits = P.toSD = function (sd, rm) { - var x = this, - Ctor = x.constructor; - - if (sd === void 0) { - sd = Ctor.precision; - rm = Ctor.rounding; - } else { - checkInt32(sd, 1, MAX_DIGITS); - - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } - - return finalise(new Ctor(x), sd, rm); - }; - - - /* - * Return a string representing the value of this Decimal. - * - * Return exponential notation if this Decimal has a positive exponent equal to or greater than - * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`. - * - */ - P.toString = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() && !x.isZero() ? '-' + str : str; - }; - - - /* - * Return a new Decimal whose value is the value of this Decimal truncated to a whole number. - * - */ - P.truncated = P.trunc = function () { - return finalise(new this.constructor(this), this.e + 1, 1); - }; - - - /* - * Return a string representing the value of this Decimal. - * Unlike `toString`, negative zero will include the minus sign. - * - */ - P.valueOf = P.toJSON = function () { - var x = this, - Ctor = x.constructor, - str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); - - return x.isNeg() ? '-' + str : str; - }; - - - /* - // Add aliases to match BigDecimal method names. - // P.add = P.plus; - P.subtract = P.minus; - P.multiply = P.times; - P.divide = P.div; - P.remainder = P.mod; - P.compareTo = P.cmp; - P.negate = P.neg; - */ - - - // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. - - - /* - * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower, - * finiteToString, naturalExponential, naturalLogarithm - * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest, - * P.toPrecision, P.toSignificantDigits, toStringBinary, random - * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm - * convertBase toStringBinary, parseOther - * cos P.cos - * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy, - * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction, - * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm, - * taylorSeries, atan2, parseOther - * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh, - * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus, - * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot, - * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed, - * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits, - * P.truncated, divide, getLn10, getPi, naturalExponential, - * naturalLogarithm, ceil, floor, round, trunc - * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf, - * toStringBinary - * getBase10Exponent P.minus, P.plus, P.times, parseOther - * getLn10 P.logarithm, naturalLogarithm - * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2 - * getPrecision P.precision, P.toFraction - * getZeroString digitsToString, finiteToString - * intPow P.toPower, parseOther - * isOdd toLessThanHalfPi - * maxOrMin max, min - * naturalExponential P.naturalExponential, P.toPower - * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm, - * P.toPower, naturalExponential - * nonFiniteToString finiteToString, toStringBinary - * parseDecimal Decimal - * parseOther Decimal - * sin P.sin - * taylorSeries P.cosh, P.sinh, cos, sin - * toLessThanHalfPi P.cos, P.sin - * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal - * truncate intPow - * - * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi, - * naturalLogarithm, config, parseOther, random, Decimal - */ - - - function digitsToString(d) { - var i, k, ws, - indexOfLastWord = d.length - 1, - str = '', - w = d[0]; - - if (indexOfLastWord > 0) { - str += w; - for (i = 1; i < indexOfLastWord; i++) { - ws = d[i] + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - str += ws; - } - - w = d[i]; - ws = w + ''; - k = LOG_BASE - ws.length; - if (k) str += getZeroString(k); - } else if (w === 0) { - return '0'; - } - - // Remove trailing zeros of last w. - for (; w % 10 === 0;) w /= 10; - - return str + w; - } - - - function checkInt32(i, min, max) { - if (i !== ~~i || i < min || i > max) { - throw Error(invalidArgument + i); - } - } - - - /* - * Check 5 rounding digits if `repeating` is null, 4 otherwise. - * `repeating == null` if caller is `log` or `pow`, - * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`. - */ - function checkRoundingDigits(d, i, rm, repeating) { - var di, k, r, rd; - - // Get the length of the first word of the array d. - for (k = d[0]; k >= 10; k /= 10) --i; - - // Is the rounding digit in the first word of d? - if (--i < 0) { - i += LOG_BASE; - di = 0; - } else { - di = Math.ceil((i + 1) / LOG_BASE); - i %= LOG_BASE; - } - - // i is the index (0 - 6) of the rounding digit. - // E.g. if within the word 3487563 the first rounding digit is 5, - // then i = 4, k = 1000, rd = 3487563 % 1000 = 563 - k = mathpow(10, LOG_BASE - i); - rd = d[di] % k | 0; - - if (repeating == null) { - if (i < 3) { - if (i == 0) rd = rd / 100 | 0; - else if (i == 1) rd = rd / 10 | 0; - r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0; - } else { - r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) && - (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 || - (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0; - } - } else { - if (i < 4) { - if (i == 0) rd = rd / 1000 | 0; - else if (i == 1) rd = rd / 100 | 0; - else if (i == 2) rd = rd / 10 | 0; - r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999; - } else { - r = ((repeating || rm < 4) && rd + 1 == k || - (!repeating && rm > 3) && rd + 1 == k / 2) && - (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1; - } - } - - return r; - } - - - // Convert string of `baseIn` to an array of numbers of `baseOut`. - // Eg. convertBase('255', 10, 16) returns [15, 15]. - // Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. - function convertBase(str, baseIn, baseOut) { - var j, - arr = [0], - arrL, - i = 0, - strL = str.length; - - for (; i < strL;) { - for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn; - arr[0] += NUMERALS.indexOf(str.charAt(i++)); - for (j = 0; j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] === void 0) arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - - return arr.reverse(); - } - - - /* - * cos(x) = 1 - x^2/2! + x^4/4! - ... - * |x| < pi/2 - * - */ - function cosine(Ctor, x) { - var k, y, - len = x.d.length; - - // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1 - // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1 - - // Estimate the optimum number of times to use the argument reduction. - if (len < 32) { - k = Math.ceil(len / 3); - y = (1 / tinyPow(4, k)).toString(); - } else { - k = 16; - y = '2.3283064365386962890625e-10'; - } - - Ctor.precision += k; - - x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1)); - - // Reverse argument reduction - for (var i = k; i--;) { - var cos2x = x.times(x); - x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1); - } - - Ctor.precision -= k; - - return x; - } - - - /* - * Perform division in the specified base. - */ - var divide = (function () { - - // Assumes non-zero x and k, and hence non-zero result. - function multiplyInteger(x, k, base) { - var temp, - carry = 0, - i = x.length; - - for (x = x.slice(); i--;) { - temp = x[i] * k + carry; - x[i] = temp % base | 0; - carry = temp / base | 0; - } - - if (carry) x.unshift(carry); - - return x; - } - - function compare(a, b, aL, bL) { - var i, r; - - if (aL != bL) { - r = aL > bL ? 1 : -1; - } else { - for (i = r = 0; i < aL; i++) { - if (a[i] != b[i]) { - r = a[i] > b[i] ? 1 : -1; - break; - } - } - } - - return r; - } - - function subtract(a, b, aL, base) { - var i = 0; - - // Subtract b from a. - for (; aL--;) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - - // Remove leading zeros. - for (; !a[0] && a.length > 1;) a.shift(); - } - - return function (x, y, pr, rm, dp, base) { - var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, - yL, yz, - Ctor = x.constructor, - sign = x.s == y.s ? 1 : -1, - xd = x.d, - yd = y.d; - - // Either NaN, Infinity or 0? - if (!xd || !xd[0] || !yd || !yd[0]) { - - return new Ctor(// Return NaN if either NaN, or both Infinity or 0. - !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN : - - // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0. - xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0); - } - - if (base) { - logBase = 1; - e = x.e - y.e; - } else { - base = BASE; - logBase = LOG_BASE; - e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase); - } - - yL = yd.length; - xL = xd.length; - q = new Ctor(sign); - qd = q.d = []; - - // Result exponent may be one less than e. - // The digit array of a Decimal from toStringBinary may have trailing zeros. - for (i = 0; yd[i] == (xd[i] || 0); i++); - - if (yd[i] > (xd[i] || 0)) e--; - - if (pr == null) { - sd = pr = Ctor.precision; - rm = Ctor.rounding; - } else if (dp) { - sd = pr + (x.e - y.e) + 1; - } else { - sd = pr; - } - - if (sd < 0) { - qd.push(1); - more = true; - } else { - - // Convert precision in number of base 10 digits to base 1e7 digits. - sd = sd / logBase + 2 | 0; - i = 0; - - // divisor < 1e7 - if (yL == 1) { - k = 0; - yd = yd[0]; - sd++; - - // k is the carry. - for (; (i < xL || k) && sd--; i++) { - t = k * base + (xd[i] || 0); - qd[i] = t / yd | 0; - k = t % yd | 0; - } - - more = k || i < xL; - - // divisor >= 1e7 - } else { - - // Normalise xd and yd so highest order digit of yd is >= base/2 - k = base / (yd[0] + 1) | 0; - - if (k > 1) { - yd = multiplyInteger(yd, k, base); - xd = multiplyInteger(xd, k, base); - yL = yd.length; - xL = xd.length; - } - - xi = yL; - rem = xd.slice(0, yL); - remL = rem.length; - - // Add zeros to make remainder as long as divisor. - for (; remL < yL;) rem[remL++] = 0; - - yz = yd.slice(); - yz.unshift(0); - yd0 = yd[0]; - - if (yd[1] >= base / 2) ++yd0; - - do { - k = 0; - - // Compare divisor and remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < remainder. - if (cmp < 0) { - - // Calculate trial digit, k. - rem0 = rem[0]; - if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - - // k will be how many times the divisor goes into the current remainder. - k = rem0 / yd0 | 0; - - // Algorithm: - // 1. product = divisor * trial digit (k) - // 2. if product > remainder: product -= divisor, k-- - // 3. remainder -= product - // 4. if product was < remainder at 2: - // 5. compare new remainder and divisor - // 6. If remainder > divisor: remainder -= divisor, k++ - - if (k > 1) { - if (k >= base) k = base - 1; - - // product = divisor * trial digit. - prod = multiplyInteger(yd, k, base); - prodL = prod.length; - remL = rem.length; - - // Compare product and remainder. - cmp = compare(prod, rem, prodL, remL); - - // product > remainder. - if (cmp == 1) { - k--; - - // Subtract divisor from product. - subtract(prod, yL < prodL ? yz : yd, prodL, base); - } - } else { - - // cmp is -1. - // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1 - // to avoid it. If k is 1 there is a need to compare yd and rem again below. - if (k == 0) cmp = k = 1; - prod = yd.slice(); - } - - prodL = prod.length; - if (prodL < remL) prod.unshift(0); - - // Subtract product from remainder. - subtract(rem, prod, remL, base); - - // If product was < previous remainder. - if (cmp == -1) { - remL = rem.length; - - // Compare divisor and new remainder. - cmp = compare(yd, rem, yL, remL); - - // If divisor < new remainder, subtract divisor from remainder. - if (cmp < 1) { - k++; - - // Subtract divisor from remainder. - subtract(rem, yL < remL ? yz : yd, remL, base); - } - } - - remL = rem.length; - } else if (cmp === 0) { - k++; - rem = [0]; - } // if cmp === 1, k will be 0 - - // Add the next digit, k, to the result array. - qd[i++] = k; - - // Update the remainder. - if (cmp && rem[0]) { - rem[remL++] = xd[xi] || 0; - } else { - rem = [xd[xi]]; - remL = 1; - } - - } while ((xi++ < xL || rem[0] !== void 0) && sd--); - - more = rem[0] !== void 0; - } - - // Leading zero? - if (!qd[0]) qd.shift(); - } - - // logBase is 1 when divide is being used for base conversion. - if (logBase == 1) { - q.e = e; - inexact = more; - } else { - - // To calculate q.e, first get the number of digits of qd[0]. - for (i = 1, k = qd[0]; k >= 10; k /= 10) i++; - q.e = i + e * logBase - 1; - - finalise(q, dp ? pr + q.e + 1 : pr, rm, more); - } - - return q; - }; - })(); - - - /* - * Round `x` to `sd` significant digits using rounding mode `rm`. - * Check for over/under-flow. - */ - function finalise(x, sd, rm, isTruncated) { - var digits, i, j, k, rd, roundUp, w, xd, xdi, - Ctor = x.constructor; - - // Don't round if sd is null or undefined. - out: if (sd != null) { - xd = x.d; - - // Infinity/NaN. - if (!xd) return x; - - // rd: the rounding digit, i.e. the digit after the digit that may be rounded up. - // w: the word of xd containing rd, a base 1e7 number. - // xdi: the index of w within xd. - // digits: the number of digits of w. - // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if - // they had leading zeros) - // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero). - - // Get the length of the first word of the digits array xd. - for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++; - i = sd - digits; - - // Is the rounding digit in the first word of xd? - if (i < 0) { - i += LOG_BASE; - j = sd; - w = xd[xdi = 0]; - - // Get the rounding digit at index j of w. - rd = w / mathpow(10, digits - j - 1) % 10 | 0; - } else { - xdi = Math.ceil((i + 1) / LOG_BASE); - k = xd.length; - if (xdi >= k) { - if (isTruncated) { - - // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`. - for (; k++ <= xdi;) xd.push(0); - w = rd = 0; - digits = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; - } else { - break out; - } - } else { - w = k = xd[xdi]; - - // Get the number of digits of w. - for (digits = 1; k >= 10; k /= 10) digits++; - - // Get the index of rd within w. - i %= LOG_BASE; - - // Get the index of rd within w, adjusted for leading zeros. - // The number of leading zeros of w is given by LOG_BASE - digits. - j = i - LOG_BASE + digits; - - // Get the rounding digit at index j of w. - rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0; - } - } - - // Are there any non-zero digits after the rounding digit? - isTruncated = isTruncated || sd < 0 || - xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1)); - - // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right - // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression - // will give 714. - - roundUp = rm < 4 - ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) - : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 && - - // Check whether the digit to the left of the rounding digit is odd. - ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 || - rm == (x.s < 0 ? 8 : 7)); - - if (sd < 1 || !xd[0]) { - xd.length = 0; - if (roundUp) { - - // Convert sd to decimal places. - sd -= x.e + 1; - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE); - x.e = -sd || 0; - } else { - - // Zero. - xd[0] = x.e = 0; - } - - return x; - } - - // Remove excess digits. - if (i == 0) { - xd.length = xdi; - k = 1; - xdi--; - } else { - xd.length = xdi + 1; - k = mathpow(10, LOG_BASE - i); - - // E.g. 56700 becomes 56000 if 7 is the rounding digit. - // j > 0 means i > number of leading zeros of w. - xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0; - } - - if (roundUp) { - for (;;) { - - // Is the digit to be rounded up in the first word of xd? - if (xdi == 0) { - - // i will be the length of xd[0] before k is added. - for (i = 1, j = xd[0]; j >= 10; j /= 10) i++; - j = xd[0] += k; - for (k = 1; j >= 10; j /= 10) k++; - - // if i != k the length has increased. - if (i != k) { - x.e++; - if (xd[0] == BASE) xd[0] = 1; - } - - break; - } else { - xd[xdi] += k; - if (xd[xdi] != BASE) break; - xd[xdi--] = 0; - k = 1; - } - } - } - - // Remove trailing zeros. - for (i = xd.length; xd[--i] === 0;) xd.pop(); - } - - if (external) { - - // Overflow? - if (x.e > Ctor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < Ctor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // Ctor.underflow = true; - } // else Ctor.underflow = false; - } - - return x; - } - - - function finiteToString(x, isExp, sd) { - if (!x.isFinite()) return nonFiniteToString(x); - var k, - e = x.e, - str = digitsToString(x.d), - len = str.length; - - if (isExp) { - if (sd && (k = sd - len) > 0) { - str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k); - } else if (len > 1) { - str = str.charAt(0) + '.' + str.slice(1); - } - - str = str + (x.e < 0 ? 'e' : 'e+') + x.e; - } else if (e < 0) { - str = '0.' + getZeroString(-e - 1) + str; - if (sd && (k = sd - len) > 0) str += getZeroString(k); - } else if (e >= len) { - str += getZeroString(e + 1 - len); - if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k); - } else { - if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k); - if (sd && (k = sd - len) > 0) { - if (e + 1 === len) str += '.'; - str += getZeroString(k); - } - } - - return str; - } - - - // Calculate the base 10 exponent from the base 1e7 exponent. - function getBase10Exponent(digits, e) { - var w = digits[0]; - - // Add the number of digits of the first word of the digits array. - for ( e *= LOG_BASE; w >= 10; w /= 10) e++; - return e; - } - - - function getLn10(Ctor, sd, pr) { - if (sd > LN10_PRECISION) { - - // Reset global state in case the exception is caught. - external = true; - if (pr) Ctor.precision = pr; - throw Error(precisionLimitExceeded); - } - return finalise(new Ctor(LN10), sd, 1, true); - } - - - function getPi(Ctor, sd, rm) { - if (sd > PI_PRECISION) throw Error(precisionLimitExceeded); - return finalise(new Ctor(PI), sd, rm, true); - } - - - function getPrecision(digits) { - var w = digits.length - 1, - len = w * LOG_BASE + 1; - - w = digits[w]; - - // If non-zero... - if (w) { - - // Subtract the number of trailing zeros of the last word. - for (; w % 10 == 0; w /= 10) len--; - - // Add the number of digits of the first word. - for (w = digits[0]; w >= 10; w /= 10) len++; - } - - return len; - } - - - function getZeroString(k) { - var zs = ''; - for (; k--;) zs += '0'; - return zs; - } - - - /* - * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an - * integer of type number. - * - * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`. - * - */ - function intPow(Ctor, x, n, pr) { - var isTruncated, - r = new Ctor(1), - - // Max n of 9007199254740991 takes 53 loop iterations. - // Maximum digits array length; leaves [28, 34] guard digits. - k = Math.ceil(pr / LOG_BASE + 4); - - external = false; - - for (;;) { - if (n % 2) { - r = r.times(x); - if (truncate(r.d, k)) isTruncated = true; - } - - n = mathfloor(n / 2); - if (n === 0) { - - // To ensure correct rounding when r.d is truncated, increment the last word if it is zero. - n = r.d.length - 1; - if (isTruncated && r.d[n] === 0) ++r.d[n]; - break; - } - - x = x.times(x); - truncate(x.d, k); - } - - external = true; - - return r; - } - - - function isOdd(n) { - return n.d[n.d.length - 1] & 1; - } - - - /* - * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'. - */ - function maxOrMin(Ctor, args, ltgt) { - var y, - x = new Ctor(args[0]), - i = 0; - - for (; ++i < args.length;) { - y = new Ctor(args[i]); - if (!y.s) { - x = y; - break; - } else if (x[ltgt](y)) { - x = y; - } - } - - return x; - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant - * digits. - * - * Taylor/Maclaurin series. - * - * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ... - * - * Argument reduction: - * Repeat x = x / 32, k += 5, until |x| < 0.1 - * exp(x) = exp(x / 2^k)^(2^k) - * - * Previously, the argument was initially reduced by - * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10) - * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was - * found to be slower than just dividing repeatedly by 32 as above. - * - * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000 - * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000 - * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324) - * - * exp(Infinity) = Infinity - * exp(-Infinity) = 0 - * exp(NaN) = NaN - * exp(±0) = 1 - * - * exp(x) is non-terminating for any finite, non-zero x. - * - * The result will always be correctly rounded. - * - */ - function naturalExponential(x, sd) { - var denominator, guard, j, pow, sum, t, wpr, - rep = 0, - i = 0, - k = 0, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // 0/NaN/Infinity? - if (!x.d || !x.d[0] || x.e > 17) { - - return new Ctor(x.d - ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0 - : x.s ? x.s < 0 ? 0 : x : 0 / 0); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - t = new Ctor(0.03125); - - // while abs(x) >= 0.1 - while (x.e > -2) { - - // x = x / 2^5 - x = x.times(t); - k += 5; - } - - // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision - // necessary to ensure the first 4 rounding digits are correct. - guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0; - wpr += guard; - denominator = pow = sum = new Ctor(1); - Ctor.precision = wpr; - - for (;;) { - pow = finalise(pow.times(x), wpr, 1); - denominator = denominator.times(++i); - t = sum.plus(divide(pow, denominator, wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - j = k; - while (j--) sum = finalise(sum.times(sum), wpr, 1); - - // Check to see if the first 4 rounding digits are [49]999. - // If so, repeat the summation with a higher precision, otherwise - // e.g. with precision: 18, rounding: 1 - // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123) - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - - if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += 10; - denominator = pow = t = new Ctor(1); - i = 0; - rep++; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - } - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant - * digits. - * - * ln(-n) = NaN - * ln(0) = -Infinity - * ln(-0) = -Infinity - * ln(1) = 0 - * ln(Infinity) = Infinity - * ln(-Infinity) = NaN - * ln(NaN) = NaN - * - * ln(n) (n != 1) is non-terminating. - * - */ - function naturalLogarithm(y, sd) { - var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2, - n = 1, - guard = 10, - x = y, - xd = x.d, - Ctor = x.constructor, - rm = Ctor.rounding, - pr = Ctor.precision; - - // Is x negative or Infinity, NaN, 0 or 1? - if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) { - return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x); - } - - if (sd == null) { - external = false; - wpr = pr; - } else { - wpr = sd; - } - - Ctor.precision = wpr += guard; - c = digitsToString(xd); - c0 = c.charAt(0); - - if (Math.abs(e = x.e) < 1.5e15) { - - // Argument reduction. - // The series converges faster the closer the argument is to 1, so using - // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b - // multiply the argument by itself until the leading digits of the significand are 7, 8, 9, - // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can - // later be divided by this number, then separate out the power of 10 using - // ln(a*10^b) = ln(a) + b*ln(10). - - // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14). - //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) { - // max n is 6 (gives 0.7 - 1.3) - while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) { - x = x.times(y); - c = digitsToString(x.d); - c0 = c.charAt(0); - n++; - } - - e = x.e; - - if (c0 > 1) { - x = new Ctor('0.' + c); - e++; - } else { - x = new Ctor(c0 + '.' + c.slice(1)); - } - } else { - - // The argument reduction method above may result in overflow if the argument y is a massive - // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this - // function using ln(x*10^e) = ln(x) + e*ln(10). - t = getLn10(Ctor, wpr + 2, pr).times(e + ''); - x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t); - Ctor.precision = pr; - - return sd == null ? finalise(x, pr, rm, external = true) : x; - } - - // x1 is x reduced to a value near 1. - x1 = x; - - // Taylor series. - // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...) - // where x = (y - 1)/(y + 1) (|x| < 1) - sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = 3; - - for (;;) { - numerator = finalise(numerator.times(x2), wpr, 1); - t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1)); - - if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) { - sum = sum.times(2); - - // Reverse the argument reduction. Check that e is not 0 because, besides preventing an - // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0. - if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + '')); - sum = divide(sum, new Ctor(n), wpr, 1); - - // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has - // been repeated previously) and the first 4 rounding digits 9999? - // If so, restart the summation with a higher precision, otherwise - // e.g. with precision: 12, rounding: 1 - // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463. - // `wpr - guard` is the index of first rounding digit. - if (sd == null) { - if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) { - Ctor.precision = wpr += guard; - t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1); - x2 = finalise(x.times(x), wpr, 1); - denominator = rep = 1; - } else { - return finalise(sum, Ctor.precision = pr, rm, external = true); - } - } else { - Ctor.precision = pr; - return sum; - } - } - - sum = t; - denominator += 2; - } - } - - - // ±Infinity, NaN. - function nonFiniteToString(x) { - // Unsigned. - return String(x.s * x.s / 0); - } - - - /* - * Parse the value of a new Decimal `x` from string `str`. - */ - function parseDecimal(x, str) { - var e, i, len; - - // Decimal point? - if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); - - // Exponential form? - if ((i = str.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e < 0) { - - // Integer. - e = str.length; - } - - // Determine leading zeros. - for (i = 0; str.charCodeAt(i) === 48; i++); - - // Determine trailing zeros. - for (len = str.length; str.charCodeAt(len - 1) === 48; --len); - str = str.slice(i, len); - - if (str) { - len -= i; - x.e = e = e - i - 1; - x.d = []; - - // Transform base - - // e is the base 10 exponent. - // i is where to slice str to get the first word of the digits array. - i = (e + 1) % LOG_BASE; - if (e < 0) i += LOG_BASE; - - if (i < len) { - if (i) x.d.push(+str.slice(0, i)); - for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE)); - str = str.slice(i); - i = LOG_BASE - str.length; - } else { - i -= len; - } - - for (; i--;) str += '0'; - x.d.push(+str); - - if (external) { - - // Overflow? - if (x.e > x.constructor.maxE) { - - // Infinity. - x.d = null; - x.e = NaN; - - // Underflow? - } else if (x.e < x.constructor.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - // x.constructor.underflow = true; - } // else x.constructor.underflow = false; - } - } else { - - // Zero. - x.e = 0; - x.d = [0]; - } - - return x; - } - - - /* - * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value. - */ - function parseOther(x, str) { - var base, Ctor, divisor, i, isFloat, len, p, xd, xe; - - if (str === 'Infinity' || str === 'NaN') { - if (!+str) x.s = NaN; - x.e = NaN; - x.d = null; - return x; - } - - if (isHex.test(str)) { - base = 16; - str = str.toLowerCase(); - } else if (isBinary.test(str)) { - base = 2; - } else if (isOctal.test(str)) { - base = 8; - } else { - throw Error(invalidArgument + str); - } - - // Is there a binary exponent part? - i = str.search(/p/i); - - if (i > 0) { - p = +str.slice(i + 1); - str = str.substring(2, i); - } else { - str = str.slice(2); - } - - // Convert `str` as an integer then divide the result by `base` raised to a power such that the - // fraction part will be restored. - i = str.indexOf('.'); - isFloat = i >= 0; - Ctor = x.constructor; - - if (isFloat) { - str = str.replace('.', ''); - len = str.length; - i = len - i; - - // log[10](16) = 1.2041... , log[10](88) = 1.9444.... - divisor = intPow(Ctor, new Ctor(base), i, i * 2); - } - - xd = convertBase(str, base, BASE); - xe = xd.length - 1; - - // Remove trailing zeros. - for (i = xe; xd[i] === 0; --i) xd.pop(); - if (i < 0) return new Ctor(x.s * 0); - x.e = getBase10Exponent(xd, xe); - x.d = xd; - external = false; - - // At what precision to perform the division to ensure exact conversion? - // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount) - // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412 - // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits. - // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount - // Therefore using 4 * the number of digits of str will always be enough. - if (isFloat) x = divide(x, divisor, len * 4); - - // Multiply by the binary exponent part if present. - if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p)); - external = true; - - return x; - } - - - /* - * sin(x) = x - x^3/3! + x^5/5! - ... - * |x| < pi/2 - * - */ - function sine(Ctor, x) { - var k, - len = x.d.length; - - if (len < 3) return taylorSeries(Ctor, 2, x, x); - - // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x) - // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5) - // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20)) - - // Estimate the optimum number of times to use the argument reduction. - k = 1.4 * Math.sqrt(len); - k = k > 16 ? 16 : k | 0; - - x = x.times(1 / tinyPow(5, k)); - x = taylorSeries(Ctor, 2, x, x); - - // Reverse argument reduction - var sin2_x, - d5 = new Ctor(5), - d16 = new Ctor(16), - d20 = new Ctor(20); - for (; k--;) { - sin2_x = x.times(x); - x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20)))); - } - - return x; - } - - - // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`. - function taylorSeries(Ctor, n, x, y, isHyperbolic) { - var j, t, u, x2, - i = 1, - pr = Ctor.precision, - k = Math.ceil(pr / LOG_BASE); - - external = false; - x2 = x.times(x); - u = new Ctor(y); - - for (;;) { - t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1); - u = isHyperbolic ? y.plus(t) : y.minus(t); - y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1); - t = u.plus(y); - - if (t.d[k] !== void 0) { - for (j = k; t.d[j] === u.d[j] && j--;); - if (j == -1) break; - } - - j = u; - u = y; - y = t; - t = j; - i++; - } - - external = true; - t.d.length = k + 1; - - return t; - } - - - // Exponent e must be positive and non-zero. - function tinyPow(b, e) { - var n = b; - while (--e) n *= b; - return n; - } - - - // Return the absolute value of `x` reduced to less than or equal to half pi. - function toLessThanHalfPi(Ctor, x) { - var t, - isNeg = x.s < 0, - pi = getPi(Ctor, Ctor.precision, 1), - halfPi = pi.times(0.5); - - x = x.abs(); - - if (x.lte(halfPi)) { - quadrant = isNeg ? 4 : 1; - return x; - } - - t = x.divToInt(pi); - - if (t.isZero()) { - quadrant = isNeg ? 3 : 2; - } else { - x = x.minus(t.times(pi)); - - // 0 <= x < pi - if (x.lte(halfPi)) { - quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1); - return x; - } - - quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2); - } - - return x.minus(pi).abs(); - } - - - /* - * Return the value of Decimal `x` as a string in base `baseOut`. - * - * If the optional `sd` argument is present include a binary exponent suffix. - */ - function toStringBinary(x, baseOut, sd, rm) { - var base, e, i, k, len, roundUp, str, xd, y, - Ctor = x.constructor, - isExp = sd !== void 0; - - if (isExp) { - checkInt32(sd, 1, MAX_DIGITS); - if (rm === void 0) rm = Ctor.rounding; - else checkInt32(rm, 0, 8); - } else { - sd = Ctor.precision; - rm = Ctor.rounding; - } - - if (!x.isFinite()) { - str = nonFiniteToString(x); - } else { - str = finiteToString(x); - i = str.indexOf('.'); - - // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required: - // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10)) - // minBinaryExponent = floor(decimalExponent * log[2](10)) - // log[2](10) = 3.321928094887362347870319429489390175864 - - if (isExp) { - base = 2; - if (baseOut == 16) { - sd = sd * 4 - 3; - } else if (baseOut == 8) { - sd = sd * 3 - 2; - } - } else { - base = baseOut; - } - - // Convert the number as an integer then divide the result by its base raised to a power such - // that the fraction part will be restored. - - // Non-integer. - if (i >= 0) { - str = str.replace('.', ''); - y = new Ctor(1); - y.e = str.length - i; - y.d = convertBase(finiteToString(y), 10, base); - y.e = y.d.length; - } - - xd = convertBase(str, 10, base); - e = len = xd.length; - - // Remove trailing zeros. - for (; xd[--len] == 0;) xd.pop(); - - if (!xd[0]) { - str = isExp ? '0p+0' : '0'; - } else { - if (i < 0) { - e--; - } else { - x = new Ctor(x); - x.d = xd; - x.e = e; - x = divide(x, y, sd, rm, 0, base); - xd = x.d; - e = x.e; - roundUp = inexact; - } - - // The rounding digit, i.e. the digit after the digit that may be rounded up. - i = xd[sd]; - k = base / 2; - roundUp = roundUp || xd[sd + 1] !== void 0; - - roundUp = rm < 4 - ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2)) - : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 || - rm === (x.s < 0 ? 8 : 7)); - - xd.length = sd; - - if (roundUp) { - - // Rounding up may mean the previous digit has to be rounded up and so on. - for (; ++xd[--sd] > base - 1;) { - xd[sd] = 0; - if (!sd) { - ++e; - xd.unshift(1); - } - } - } - - // Determine trailing zeros. - for (len = xd.length; !xd[len - 1]; --len); - - // E.g. [4, 11, 15] becomes 4bf. - for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]); - - // Add binary exponent suffix? - if (isExp) { - if (len > 1) { - if (baseOut == 16 || baseOut == 8) { - i = baseOut == 16 ? 4 : 3; - for (--len; len % i; len++) str += '0'; - xd = convertBase(str, base, baseOut); - for (len = xd.length; !xd[len - 1]; --len); - - // xd[0] will always be be 1 - for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]); - } else { - str = str.charAt(0) + '.' + str.slice(1); - } - } - - str = str + (e < 0 ? 'p' : 'p+') + e; - } else if (e < 0) { - for (; ++e;) str = '0' + str; - str = '0.' + str; - } else { - if (++e > len) for (e -= len; e-- ;) str += '0'; - else if (e < len) str = str.slice(0, e) + '.' + str.slice(e); - } - } - - str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str; - } - - return x.s < 0 ? '-' + str : str; - } - - - // Does not strip trailing zeros. - function truncate(arr, len) { - if (arr.length > len) { - arr.length = len; - return true; - } - } - - - // Decimal methods - - - /* - * abs - * acos - * acosh - * add - * asin - * asinh - * atan - * atanh - * atan2 - * cbrt - * ceil - * clone - * config - * cos - * cosh - * div - * exp - * floor - * hypot - * ln - * log - * log2 - * log10 - * max - * min - * mod - * mul - * pow - * random - * round - * set - * sign - * sin - * sinh - * sqrt - * sub - * tan - * tanh - * trunc - */ - - - /* - * Return a new Decimal whose value is the absolute value of `x`. - * - * x {number|string|Decimal} - * - */ - function abs(x) { - return new this(x).abs(); - } - - - /* - * Return a new Decimal whose value is the arccosine in radians of `x`. - * - * x {number|string|Decimal} - * - */ - function acos(x) { - return new this(x).acos(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function acosh(x) { - return new this(x).acosh(); - } - - - /* - * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function add(x, y) { - return new this(x).plus(y); - } - - - /* - * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function asin(x) { - return new this(x).asin(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function asinh(x) { - return new this(x).asinh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function atan(x) { - return new this(x).atan(); - } - - - /* - * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to - * `precision` significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function atanh(x) { - return new this(x).atanh(); - } - - - /* - * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi - * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`. - * - * Domain: [-Infinity, Infinity] - * Range: [-pi, pi] - * - * y {number|string|Decimal} The y-coordinate. - * x {number|string|Decimal} The x-coordinate. - * - * atan2(±0, -0) = ±pi - * atan2(±0, +0) = ±0 - * atan2(±0, -x) = ±pi for x > 0 - * atan2(±0, x) = ±0 for x > 0 - * atan2(-y, ±0) = -pi/2 for y > 0 - * atan2(y, ±0) = pi/2 for y > 0 - * atan2(±y, -Infinity) = ±pi for finite y > 0 - * atan2(±y, +Infinity) = ±0 for finite y > 0 - * atan2(±Infinity, x) = ±pi/2 for finite x - * atan2(±Infinity, -Infinity) = ±3*pi/4 - * atan2(±Infinity, +Infinity) = ±pi/4 - * atan2(NaN, x) = NaN - * atan2(y, NaN) = NaN - * - */ - function atan2(y, x) { - y = new this(y); - x = new this(x); - var r, - pr = this.precision, - rm = this.rounding, - wpr = pr + 4; - - // Either NaN - if (!y.s || !x.s) { - r = new this(NaN); - - // Both ±Infinity - } else if (!y.d && !x.d) { - r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); - r.s = y.s; - - // x is ±Infinity or y is ±0 - } else if (!x.d || y.isZero()) { - r = x.s < 0 ? getPi(this, pr, rm) : new this(0); - r.s = y.s; - - // y is ±Infinity or x is ±0 - } else if (!y.d || x.isZero()) { - r = getPi(this, wpr, 1).times(0.5); - r.s = y.s; - - // Both non-zero and finite - } else if (x.s < 0) { - this.precision = wpr; - this.rounding = 1; - r = this.atan(divide(y, x, wpr, 1)); - x = getPi(this, wpr, 1); - this.precision = pr; - this.rounding = rm; - r = y.s < 0 ? r.minus(x) : r.plus(x); - } else { - r = this.atan(divide(y, x, wpr, 1)); - } - - return r; - } - - - /* - * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function cbrt(x) { - return new this(x).cbrt(); - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`. - * - * x {number|string|Decimal} - * - */ - function ceil(x) { - return finalise(x = new this(x), x.e + 1, 2); - } - - - /* - * Configure global settings for a Decimal constructor. - * - * `obj` is an object with one or more of the following properties, - * - * precision {number} - * rounding {number} - * toExpNeg {number} - * toExpPos {number} - * maxE {number} - * minE {number} - * modulo {number} - * crypto {boolean|number} - * defaults {true} - * - * E.g. Decimal.config({ precision: 20, rounding: 4 }) - * - */ - function config(obj) { - if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); - var i, p, v, - useDefaults = obj.defaults === true, - ps = [ - 'precision', 1, MAX_DIGITS, - 'rounding', 0, 8, - 'toExpNeg', -EXP_LIMIT, 0, - 'toExpPos', 0, EXP_LIMIT, - 'maxE', 0, EXP_LIMIT, - 'minE', -EXP_LIMIT, 0, - 'modulo', 0, 9 - ]; - - for (i = 0; i < ps.length; i += 3) { - if (p = ps[i], useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; - else throw Error(invalidArgument + p + ': ' + v); - } - } - - if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p]; - if ((v = obj[p]) !== void 0) { - if (v === true || v === false || v === 0 || v === 1) { - if (v) { - if (typeof crypto != 'undefined' && crypto && - (crypto.getRandomValues || crypto.randomBytes)) { - this[p] = true; - } else { - throw Error(cryptoUnavailable); - } - } else { - this[p] = false; - } - } else { - throw Error(invalidArgument + p + ': ' + v); - } - } - - return this; - } - - - /* - * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cos(x) { - return new this(x).cos(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function cosh(x) { - return new this(x).cosh(); - } - - - /* - * Create and return a Decimal constructor with the same configuration properties as this Decimal - * constructor. - * - */ - function clone(obj) { - var i, p, ps; - - /* - * The Decimal constructor and exported function. - * Return a new Decimal instance. - * - * v {number|string|Decimal} A numeric value. - * - */ - function Decimal(v) { - var e, i, t, - x = this; - - // Decimal called without new. - if (!(x instanceof Decimal)) return new Decimal(v); - - // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor - // which points to Object. - x.constructor = Decimal; - - // Duplicate. - if (v instanceof Decimal) { - x.s = v.s; - - if (external) { - if (!v.d || v.e > Decimal.maxE) { - - // Infinity. - x.e = NaN; - x.d = null; - } else if (v.e < Decimal.minE) { - - // Zero. - x.e = 0; - x.d = [0]; - } else { - x.e = v.e; - x.d = v.d.slice(); - } - } else { - x.e = v.e; - x.d = v.d ? v.d.slice() : v.d; - } - - return; - } - - t = typeof v; - - if (t === 'number') { - if (v === 0) { - x.s = 1 / v < 0 ? -1 : 1; - x.e = 0; - x.d = [0]; - return; - } - - if (v < 0) { - v = -v; - x.s = -1; - } else { - x.s = 1; - } - - // Fast path for small integers. - if (v === ~~v && v < 1e7) { - for (e = 0, i = v; i >= 10; i /= 10) e++; - - if (external) { - if (e > Decimal.maxE) { - x.e = NaN; - x.d = null; - } else if (e < Decimal.minE) { - x.e = 0; - x.d = [0]; - } else { - x.e = e; - x.d = [v]; - } - } else { - x.e = e; - x.d = [v]; - } - - return; - - // Infinity, NaN. - } else if (v * 0 !== 0) { - if (!v) x.s = NaN; - x.e = NaN; - x.d = null; - return; - } - - return parseDecimal(x, v.toString()); - - } else if (t !== 'string') { - throw Error(invalidArgument + v); - } - - // Minus sign? - if ((i = v.charCodeAt(0)) === 45) { - v = v.slice(1); - x.s = -1; - } else { - // Plus sign? - if (i === 43) v = v.slice(1); - x.s = 1; - } - - return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); - } - - Decimal.prototype = P; - - Decimal.ROUND_UP = 0; - Decimal.ROUND_DOWN = 1; - Decimal.ROUND_CEIL = 2; - Decimal.ROUND_FLOOR = 3; - Decimal.ROUND_HALF_UP = 4; - Decimal.ROUND_HALF_DOWN = 5; - Decimal.ROUND_HALF_EVEN = 6; - Decimal.ROUND_HALF_CEIL = 7; - Decimal.ROUND_HALF_FLOOR = 8; - Decimal.EUCLID = 9; - - Decimal.config = Decimal.set = config; - Decimal.clone = clone; - Decimal.isDecimal = isDecimalInstance; - - Decimal.abs = abs; - Decimal.acos = acos; - Decimal.acosh = acosh; // ES6 - Decimal.add = add; - Decimal.asin = asin; - Decimal.asinh = asinh; // ES6 - Decimal.atan = atan; - Decimal.atanh = atanh; // ES6 - Decimal.atan2 = atan2; - Decimal.cbrt = cbrt; // ES6 - Decimal.ceil = ceil; - Decimal.cos = cos; - Decimal.cosh = cosh; // ES6 - Decimal.div = div; - Decimal.exp = exp; - Decimal.floor = floor; - Decimal.hypot = hypot; // ES6 - Decimal.ln = ln; - Decimal.log = log; - Decimal.log10 = log10; // ES6 - Decimal.log2 = log2; // ES6 - Decimal.max = max; - Decimal.min = min; - Decimal.mod = mod; - Decimal.mul = mul; - Decimal.pow = pow; - Decimal.random = random; - Decimal.round = round; - Decimal.sign = sign; // ES6 - Decimal.sin = sin; - Decimal.sinh = sinh; // ES6 - Decimal.sqrt = sqrt; - Decimal.sub = sub; - Decimal.tan = tan; - Decimal.tanh = tanh; // ES6 - Decimal.trunc = trunc; // ES6 - - if (obj === void 0) obj = {}; - if (obj) { - if (obj.defaults !== true) { - ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; - for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; - } - } - - Decimal.config(obj); - - return Decimal; - } - - - /* - * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function div(x, y) { - return new this(x).div(y); - } - - - /* - * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The power to which to raise the base of the natural log. - * - */ - function exp(x) { - return new this(x).exp(); - } - - - /* - * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`. - * - * x {number|string|Decimal} - * - */ - function floor(x) { - return finalise(x = new this(x), x.e + 1, 3); - } - - - /* - * Return a new Decimal whose value is the square root of the sum of the squares of the arguments, - * rounded to `precision` significant digits using rounding mode `rounding`. - * - * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...) - * - * arguments {number|string|Decimal} - * - */ - function hypot() { - var i, n, - t = new this(0); - - external = false; - - for (i = 0; i < arguments.length;) { - n = new this(arguments[i++]); - if (!n.d) { - if (n.s) { - external = true; - return new this(1 / 0); - } - t = n; - } else if (t.d) { - t = t.plus(n.times(n)); - } - } - - external = true; - - return t.sqrt(); - } - - - /* - * Return true if object is a Decimal instance (where Decimal is any Decimal constructor), - * otherwise return false. - * - */ - function isDecimalInstance(obj) { - return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false; - } - - - /* - * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function ln(x) { - return new this(x).ln(); - } - - - /* - * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base - * is specified, rounded to `precision` significant digits using rounding mode `rounding`. - * - * log[y](x) - * - * x {number|string|Decimal} The argument of the logarithm. - * y {number|string|Decimal} The base of the logarithm. - * - */ - function log(x, y) { - return new this(x).log(y); - } - - - /* - * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log2(x) { - return new this(x).log(2); - } - - - /* - * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function log10(x) { - return new this(x).log(10); - } - - - /* - * Return a new Decimal whose value is the maximum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function max() { - return maxOrMin(this, arguments, 'lt'); - } - - - /* - * Return a new Decimal whose value is the minimum of the arguments. - * - * arguments {number|string|Decimal} - * - */ - function min() { - return maxOrMin(this, arguments, 'gt'); - } - - - /* - * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mod(x, y) { - return new this(x).mod(y); - } - - - /* - * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function mul(x, y) { - return new this(x).mul(y); - } - - - /* - * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} The base. - * y {number|string|Decimal} The exponent. - * - */ - function pow(x, y) { - return new this(x).pow(y); - } - - - /* - * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with - * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros - * are produced). - * - * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive. - * - */ - function random(sd) { - var d, e, k, n, - i = 0, - r = new this(1), - rd = []; - - if (sd === void 0) sd = this.precision; - else checkInt32(sd, 1, MAX_DIGITS); - - k = Math.ceil(sd / LOG_BASE); - - if (!this.crypto) { - for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; - - // Browsers supporting crypto.getRandomValues. - } else if (crypto.getRandomValues) { - d = crypto.getRandomValues(new Uint32Array(k)); - - for (; i < k;) { - n = d[i]; - - // 0 <= n < 4294967296 - // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). - if (n >= 4.29e9) { - d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; - } else { - - // 0 <= n <= 4289999999 - // 0 <= (n % 1e7) <= 9999999 - rd[i++] = n % 1e7; - } - } - - // Node.js supporting crypto.randomBytes. - } else if (crypto.randomBytes) { - - // buffer - d = crypto.randomBytes(k *= 4); - - for (; i < k;) { - - // 0 <= n < 2147483648 - n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); - - // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). - if (n >= 2.14e9) { - crypto.randomBytes(4).copy(d, i); - } else { - - // 0 <= n <= 2139999999 - // 0 <= (n % 1e7) <= 9999999 - rd.push(n % 1e7); - i += 4; - } - } - - i = k / 4; - } else { - throw Error(cryptoUnavailable); - } - - k = rd[--i]; - sd %= LOG_BASE; - - // Convert trailing digits to zeros according to sd. - if (k && sd) { - n = mathpow(10, LOG_BASE - sd); - rd[i] = (k / n | 0) * n; - } - - // Remove trailing words which are zero. - for (; rd[i] === 0; i--) rd.pop(); - - // Zero? - if (i < 0) { - e = 0; - rd = [0]; - } else { - e = -1; - - // Remove leading words which are zero and adjust exponent accordingly. - for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); - - // Count the digits of the first word of rd to determine leading zeros. - for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; - - // Adjust the exponent for leading zeros of the first word of rd. - if (k < LOG_BASE) e -= LOG_BASE - k; - } - - r.e = e; - r.d = rd; - - return r; - } - - - /* - * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`. - * - * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL). - * - * x {number|string|Decimal} - * - */ - function round(x) { - return finalise(x = new this(x), x.e + 1, this.rounding); - } - - - /* - * Return - * 1 if x > 0, - * -1 if x < 0, - * 0 if x is 0, - * -0 if x is -0, - * NaN otherwise - * - * x {number|string|Decimal} - * - */ - function sign(x) { - x = new this(x); - return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; - } - - - /* - * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sin(x) { - return new this(x).sin(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function sinh(x) { - return new this(x).sinh(); - } - - - /* - * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} - * - */ - function sqrt(x) { - return new this(x).sqrt(); - } - - - /* - * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits - * using rounding mode `rounding`. - * - * x {number|string|Decimal} - * y {number|string|Decimal} - * - */ - function sub(x, y) { - return new this(x).sub(y); - } - - - /* - * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant - * digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tan(x) { - return new this(x).tan(); - } - - - /* - * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision` - * significant digits using rounding mode `rounding`. - * - * x {number|string|Decimal} A value in radians. - * - */ - function tanh(x) { - return new this(x).tanh(); - } - - - /* - * Return a new Decimal whose value is `x` truncated to an integer. - * - * x {number|string|Decimal} - * - */ - function trunc(x) { - return finalise(x = new this(x), x.e + 1, 1); - } - - - // Create and configure initial Decimal constructor. - Decimal = clone(DEFAULTS); - - Decimal['default'] = Decimal.Decimal = Decimal; - - // Create the internal constants from their string values. - LN10 = new Decimal(LN10); - PI = new Decimal(PI); - - - // Export. - - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { - return Decimal; - }); - - // Node and other environments that support module.exports. - } else if ( true && module.exports) { - if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') { - P[Symbol.for('nodejs.util.inspect.custom')] = P.toString; - P[Symbol.toStringTag] = 'Decimal'; - } - - module.exports = Decimal; - - // Browser. - } else { - if (!globalScope) { - globalScope = typeof self != 'undefined' && self && self.self == self ? self : window; - } - - noConflict = globalScope.Decimal; - Decimal.noConflict = function () { - globalScope.Decimal = noConflict; - return Decimal; - }; - - globalScope.Decimal = Decimal; - } -})(this); - - /***/ }), /***/ 18611: @@ -232136,764 +218624,6 @@ class Deprecation extends Error { exports.Deprecation = Deprecation; -/***/ }), - -/***/ 85589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const legacyErrorCodes = __nccwpck_require__(34370); -const idlUtils = __nccwpck_require__(69497); - -exports.implementation = class DOMExceptionImpl { - constructor(globalObject, [message, name]) { - this.name = name; - this.message = message; - } - - get code() { - return legacyErrorCodes[this.name] || 0; - } -}; - -// A proprietary V8 extension that causes the stack property to appear. -exports.init = impl => { - if (Error.captureStackTrace) { - const wrapper = idlUtils.wrapperForImpl(impl); - Error.captureStackTrace(wrapper, wrapper.constructor); - } -}; - - -/***/ }), - -/***/ 37561: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const conversions = __nccwpck_require__(19463); -const utils = __nccwpck_require__(69497); - -const impl = utils.implSymbol; -const ctorRegistry = utils.ctorRegistrySymbol; - -const iface = { - // When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()` - // method into this array. It allows objects that directly implements *those* interfaces to be recognized as - // implementing this mixin interface. - _mixedIntoPredicates: [], - is(obj) { - if (obj) { - if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) { - return true; - } - for (const isMixedInto of module.exports._mixedIntoPredicates) { - if (isMixedInto(obj)) { - return true; - } - } - } - return false; - }, - isImpl(obj) { - if (obj) { - if (obj instanceof Impl.implementation) { - return true; - } - - const wrapper = utils.wrapperForImpl(obj); - for (const isMixedInto of module.exports._mixedIntoPredicates) { - if (isMixedInto(wrapper)) { - return true; - } - } - } - return false; - }, - convert(obj, { context = "The provided value" } = {}) { - if (module.exports.is(obj)) { - return utils.implForWrapper(obj); - } - throw new TypeError(`${context} is not of type 'DOMException'.`); - }, - - create(globalObject, constructorArgs, privateData) { - if (globalObject[ctorRegistry] === undefined) { - throw new Error("Internal error: invalid global object"); - } - - const ctor = globalObject[ctorRegistry]["DOMException"]; - if (ctor === undefined) { - throw new Error("Internal error: constructor DOMException is not installed on the passed global object"); - } - - let obj = Object.create(ctor.prototype); - obj = iface.setup(obj, globalObject, constructorArgs, privateData); - return obj; - }, - createImpl(globalObject, constructorArgs, privateData) { - const obj = iface.create(globalObject, constructorArgs, privateData); - return utils.implForWrapper(obj); - }, - _internalSetup(obj) {}, - setup(obj, globalObject, constructorArgs = [], privateData = {}) { - privateData.wrapper = obj; - - iface._internalSetup(obj); - Object.defineProperty(obj, impl, { - value: new Impl.implementation(globalObject, constructorArgs, privateData), - configurable: true - }); - - obj[impl][utils.wrapperSymbol] = obj; - if (Impl.init) { - Impl.init(obj[impl], privateData); - } - return obj; - }, - - install(globalObject) { - class DOMException { - constructor() { - const args = []; - { - let curArg = arguments[0]; - if (curArg !== undefined) { - curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 1" }); - } else { - curArg = ""; - } - args.push(curArg); - } - { - let curArg = arguments[1]; - if (curArg !== undefined) { - curArg = conversions["DOMString"](curArg, { context: "Failed to construct 'DOMException': parameter 2" }); - } else { - curArg = "Error"; - } - args.push(curArg); - } - return iface.setup(Object.create(new.target.prototype), globalObject, args); - } - - get name() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - - return this[impl]["name"]; - } - - get message() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - - return this[impl]["message"]; - } - - get code() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - - return this[impl]["code"]; - } - } - Object.defineProperties(DOMException.prototype, { - name: { enumerable: true }, - message: { enumerable: true }, - code: { enumerable: true }, - [Symbol.toStringTag]: { value: "DOMException", configurable: true }, - INDEX_SIZE_ERR: { value: 1, enumerable: true }, - DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, - HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, - WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, - INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, - NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, - NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, - NOT_FOUND_ERR: { value: 8, enumerable: true }, - NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, - INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, - INVALID_STATE_ERR: { value: 11, enumerable: true }, - SYNTAX_ERR: { value: 12, enumerable: true }, - INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, - NAMESPACE_ERR: { value: 14, enumerable: true }, - INVALID_ACCESS_ERR: { value: 15, enumerable: true }, - VALIDATION_ERR: { value: 16, enumerable: true }, - TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, - SECURITY_ERR: { value: 18, enumerable: true }, - NETWORK_ERR: { value: 19, enumerable: true }, - ABORT_ERR: { value: 20, enumerable: true }, - URL_MISMATCH_ERR: { value: 21, enumerable: true }, - QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, - TIMEOUT_ERR: { value: 23, enumerable: true }, - INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, - DATA_CLONE_ERR: { value: 25, enumerable: true } - }); - Object.defineProperties(DOMException, { - INDEX_SIZE_ERR: { value: 1, enumerable: true }, - DOMSTRING_SIZE_ERR: { value: 2, enumerable: true }, - HIERARCHY_REQUEST_ERR: { value: 3, enumerable: true }, - WRONG_DOCUMENT_ERR: { value: 4, enumerable: true }, - INVALID_CHARACTER_ERR: { value: 5, enumerable: true }, - NO_DATA_ALLOWED_ERR: { value: 6, enumerable: true }, - NO_MODIFICATION_ALLOWED_ERR: { value: 7, enumerable: true }, - NOT_FOUND_ERR: { value: 8, enumerable: true }, - NOT_SUPPORTED_ERR: { value: 9, enumerable: true }, - INUSE_ATTRIBUTE_ERR: { value: 10, enumerable: true }, - INVALID_STATE_ERR: { value: 11, enumerable: true }, - SYNTAX_ERR: { value: 12, enumerable: true }, - INVALID_MODIFICATION_ERR: { value: 13, enumerable: true }, - NAMESPACE_ERR: { value: 14, enumerable: true }, - INVALID_ACCESS_ERR: { value: 15, enumerable: true }, - VALIDATION_ERR: { value: 16, enumerable: true }, - TYPE_MISMATCH_ERR: { value: 17, enumerable: true }, - SECURITY_ERR: { value: 18, enumerable: true }, - NETWORK_ERR: { value: 19, enumerable: true }, - ABORT_ERR: { value: 20, enumerable: true }, - URL_MISMATCH_ERR: { value: 21, enumerable: true }, - QUOTA_EXCEEDED_ERR: { value: 22, enumerable: true }, - TIMEOUT_ERR: { value: 23, enumerable: true }, - INVALID_NODE_TYPE_ERR: { value: 24, enumerable: true }, - DATA_CLONE_ERR: { value: 25, enumerable: true } - }); - if (globalObject[ctorRegistry] === undefined) { - globalObject[ctorRegistry] = Object.create(null); - } - globalObject[ctorRegistry]["DOMException"] = DOMException; - - Object.defineProperty(globalObject, "DOMException", { - configurable: true, - writable: true, - value: DOMException - }); - } -}; // iface -module.exports = iface; - -const Impl = __nccwpck_require__(85589); - - -/***/ }), - -/***/ 69497: -/***/ ((module, exports) => { - -"use strict"; - - -// Returns "Type(value) is Object" in ES terminology. -function isObject(value) { - return typeof value === "object" && value !== null || typeof value === "function"; -} - -function hasOwn(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -const wrapperSymbol = Symbol("wrapper"); -const implSymbol = Symbol("impl"); -const sameObjectCaches = Symbol("SameObject caches"); -const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry"); - -function getSameObject(wrapper, prop, creator) { - if (!wrapper[sameObjectCaches]) { - wrapper[sameObjectCaches] = Object.create(null); - } - - if (prop in wrapper[sameObjectCaches]) { - return wrapper[sameObjectCaches][prop]; - } - - wrapper[sameObjectCaches][prop] = creator(); - return wrapper[sameObjectCaches][prop]; -} - -function wrapperForImpl(impl) { - return impl ? impl[wrapperSymbol] : null; -} - -function implForWrapper(wrapper) { - return wrapper ? wrapper[implSymbol] : null; -} - -function tryWrapperForImpl(impl) { - const wrapper = wrapperForImpl(impl); - return wrapper ? wrapper : impl; -} - -function tryImplForWrapper(wrapper) { - const impl = implForWrapper(wrapper); - return impl ? impl : wrapper; -} - -const iterInternalSymbol = Symbol("internal"); -const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); - -function isArrayIndexPropName(P) { - if (typeof P !== "string") { - return false; - } - const i = P >>> 0; - if (i === Math.pow(2, 32) - 1) { - return false; - } - const s = `${i}`; - if (P !== s) { - return false; - } - return true; -} - -const byteLengthGetter = - Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; -function isArrayBuffer(value) { - try { - byteLengthGetter.call(value); - return true; - } catch (e) { - return false; - } -} - -const supportsPropertyIndex = Symbol("supports property index"); -const supportedPropertyIndices = Symbol("supported property indices"); -const supportsPropertyName = Symbol("supports property name"); -const supportedPropertyNames = Symbol("supported property names"); -const indexedGet = Symbol("indexed property get"); -const indexedSetNew = Symbol("indexed property set new"); -const indexedSetExisting = Symbol("indexed property set existing"); -const namedGet = Symbol("named property get"); -const namedSetNew = Symbol("named property set new"); -const namedSetExisting = Symbol("named property set existing"); -const namedDelete = Symbol("named property delete"); - -module.exports = exports = { - isObject, - hasOwn, - wrapperSymbol, - implSymbol, - getSameObject, - ctorRegistrySymbol, - wrapperForImpl, - implForWrapper, - tryWrapperForImpl, - tryImplForWrapper, - iterInternalSymbol, - IteratorPrototype, - isArrayBuffer, - isArrayIndexPropName, - supportsPropertyIndex, - supportedPropertyIndices, - supportsPropertyName, - supportedPropertyNames, - indexedGet, - indexedSetNew, - indexedSetExisting, - namedGet, - namedSetNew, - namedSetExisting, - namedDelete -}; - - -/***/ }), - -/***/ 19463: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -function _(message, opts) { - return `${opts && opts.context ? opts.context : "Value"} ${message}.`; -} - -function type(V) { - if (V === null) { - return "Null"; - } - switch (typeof V) { - case "undefined": - return "Undefined"; - case "boolean": - return "Boolean"; - case "number": - return "Number"; - case "string": - return "String"; - case "symbol": - return "Symbol"; - case "object": - // Falls through - case "function": - // Falls through - default: - // Per ES spec, typeof returns an implemention-defined value that is not any of the existing ones for - // uncallable non-standard exotic objects. Yet Type() which the Web IDL spec depends on returns Object for - // such cases. So treat the default case as an object. - return "Object"; - } -} - -// Round x to the nearest integer, choosing the even integer if it lies halfway between two. -function evenRound(x) { - // There are four cases for numbers with fractional part being .5: - // - // case | x | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 | example - // 1 | 2n + 0.5 | 2n | 2n + 1 | 2n | > | 0.5 | 0 | 0.5 -> 0 - // 2 | 2n + 1.5 | 2n + 1 | 2n + 2 | 2n + 2 | > | 0.5 | 1 | 1.5 -> 2 - // 3 | -2n - 0.5 | -2n - 1 | -2n | -2n | < | -0.5 | 0 | -0.5 -> 0 - // 4 | -2n - 1.5 | -2n - 2 | -2n - 1 | -2n - 2 | < | -0.5 | 1 | -1.5 -> -2 - // (where n is a non-negative integer) - // - // Branch here for cases 1 and 4 - if ((x > 0 && (x % 1) === +0.5 && (x & 1) === 0) || - (x < 0 && (x % 1) === -0.5 && (x & 1) === 1)) { - return censorNegativeZero(Math.floor(x)); - } - - return censorNegativeZero(Math.round(x)); -} - -function integerPart(n) { - return censorNegativeZero(Math.trunc(n)); -} - -function sign(x) { - return x < 0 ? -1 : 1; -} - -function modulo(x, y) { - // https://tc39.github.io/ecma262/#eqn-modulo - // Note that http://stackoverflow.com/a/4467559/3191 does NOT work for large modulos - const signMightNotMatch = x % y; - if (sign(y) !== sign(signMightNotMatch)) { - return signMightNotMatch + y; - } - return signMightNotMatch; -} - -function censorNegativeZero(x) { - return x === 0 ? 0 : x; -} - -function createIntegerConversion(bitLength, typeOpts) { - const isSigned = !typeOpts.unsigned; - - let lowerBound; - let upperBound; - if (bitLength === 64) { - upperBound = Math.pow(2, 53) - 1; - lowerBound = !isSigned ? 0 : -Math.pow(2, 53) + 1; - } else if (!isSigned) { - lowerBound = 0; - upperBound = Math.pow(2, bitLength) - 1; - } else { - lowerBound = -Math.pow(2, bitLength - 1); - upperBound = Math.pow(2, bitLength - 1) - 1; - } - - const twoToTheBitLength = Math.pow(2, bitLength); - const twoToOneLessThanTheBitLength = Math.pow(2, bitLength - 1); - - return (V, opts) => { - if (opts === undefined) { - opts = {}; - } - - let x = +V; - x = censorNegativeZero(x); // Spec discussion ongoing: https://github.com/heycam/webidl/issues/306 - - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite number", opts)); - } - - x = integerPart(x); - - if (x < lowerBound || x > upperBound) { - throw new TypeError(_( - `is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`, opts)); - } - - return x; - } - - if (!Number.isNaN(x) && opts.clamp) { - x = Math.min(Math.max(x, lowerBound), upperBound); - x = evenRound(x); - return x; - } - - if (!Number.isFinite(x) || x === 0) { - return 0; - } - x = integerPart(x); - - // Math.pow(2, 64) is not accurately representable in JavaScript, so try to avoid these per-spec operations if - // possible. Hopefully it's an optimization for the non-64-bitLength cases too. - if (x >= lowerBound && x <= upperBound) { - return x; - } - - // These will not work great for bitLength of 64, but oh well. See the README for more details. - x = modulo(x, twoToTheBitLength); - if (isSigned && x >= twoToOneLessThanTheBitLength) { - return x - twoToTheBitLength; - } - return x; - }; -} - -exports.any = V => { - return V; -}; - -exports["void"] = function () { - return undefined; -}; - -exports.boolean = function (val) { - return !!val; -}; - -exports.byte = createIntegerConversion(8, { unsigned: false }); -exports.octet = createIntegerConversion(8, { unsigned: true }); - -exports.short = createIntegerConversion(16, { unsigned: false }); -exports["unsigned short"] = createIntegerConversion(16, { unsigned: true }); - -exports.long = createIntegerConversion(32, { unsigned: false }); -exports["unsigned long"] = createIntegerConversion(32, { unsigned: true }); - -exports["long long"] = createIntegerConversion(64, { unsigned: false }); -exports["unsigned long long"] = createIntegerConversion(64, { unsigned: true }); - -exports.double = (V, opts) => { - const x = +V; - - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite floating-point value", opts)); - } - - return x; -}; - -exports["unrestricted double"] = V => { - const x = +V; - - return x; -}; - -exports.float = (V, opts) => { - const x = +V; - - if (!Number.isFinite(x)) { - throw new TypeError(_("is not a finite floating-point value", opts)); - } - - if (Object.is(x, -0)) { - return x; - } - - const y = Math.fround(x); - - if (!Number.isFinite(y)) { - throw new TypeError(_("is outside the range of a single-precision floating-point value", opts)); - } - - return y; -}; - -exports["unrestricted float"] = V => { - const x = +V; - - if (isNaN(x)) { - return x; - } - - if (Object.is(x, -0)) { - return x; - } - - return Math.fround(x); -}; - -exports.DOMString = function (V, opts) { - if (opts === undefined) { - opts = {}; - } - - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } - - if (typeof V === "symbol") { - throw new TypeError(_("is a symbol, which cannot be converted to a string", opts)); - } - - return String(V); -}; - -exports.ByteString = (V, opts) => { - const x = exports.DOMString(V, opts); - let c; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError(_("is not a valid ByteString", opts)); - } - } - - return x; -}; - -exports.USVString = (V, opts) => { - const S = exports.DOMString(V, opts); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + ((2 << 9) * a) + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } - - return U.join(""); -}; - -exports.object = (V, opts) => { - if (type(V) !== "Object") { - throw new TypeError(_("is not an object", opts)); - } - - return V; -}; - -// Not exported, but used in Function and VoidFunction. - -// Neither Function nor VoidFunction is defined with [TreatNonObjectAsNull], so -// handling for that is omitted. -function convertCallbackFunction(V, opts) { - if (typeof V !== "function") { - throw new TypeError(_("is not a function", opts)); - } - return V; -} - -const abByteLengthGetter = - Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; - -function isArrayBuffer(V) { - try { - abByteLengthGetter.call(V); - return true; - } catch (e) { - return false; - } -} - -// I don't think we can reliably detect detached ArrayBuffers. -exports.ArrayBuffer = (V, opts) => { - if (!isArrayBuffer(V)) { - throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); - } - return V; -}; - -const dvByteLengthGetter = - Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get; -exports.DataView = (V, opts) => { - try { - dvByteLengthGetter.call(V); - return V; - } catch (e) { - throw new TypeError(_("is not a view on an DataView object", opts)); - } -}; - -[ - Int8Array, Int16Array, Int32Array, Uint8Array, - Uint16Array, Uint32Array, Uint8ClampedArray, Float32Array, Float64Array -].forEach(func => { - const name = func.name; - const article = /^[AEIOU]/.test(name) ? "an" : "a"; - exports[name] = (V, opts) => { - if (!ArrayBuffer.isView(V) || V.constructor.name !== name) { - throw new TypeError(_(`is not ${article} ${name} object`, opts)); - } - - return V; - }; -}); - -// Common definitions - -exports.ArrayBufferView = (V, opts) => { - if (!ArrayBuffer.isView(V)) { - throw new TypeError(_("is not a view on an ArrayBuffer object", opts)); - } - - return V; -}; - -exports.BufferSource = (V, opts) => { - if (!ArrayBuffer.isView(V) && !isArrayBuffer(V)) { - throw new TypeError(_("is not an ArrayBuffer object or a view on one", opts)); - } - - return V; -}; - -exports.DOMTimeStamp = exports["unsigned long long"]; - -exports.Function = convertCallbackFunction; - -exports.VoidFunction = convertCallbackFunction; - - -/***/ }), - -/***/ 57617: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const DOMException = __nccwpck_require__(37561); - -// Special install function to make the DOMException inherit from Error. -// https://heycam.github.io/webidl/#es-DOMException-specialness -function installOverride(globalObject) { - if (typeof globalObject.Error !== "function") { - throw new Error("Internal error: Error constructor is not present on the given global object."); - } - - DOMException.install(globalObject); - Object.setPrototypeOf(globalObject.DOMException.prototype, globalObject.Error.prototype); -} - -module.exports = {...DOMException, install: installOverride }; - - /***/ }), /***/ 49865: @@ -241285,309 +227015,6 @@ exports.timings = function (data) { } -/***/ }), - -/***/ 15487: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const whatwgEncoding = __nccwpck_require__(49967); - -// https://html.spec.whatwg.org/#encoding-sniffing-algorithm -module.exports = (buffer, { transportLayerEncodingLabel, defaultEncoding = "windows-1252" } = {}) => { - let encoding = whatwgEncoding.getBOMEncoding(buffer); // see https://github.com/whatwg/html/issues/1910 - - if (encoding === null && transportLayerEncodingLabel !== undefined) { - encoding = whatwgEncoding.labelToName(transportLayerEncodingLabel); - } - - if (encoding === null) { - encoding = prescanMetaCharset(buffer); - } - - if (encoding === null) { - encoding = defaultEncoding; - } - - return encoding; -}; - -// https://html.spec.whatwg.org/multipage/syntax.html#prescan-a-byte-stream-to-determine-its-encoding -function prescanMetaCharset(buffer) { - const l = Math.min(buffer.length, 1024); - for (let i = 0; i < l; i++) { - let c = buffer[i]; - if (c === 0x3C) { - // "<" - const c1 = buffer[i + 1]; - const c2 = buffer[i + 2]; - const c3 = buffer[i + 3]; - const c4 = buffer[i + 4]; - const c5 = buffer[i + 5]; - // !-- (comment start) - if (c1 === 0x21 && c2 === 0x2D && c3 === 0x2D) { - i += 4; - for (; i < l; i++) { - c = buffer[i]; - const cMinus1 = buffer[i - 1]; - const cMinus2 = buffer[i - 2]; - // --> (comment end) - if (c === 0x3E && cMinus1 === 0x2D && cMinus2 === 0x2D) { - break; - } - } - } else if ((c1 === 0x4D || c1 === 0x6D) && - (c2 === 0x45 || c2 === 0x65) && - (c3 === 0x54 || c3 === 0x74) && - (c4 === 0x41 || c4 === 0x61) && - (isSpaceCharacter(c5) || c5 === 0x2F)) { - // "meta" + space or / - i += 6; - const attributeList = new Set(); - let gotPragma = false; - let needPragma = null; - let charset = null; - - let attrRes; - do { - attrRes = getAttribute(buffer, i, l); - if (attrRes.attr && !attributeList.has(attrRes.attr.name)) { - attributeList.add(attrRes.attr.name); - if (attrRes.attr.name === "http-equiv") { - gotPragma = attrRes.attr.value === "content-type"; - } else if (attrRes.attr.name === "content" && !charset) { - charset = extractCharacterEncodingFromMeta(attrRes.attr.value); - if (charset !== null) { - needPragma = true; - } - } else if (attrRes.attr.name === "charset") { - charset = whatwgEncoding.labelToName(attrRes.attr.value); - needPragma = false; - } - } - i = attrRes.i; - } while (attrRes.attr); - - if (needPragma === null) { - continue; - } - if (needPragma === true && gotPragma === false) { - continue; - } - if (charset === null) { - continue; - } - - if (charset === "UTF-16LE" || charset === "UTF-16BE") { - charset = "UTF-8"; - } - if (charset === "x-user-defined") { - charset = "windows-1252"; - } - - return charset; - } else if ((c1 >= 0x41 && c1 <= 0x5A) || (c1 >= 0x61 && c1 <= 0x7A)) { - // a-z or A-Z - for (i += 2; i < l; i++) { - c = buffer[i]; - // space or > - if (isSpaceCharacter(c) || c === 0x3E) { - break; - } - } - let attrRes; - do { - attrRes = getAttribute(buffer, i, l); - i = attrRes.i; - } while (attrRes.attr); - } else if (c1 === 0x21 || c1 === 0x2F || c1 === 0x3F) { - // ! or / or ? - for (i += 2; i < l; i++) { - c = buffer[i]; - // > - if (c === 0x3E) { - break; - } - } - } - } - } - return null; -} - -// https://html.spec.whatwg.org/multipage/syntax.html#concept-get-attributes-when-sniffing -function getAttribute(buffer, i, l) { - for (; i < l; i++) { - let c = buffer[i]; - // space or / - if (isSpaceCharacter(c) || c === 0x2F) { - continue; - } - // ">" - if (c === 0x3E) { - break; - } - let name = ""; - let value = ""; - nameLoop:for (; i < l; i++) { - c = buffer[i]; - // "=" - if (c === 0x3D && name !== "") { - i++; - break; - } - // space - if (isSpaceCharacter(c)) { - for (i++; i < l; i++) { - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - continue; - } - // not "=" - if (c !== 0x3D) { - return { attr: { name, value }, i }; - } - - i++; - break nameLoop; - } - break; - } - // / or > - if (c === 0x2F || c === 0x3E) { - return { attr: { name, value }, i }; - } - // A-Z - if (c >= 0x41 && c <= 0x5A) { - name += String.fromCharCode(c + 0x20); // lowercase - } else { - name += String.fromCharCode(c); - } - } - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - for (i++; i < l; i++) { - c = buffer[i]; - // space - if (isSpaceCharacter(c)) { - continue; - } else { - break; - } - } - } - // " or ' - if (c === 0x22 || c === 0x27) { - const quote = c; - for (i++; i < l; i++) { - c = buffer[i]; - - if (c === quote) { - i++; - return { attr: { name, value }, i }; - } - - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } - } - } - - // > - if (c === 0x3E) { - return { attr: { name, value }, i }; - } - - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } - - for (i++; i < l; i++) { - c = buffer[i]; - - // space or > - if (isSpaceCharacter(c) || c === 0x3E) { - return { attr: { name, value }, i }; - } - - // A-Z - if (c >= 0x41 && c <= 0x5A) { - value += String.fromCharCode(c + 0x20); // lowercase - } else { - value += String.fromCharCode(c); - } - } - } - return { i }; -} - -function extractCharacterEncodingFromMeta(string) { - let position = 0; - - while (true) { - const indexOfCharset = string.substring(position).search(/charset/i); - - if (indexOfCharset === -1) { - return null; - } - let subPosition = position + indexOfCharset + "charset".length; - - while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { - ++subPosition; - } - - if (string[subPosition] !== "=") { - position = subPosition - 1; - continue; - } - - ++subPosition; - - while (isSpaceCharacter(string[subPosition].charCodeAt(0))) { - ++subPosition; - } - - position = subPosition; - break; - } - - if (string[position] === "\"" || string[position] === "'") { - const nextIndex = string.indexOf(string[position], position + 1); - - if (nextIndex !== -1) { - return whatwgEncoding.labelToName(string.substring(position + 1, nextIndex)); - } - - // It is an unmatched quotation mark - return null; - } - - if (string.length === position + 1) { - return null; - } - - const indexOfASCIIWhitespaceOrSemicolon = string.substring(position + 1).search(/\x09|\x0A|\x0C|\x0D|\x20|;/); - const end = indexOfASCIIWhitespaceOrSemicolon === -1 ? - string.length : - position + indexOfASCIIWhitespaceOrSemicolon + 1; - - return whatwgEncoding.labelToName(string.substring(position, end)); -} - -function isSpaceCharacter(c) { - return c === 0x09 || c === 0x0A || c === 0x0C || c === 0x0D || c === 0x20; -} - - /***/ }), /***/ 61002: @@ -245223,2755 +230650,6 @@ return{name,number,description,supported,action,forced,standard}; }; //# sourceMappingURL=signals.js.map -/***/ }), - -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); - -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. - -exports._dbcs = DBCSCodec; - -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; - -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; - - -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); - - // Load tables. - var mappingTable = codecOptions.table(); - - - // Decode tables: MBCS -> Unicode. - - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; - - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); - - this.defaultCharUnicode = iconv.defaultCharUnicode; - - - // Encode tables: Unicode -> DBCS. - - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; - - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } - - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - - - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. - - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} - -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; - -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); - - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; - - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; -} - - -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); - - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; - - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} - -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} - -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} - -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } - } - - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} - -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; - - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - } -} - - - -// == Encoder ================================================================== - -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} - -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; - - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } - - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } - - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; - - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; - - } else if (resCode == undefined) { // Current character is not part of the sequence. - - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. - - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } - - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } - - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } - - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} - -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - - var newBuf = Buffer.alloc(10), j = 0; - - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } - - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; - } - - return newBuf.slice(0, j); -} - -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; - - -// == Decoder ================================================================== - -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); - - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} - -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; - - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; - - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; - - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; - - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - - // Reset trie node. - nodeIdx = 0; seqStart = i+1; - } - - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} - -DBCSDecoder.prototype.end = function() { - var ret = ''; - - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); - - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } - - this.nodeIdx = 0; - return ret; -} - -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; - - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; - } - return l; -} - - - -/***/ }), - -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. - -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(27014) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', - - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(31532) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, - - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - - - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', - - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(13336) }, - }, - - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', - - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(13336).concat)(__nccwpck_require__(44346)) }, - gb18030: function() { return __nccwpck_require__(36258) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, - - 'chinese': 'gb18030', - - - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(77348) }, - }, - - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', - - - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(74284) }, - }, - - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(74284).concat)(__nccwpck_require__(63480)) }, - encodeSkipVals: [0xa2cc], - }, - - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; - - -/***/ }), - -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(12376), - __nccwpck_require__(11155), - __nccwpck_require__(51644), - __nccwpck_require__(26657), - __nccwpck_require__(41080), - __nccwpck_require__(21012), - __nccwpck_require__(39695), - __nccwpck_require__(91386), -]; - -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; -} - - -/***/ }), - -/***/ 12376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); - -// Export Node.js internal encodings. - -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", - - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", - - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - - // Codec. - _internal: InternalCodec, -}; - -//------------------------------------------------------------------------------ - -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; - - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; - - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} - -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; - -//------------------------------------------------------------------------------ - -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = (__nccwpck_require__(71576).StringDecoder); - -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; - - -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); -} - -InternalDecoder.prototype = StringDecoder.prototype; - - -//------------------------------------------------------------------------------ -// Encoder is mostly trivial - -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} - -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} - -InternalEncoder.prototype.end = function() { -} - - -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. - -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} - -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - - return Buffer.from(str, "base64"); -} - -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} - - -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. - -function InternalEncoderCesu8(options, codec) { -} - -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} - -InternalEncoderCesu8.prototype.end = function() { -} - -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ - -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} - -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } - - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} - -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} - - -/***/ }), - -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); - -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). - -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } - - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; - - this.encodeBuf = encodeBuf; -} - -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; - - -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} - -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} - -SBCSEncoder.prototype.end = function() { -} - - -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} - -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); -} - -SBCSDecoder.prototype.end = function() { -} - - -/***/ }), - -/***/ 21012: -/***/ ((module) => { - -"use strict"; - - -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} - -/***/ }), - -/***/ 41080: -/***/ ((module) => { - -"use strict"; - - -// Manually added data to be used by sbcs codec in addition to generated one. - -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, - - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, - - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", - - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", - - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", - - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", - - "cp819": "iso88591", - "ibm819": "iso88591", - - "cyrillic": "iso88595", - - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", - - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", - - "hebrew": "iso88598", - "hebrew8": "iso88598", - - "turkish": "iso88599", - "turkish8": "iso88599", - - "thai": "iso885911", - "thai8": "iso885911", - - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", - - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", - - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", - - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", - - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", - - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", - - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", - - "strk10482002": "rk1048", - - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", - - "gb198880": "iso646cn", - "cn": "iso646cn", - - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", - - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", - - "mac": "macintosh", - "csmacintosh": "macintosh", -}; - - - -/***/ }), - -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); - -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== - -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} - -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf16BEEncoder() { -} - -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} - -Utf16BEEncoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf16BEDecoder() { - this.overflowByte = -1; -} - -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; - - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; - - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } - - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } - - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - - return buf2.slice(0, j).toString('ucs2'); -} - -Utf16BEDecoder.prototype.end = function() { -} - - -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); - -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} - -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - - -// -- Encoding (pass-through) - -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} - -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} - -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} - - -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; - - this.options = options || {}; - this.iconv = codec.iconv; -} - -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; - } - - return this.decoder.write(buf); -} - -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var res = this.decoder.write(buf), - trail = this.decoder.end(); - - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} - -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; - - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; - else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. - - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } - - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; - } - } - - return enc; -} - - - - -/***/ }), - -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(15118).Buffer); - -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 - -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; - - -// -- Encoding - -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} - -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} - -Utf7Encoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} - -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); - -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. - - -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} - -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; - - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } - - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character - - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } - - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; - - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } - - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; - - return buf.slice(0, bufIdx); -} - -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } - - return buf.slice(0, bufIdx); -} - - -// -- Decoding - -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} - -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; - -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - - - -/***/ }), - -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -var BOMChar = '\uFEFF'; - -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} - -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } - - return this.encoder.write(str); -} - -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} - - -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} - -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } - - this.pass = true; - return res; -} - -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} - - - -/***/ }), - -/***/ 30393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var Buffer = (__nccwpck_require__(14300).Buffer); -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer - -// == Extend Node primitives to use iconv-lite ================================= - -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. - - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); - - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; - - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } - - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; - - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } - - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } - - // -- Buffer --------------------------------------------------------------- - - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } - - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); - - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } - - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - - // TODO: Set _charsWritten. - } - - - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); - - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } - - Readable.prototype.collect = iconv._collect; - } - } - - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") - - delete Buffer.isNativeEncoding; - - var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); - - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; - - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; - - if (iconv.supportsStreams) { - var Readable = (__nccwpck_require__(12781).Readable); - - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } - - original = undefined; - } -} - - -/***/ }), - -/***/ 19032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = (__nccwpck_require__(15118).Buffer); - -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; - -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; - -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; - -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - - var encoder = iconv.getEncoder(encoding, options); - - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} - -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } - - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } - - var decoder = iconv.getDecoder(encoding, options); - - var res = decoder.write(buf); - var trail = decoder.end(); - - return trail ? (res + trail) : res; -} - -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } -} - -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; - -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); - - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; - - var codecDef = iconv.encodings[enc]; - - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; - - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; - - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; - - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); - - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; - - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} - -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); -} - -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); - - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); - - return encoder; -} - -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); - - return decoder; -} - - -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { - - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); - } - - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); -} - -if (false) {} - - -/***/ }), - -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Buffer = (__nccwpck_require__(14300).Buffer), - Transform = (__nccwpck_require__(12781).Transform); - - -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } - - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } - - iconv.supportsStreams = true; - - - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; - - -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} - -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); - -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; -} - - -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} - -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); - -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} - - - /***/ }), /***/ 98043: @@ -248172,22 +230850,6 @@ function isPlainObject(o) { exports.isPlainObject = isPlainObject; -/***/ }), - -/***/ 42469: -/***/ ((module) => { - -// Generated using `npm run build`. Do not edit. - -var regex = /^[a-z](?:[\.0-9_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*-(?:[\x2D\.0-9_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/; - -var isPotentialCustomElementName = function(string) { - return regex.test(string); -}; - -module.exports = isPotentialCustomElementName; - - /***/ }), /***/ 41554: @@ -255625,92873 +238287,6 @@ module.exports = new Type('tag:yaml.org,2002:timestamp', { }).call(this); -/***/ }), - -/***/ 46123: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const path = __nccwpck_require__(71017); -const fs = (__nccwpck_require__(57147).promises); -const vm = __nccwpck_require__(26144); -const toughCookie = __nccwpck_require__(47372); -const sniffHTMLEncoding = __nccwpck_require__(15487); -const whatwgURL = __nccwpck_require__(66365); -const whatwgEncoding = __nccwpck_require__(49967); -const { URL } = __nccwpck_require__(66365); -const MIMEType = __nccwpck_require__(59488); -const idlUtils = __nccwpck_require__(34908); -const VirtualConsole = __nccwpck_require__(34459); -const { createWindow } = __nccwpck_require__(55802); -const { parseIntoDocument } = __nccwpck_require__(35373); -const { fragmentSerialization } = __nccwpck_require__(33740); -const ResourceLoader = __nccwpck_require__(90007); -const NoOpResourceLoader = __nccwpck_require__(5383); - -class CookieJar extends toughCookie.CookieJar { - constructor(store, options) { - // jsdom cookie jars must be loose by default - super(store, { looseMode: true, ...options }); - } -} - -const window = Symbol("window"); -let sharedFragmentDocument = null; - -class JSDOM { - constructor(input = "", options = {}) { - const mimeType = new MIMEType(options.contentType === undefined ? "text/html" : options.contentType); - const { html, encoding } = normalizeHTML(input, mimeType); - - options = transformOptions(options, encoding, mimeType); - - this[window] = createWindow(options.windowOptions); - - const documentImpl = idlUtils.implForWrapper(this[window]._document); - - options.beforeParse(this[window]._globalProxy); - - parseIntoDocument(html, documentImpl); - - documentImpl.close(); - } - - get window() { - // It's important to grab the global proxy, instead of just the result of `createWindow(...)`, since otherwise - // things like `window.eval` don't exist. - return this[window]._globalProxy; - } - - get virtualConsole() { - return this[window]._virtualConsole; - } - - get cookieJar() { - // TODO NEWAPI move _cookieJar to window probably - return idlUtils.implForWrapper(this[window]._document)._cookieJar; - } - - serialize() { - return fragmentSerialization(idlUtils.implForWrapper(this[window]._document), { requireWellFormed: false }); - } - - nodeLocation(node) { - if (!idlUtils.implForWrapper(this[window]._document)._parseOptions.sourceCodeLocationInfo) { - throw new Error("Location information was not saved for this jsdom. Use includeNodeLocations during creation."); - } - - return idlUtils.implForWrapper(node).sourceCodeLocation; - } - - getInternalVMContext() { - if (!vm.isContext(this[window])) { - throw new TypeError("This jsdom was not configured to allow script running. " + - "Use the runScripts option during creation."); - } - - return this[window]; - } - - reconfigure(settings) { - if ("windowTop" in settings) { - this[window]._top = settings.windowTop; - } - - if ("url" in settings) { - const document = idlUtils.implForWrapper(this[window]._document); - - const url = whatwgURL.parseURL(settings.url); - if (url === null) { - throw new TypeError(`Could not parse "${settings.url}" as a URL`); - } - - document._URL = url; - document._origin = whatwgURL.serializeURLOrigin(document._URL); - } - } - - static fragment(string = "") { - if (!sharedFragmentDocument) { - sharedFragmentDocument = (new JSDOM()).window.document; - } - - const template = sharedFragmentDocument.createElement("template"); - template.innerHTML = string; - return template.content; - } - - static fromURL(url, options = {}) { - return Promise.resolve().then(() => { - // Remove the hash while sending this through the research loader fetch(). - // It gets added back a few lines down when constructing the JSDOM object. - const parsedURL = new URL(url); - const originalHash = parsedURL.hash; - parsedURL.hash = ""; - url = parsedURL.href; - - options = normalizeFromURLOptions(options); - - const resourceLoader = resourcesToResourceLoader(options.resources); - const resourceLoaderForInitialRequest = resourceLoader.constructor === NoOpResourceLoader ? - new ResourceLoader() : - resourceLoader; - - const req = resourceLoaderForInitialRequest.fetch(url, { - accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - cookieJar: options.cookieJar, - referrer: options.referrer - }); - - return req.then(body => { - const res = req.response; - - options = Object.assign(options, { - url: req.href + originalHash, - contentType: res.headers["content-type"], - referrer: req.getHeader("referer") - }); - - return new JSDOM(body, options); - }); - }); - } - - static async fromFile(filename, options = {}) { - options = normalizeFromFileOptions(filename, options); - const buffer = await fs.readFile(filename); - - return new JSDOM(buffer, options); - } -} - -function normalizeFromURLOptions(options) { - // Checks on options that are invalid for `fromURL` - if (options.url !== undefined) { - throw new TypeError("Cannot supply a url option when using fromURL"); - } - if (options.contentType !== undefined) { - throw new TypeError("Cannot supply a contentType option when using fromURL"); - } - - // Normalization of options which must be done before the rest of the fromURL code can use them, because they are - // given to request() - const normalized = { ...options }; - - if (options.referrer !== undefined) { - normalized.referrer = (new URL(options.referrer)).href; - } - - if (options.cookieJar === undefined) { - normalized.cookieJar = new CookieJar(); - } - - return normalized; - - // All other options don't need to be processed yet, and can be taken care of in the normal course of things when - // `fromURL` calls `new JSDOM(html, options)`. -} - -function normalizeFromFileOptions(filename, options) { - const normalized = { ...options }; - - if (normalized.contentType === undefined) { - const extname = path.extname(filename); - if (extname === ".xhtml" || extname === ".xht" || extname === ".xml") { - normalized.contentType = "application/xhtml+xml"; - } - } - - if (normalized.url === undefined) { - normalized.url = new URL("file:" + path.resolve(filename)); - } - - return normalized; -} - -function transformOptions(options, encoding, mimeType) { - const transformed = { - windowOptions: { - // Defaults - url: "about:blank", - referrer: "", - contentType: "text/html", - parsingMode: "html", - parseOptions: { - sourceCodeLocationInfo: false, - scriptingEnabled: false - }, - runScripts: undefined, - encoding, - pretendToBeVisual: false, - storageQuota: 5000000, - - // Defaults filled in later - resourceLoader: undefined, - virtualConsole: undefined, - cookieJar: undefined - }, - - // Defaults - beforeParse() { } - }; - - // options.contentType was parsed into mimeType by the caller. - if (!mimeType.isHTML() && !mimeType.isXML()) { - throw new RangeError(`The given content type of "${options.contentType}" was not a HTML or XML content type`); - } - - transformed.windowOptions.contentType = mimeType.essence; - transformed.windowOptions.parsingMode = mimeType.isHTML() ? "html" : "xml"; - - if (options.url !== undefined) { - transformed.windowOptions.url = (new URL(options.url)).href; - } - - if (options.referrer !== undefined) { - transformed.windowOptions.referrer = (new URL(options.referrer)).href; - } - - if (options.includeNodeLocations) { - if (transformed.windowOptions.parsingMode === "xml") { - throw new TypeError("Cannot set includeNodeLocations to true with an XML content type"); - } - - transformed.windowOptions.parseOptions = { sourceCodeLocationInfo: true }; - } - - transformed.windowOptions.cookieJar = options.cookieJar === undefined ? - new CookieJar() : - options.cookieJar; - - transformed.windowOptions.virtualConsole = options.virtualConsole === undefined ? - (new VirtualConsole()).sendTo(console) : - options.virtualConsole; - - if (!(transformed.windowOptions.virtualConsole instanceof VirtualConsole)) { - throw new TypeError("virtualConsole must be an instance of VirtualConsole"); - } - - transformed.windowOptions.resourceLoader = resourcesToResourceLoader(options.resources); - - if (options.runScripts !== undefined) { - transformed.windowOptions.runScripts = String(options.runScripts); - if (transformed.windowOptions.runScripts === "dangerously") { - transformed.windowOptions.parseOptions.scriptingEnabled = true; - } else if (transformed.windowOptions.runScripts !== "outside-only") { - throw new RangeError(`runScripts must be undefined, "dangerously", or "outside-only"`); - } - } - - if (options.beforeParse !== undefined) { - transformed.beforeParse = options.beforeParse; - } - - if (options.pretendToBeVisual !== undefined) { - transformed.windowOptions.pretendToBeVisual = Boolean(options.pretendToBeVisual); - } - - if (options.storageQuota !== undefined) { - transformed.windowOptions.storageQuota = Number(options.storageQuota); - } - - return transformed; -} - -function normalizeHTML(html, mimeType) { - let encoding = "UTF-8"; - - if (ArrayBuffer.isView(html)) { - html = Buffer.from(html.buffer, html.byteOffset, html.byteLength); - } else if (html instanceof ArrayBuffer) { - html = Buffer.from(html); - } - - if (Buffer.isBuffer(html)) { - encoding = sniffHTMLEncoding(html, { - defaultEncoding: mimeType.isXML() ? "UTF-8" : "windows-1252", - transportLayerEncodingLabel: mimeType.parameters.get("charset") - }); - html = whatwgEncoding.decode(html, encoding); - } else { - html = String(html); - } - - return { html, encoding }; -} - -function resourcesToResourceLoader(resources) { - switch (resources) { - case undefined: { - return new NoOpResourceLoader(); - } - case "usable": { - return new ResourceLoader(); - } - default: { - if (!(resources instanceof ResourceLoader)) { - throw new TypeError("resources must be an instance of ResourceLoader"); - } - return resources; - } - } -} - -exports.JSDOM = JSDOM; - -exports.VirtualConsole = VirtualConsole; -exports.CookieJar = CookieJar; -exports.ResourceLoader = ResourceLoader; - -exports.toughCookie = toughCookie; - - -/***/ }), - -/***/ 55802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -const vm = __nccwpck_require__(26144); -const webIDLConversions = __nccwpck_require__(54886); -const { CSSStyleDeclaration } = __nccwpck_require__(15674); -const { Performance: RawPerformance } = __nccwpck_require__(38481); -const notImplemented = __nccwpck_require__(42751); -const { installInterfaces } = __nccwpck_require__(71643); -const { define, mixin } = __nccwpck_require__(11463); -const Element = __nccwpck_require__(4444); -const EventTarget = __nccwpck_require__(71038); -const EventHandlerNonNull = __nccwpck_require__(23129); -const OnBeforeUnloadEventHandlerNonNull = __nccwpck_require__(64546); -const OnErrorEventHandlerNonNull = __nccwpck_require__(87517); -const PageTransitionEvent = __nccwpck_require__(32941); -const namedPropertiesWindow = __nccwpck_require__(15200); -const postMessage = __nccwpck_require__(47054); -const DOMException = __nccwpck_require__(57617); -const { btoa, atob } = __nccwpck_require__(75696); -const idlUtils = __nccwpck_require__(34908); -const WebSocketImpl = (__nccwpck_require__(13846).implementation); -const BarProp = __nccwpck_require__(35849); -const documents = __nccwpck_require__(19951); -const External = __nccwpck_require__(19995); -const Navigator = __nccwpck_require__(96340); -const Performance = __nccwpck_require__(19264); -const Screen = __nccwpck_require__(46164); -const Storage = __nccwpck_require__(76969); -const Selection = __nccwpck_require__(69144); -const reportException = __nccwpck_require__(15612); -const { getCurrentEventHandlerValue } = __nccwpck_require__(50238); -const { fireAnEvent } = __nccwpck_require__(45673); -const SessionHistory = __nccwpck_require__(14825); -const { forEachMatchingSheetRuleOfElement, getResolvedValue, propertiesWithResolvedValueImplemented, - SHADOW_DOM_PSEUDO_REGEXP } = __nccwpck_require__(11627); -const CustomElementRegistry = __nccwpck_require__(17609); -const jsGlobals = __nccwpck_require__(40264); - -const GlobalEventHandlersImpl = (__nccwpck_require__(4084).implementation); -const WindowEventHandlersImpl = (__nccwpck_require__(42515).implementation); - -const events = new Set([ - // GlobalEventHandlers - "abort", "autocomplete", - "autocompleteerror", "blur", - "cancel", "canplay", "canplaythrough", - "change", "click", - "close", "contextmenu", - "cuechange", "dblclick", - "drag", "dragend", - "dragenter", - "dragleave", "dragover", - "dragstart", "drop", - "durationchange", "emptied", - "ended", "focus", - "input", "invalid", - "keydown", "keypress", - "keyup", "load", "loadeddata", - "loadedmetadata", "loadstart", - "mousedown", "mouseenter", - "mouseleave", "mousemove", - "mouseout", "mouseover", - "mouseup", "wheel", - "pause", "play", - "playing", "progress", - "ratechange", "reset", - "resize", "scroll", - "securitypolicyviolation", - "seeked", "seeking", - "select", "sort", "stalled", - "submit", "suspend", - "timeupdate", "toggle", - "volumechange", "waiting", - - // WindowEventHandlers - "afterprint", - "beforeprint", - "hashchange", - "languagechange", - "message", - "messageerror", - "offline", - "online", - "pagehide", - "pageshow", - "popstate", - "rejectionhandled", - "storage", - "unhandledrejection", - "unload" - - // "error" and "beforeunload" are added separately -]); - -exports.createWindow = function (options) { - return new Window(options); -}; - -const jsGlobalEntriesToInstall = Object.entries(jsGlobals).filter(([name]) => name in global); - -// TODO remove when we drop Node v10 support. -const anyNodeVersionQueueMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : process.nextTick; - -// https://html.spec.whatwg.org/#the-window-object -function setupWindow(windowInstance, { runScripts }) { - if (runScripts === "outside-only" || runScripts === "dangerously") { - contextifyWindow(windowInstance); - - // Without this, these globals will only appear to scripts running inside the context using vm.runScript; they will - // not appear to scripts running from the outside, including to JSDOM implementation code. - for (const [globalName, globalPropDesc] of jsGlobalEntriesToInstall) { - const propDesc = { ...globalPropDesc, value: vm.runInContext(globalName, windowInstance) }; - Object.defineProperty(windowInstance, globalName, propDesc); - } - } else { - // Without contextifying the window, none of the globals will exist. So, let's at least alias them from the Node.js - // context. See https://github.com/jsdom/jsdom/issues/2727 for more background and discussion. - for (const [globalName, globalPropDesc] of jsGlobalEntriesToInstall) { - const propDesc = { ...globalPropDesc, value: global[globalName] }; - Object.defineProperty(windowInstance, globalName, propDesc); - } - } - - installInterfaces(windowInstance, ["Window"]); - - const EventTargetConstructor = windowInstance.EventTarget; - - // eslint-disable-next-line func-name-matching, func-style, no-shadow - const windowConstructor = function Window() { - throw new TypeError("Illegal constructor"); - }; - Object.setPrototypeOf(windowConstructor, EventTargetConstructor); - - Object.defineProperty(windowInstance, "Window", { - configurable: true, - writable: true, - value: windowConstructor - }); - - const windowPrototype = Object.create(EventTargetConstructor.prototype); - Object.defineProperties(windowPrototype, { - constructor: { - value: windowConstructor, - writable: true, - configurable: true - }, - [Symbol.toStringTag]: { - value: "Window", - configurable: true - } - }); - - windowConstructor.prototype = windowPrototype; - Object.setPrototypeOf(windowInstance, windowPrototype); - - EventTarget.setup(windowInstance, windowInstance); - mixin(windowInstance, WindowEventHandlersImpl.prototype); - mixin(windowInstance, GlobalEventHandlersImpl.prototype); - windowInstance._initGlobalEvents(); - - Object.defineProperty(windowInstance, "onbeforeunload", { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, "beforeunload")); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = OnBeforeUnloadEventHandlerNonNull.convert(V, { - context: "Failed to set the 'onbeforeunload' property on 'Window': The provided value" - }); - } - this._setEventHandlerFor("beforeunload", V); - } - }); - - Object.defineProperty(windowInstance, "onerror", { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, "error")); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = OnErrorEventHandlerNonNull.convert(V, { - context: "Failed to set the 'onerror' property on 'Window': The provided value" - }); - } - this._setEventHandlerFor("error", V); - } - }); - - for (const event of events) { - Object.defineProperty(windowInstance, `on${event}`, { - configurable: true, - enumerable: true, - get() { - return idlUtils.tryWrapperForImpl(getCurrentEventHandlerValue(this, event)); - }, - set(V) { - if (!idlUtils.isObject(V)) { - V = null; - } else { - V = EventHandlerNonNull.convert(V, { - context: `Failed to set the 'on${event}' property on 'Window': The provided value` - }); - } - this._setEventHandlerFor(event, V); - } - }); - } - - windowInstance._globalObject = windowInstance; -} - -// NOTE: per https://heycam.github.io/webidl/#Global, all properties on the Window object must be own-properties. -// That is why we assign everything inside of the constructor, instead of using a shared prototype. -// You can verify this in e.g. Firefox or Internet Explorer, which do a good job with Web IDL compliance. -function Window(options) { - setupWindow(this, { runScripts: options.runScripts }); - - const rawPerformance = new RawPerformance(); - const windowInitialized = rawPerformance.now(); - - const window = this; - - // ### PRIVATE DATA PROPERTIES - - this._resourceLoader = options.resourceLoader; - - // vm initialization is deferred until script processing is activated - this._globalProxy = this; - Object.defineProperty(idlUtils.implForWrapper(this), idlUtils.wrapperSymbol, { get: () => this._globalProxy }); - - // List options explicitly to be clear which are passed through - this._document = documents.createWrapper(window, { - parsingMode: options.parsingMode, - contentType: options.contentType, - encoding: options.encoding, - cookieJar: options.cookieJar, - url: options.url, - lastModified: options.lastModified, - referrer: options.referrer, - parseOptions: options.parseOptions, - defaultView: this._globalProxy, - global: this, - parentOrigin: options.parentOrigin - }, { alwaysUseDocumentClass: true }); - - if (vm.isContext(window)) { - const documentImpl = idlUtils.implForWrapper(window._document); - documentImpl._defaultView = window._globalProxy = vm.runInContext("this", window); - } - - const documentOrigin = idlUtils.implForWrapper(this._document)._origin; - this._origin = documentOrigin; - - // https://html.spec.whatwg.org/#session-history - this._sessionHistory = new SessionHistory({ - document: idlUtils.implForWrapper(this._document), - url: idlUtils.implForWrapper(this._document)._URL, - stateObject: null - }, this); - - this._virtualConsole = options.virtualConsole; - - this._runScripts = options.runScripts; - - // Set up the window as if it's a top level window. - // If it's not, then references will be corrected by frame/iframe code. - this._parent = this._top = this._globalProxy; - this._frameElement = null; - - // This implements window.frames.length, since window.frames returns a - // self reference to the window object. This value is incremented in the - // HTMLFrameElement implementation. - this._length = 0; - - // https://dom.spec.whatwg.org/#window-current-event - this._currentEvent = undefined; - - this._pretendToBeVisual = options.pretendToBeVisual; - this._storageQuota = options.storageQuota; - - // Some properties (such as localStorage and sessionStorage) share data - // between windows in the same origin. This object is intended - // to contain such data. - if (options.commonForOrigin && options.commonForOrigin[documentOrigin]) { - this._commonForOrigin = options.commonForOrigin; - } else { - this._commonForOrigin = { - [documentOrigin]: { - localStorageArea: new Map(), - sessionStorageArea: new Map(), - windowsInSameOrigin: [this] - } - }; - } - - this._currentOriginData = this._commonForOrigin[documentOrigin]; - - // ### WEB STORAGE - - this._localStorage = Storage.create(window, [], { - associatedWindow: this, - storageArea: this._currentOriginData.localStorageArea, - type: "localStorage", - url: this._document.documentURI, - storageQuota: this._storageQuota - }); - this._sessionStorage = Storage.create(window, [], { - associatedWindow: this, - storageArea: this._currentOriginData.sessionStorageArea, - type: "sessionStorage", - url: this._document.documentURI, - storageQuota: this._storageQuota - }); - - // ### SELECTION - - // https://w3c.github.io/selection-api/#dfn-selection - this._selection = Selection.createImpl(window); - - // https://w3c.github.io/selection-api/#dom-window - this.getSelection = function () { - return window._selection; - }; - - // ### GETTERS - - const locationbar = BarProp.create(window); - const menubar = BarProp.create(window); - const personalbar = BarProp.create(window); - const scrollbars = BarProp.create(window); - const statusbar = BarProp.create(window); - const toolbar = BarProp.create(window); - const external = External.create(window); - const navigator = Navigator.create(window, [], { userAgent: this._resourceLoader._userAgent }); - const performance = Performance.create(window, [], { rawPerformance }); - const screen = Screen.create(window); - const customElementRegistry = CustomElementRegistry.create(window); - - define(this, { - get length() { - return window._length; - }, - get window() { - return window._globalProxy; - }, - get frameElement() { - return idlUtils.wrapperForImpl(window._frameElement); - }, - get frames() { - return window._globalProxy; - }, - get self() { - return window._globalProxy; - }, - get parent() { - return window._parent; - }, - get top() { - return window._top; - }, - get document() { - return window._document; - }, - get external() { - return external; - }, - get location() { - return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location); - }, - get history() { - return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._history); - }, - get navigator() { - return navigator; - }, - get locationbar() { - return locationbar; - }, - get menubar() { - return menubar; - }, - get personalbar() { - return personalbar; - }, - get scrollbars() { - return scrollbars; - }, - get statusbar() { - return statusbar; - }, - get toolbar() { - return toolbar; - }, - get performance() { - return performance; - }, - get screen() { - return screen; - }, - get origin() { - return window._origin; - }, - // The origin IDL attribute is defined with [Replaceable]. - set origin(value) { - Object.defineProperty(this, "origin", { - value, - writable: true, - enumerable: true, - configurable: true - }); - }, - get localStorage() { - if (idlUtils.implForWrapper(this._document)._origin === "null") { - throw DOMException.create(window, [ - "localStorage is not available for opaque origins", - "SecurityError" - ]); - } - - return this._localStorage; - }, - get sessionStorage() { - if (idlUtils.implForWrapper(this._document)._origin === "null") { - throw DOMException.create(window, [ - "sessionStorage is not available for opaque origins", - "SecurityError" - ]); - } - - return this._sessionStorage; - }, - get customElements() { - return customElementRegistry; - }, - get event() { - return window._currentEvent ? idlUtils.wrapperForImpl(window._currentEvent) : undefined; - }, - set event(value) { - Object.defineProperty(window, "event", { configurable: true, enumerable: true, writable: true, value }); - } - }); - - namedPropertiesWindow.initializeWindow(this, this._globalProxy); - - // ### METHODS - - // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers - - // In the spec the list of active timers is a set of IDs. We make it a map of IDs to Node.js timer objects, so that - // we can call Node.js-side clearTimeout() when clearing, and thus allow process shutdown faster. - const listOfActiveTimers = new Map(); - let latestTimerId = 0; - - this.setTimeout = function (handler, timeout = 0, ...args) { - if (typeof handler !== "function") { - handler = webIDLConversions.DOMString(handler); - } - timeout = webIDLConversions.long(timeout); - - return timerInitializationSteps(handler, timeout, args, { methodContext: window, repeat: false }); - }; - this.setInterval = function (handler, timeout = 0, ...args) { - if (typeof handler !== "function") { - handler = webIDLConversions.DOMString(handler); - } - timeout = webIDLConversions.long(timeout); - - return timerInitializationSteps(handler, timeout, args, { methodContext: window, repeat: true }); - }; - - this.clearTimeout = function (handle = 0) { - handle = webIDLConversions.long(handle); - - const nodejsTimer = listOfActiveTimers.get(handle); - if (nodejsTimer) { - clearTimeout(nodejsTimer); - listOfActiveTimers.delete(handle); - } - }; - this.clearInterval = function (handle = 0) { - handle = webIDLConversions.long(handle); - - const nodejsTimer = listOfActiveTimers.get(handle); - if (nodejsTimer) { - // We use setTimeout() in timerInitializationSteps even for this.setInterval(). - clearTimeout(nodejsTimer); - listOfActiveTimers.delete(handle); - } - }; - - function timerInitializationSteps(handler, timeout, args, { methodContext, repeat, previousHandle }) { - // This appears to be unspecced, but matches browser behavior for close()ed windows. - if (!methodContext._document) { - return 0; - } - - // TODO: implement timer nesting level behavior. - - const methodContextProxy = methodContext._globalProxy; - const handle = previousHandle !== undefined ? previousHandle : ++latestTimerId; - - function task() { - if (!listOfActiveTimers.has(handle)) { - return; - } - - try { - if (typeof handler === "function") { - handler.apply(methodContextProxy, args); - } else if (window._runScripts === "dangerously") { - vm.runInContext(handler, window, { filename: window.location.href, displayErrors: false }); - } - } catch (e) { - reportException(window, e, window.location.href); - } - - if (listOfActiveTimers.has(handle)) { - if (repeat) { - timerInitializationSteps(handler, timeout, args, { methodContext, repeat: true, previousHandle: handle }); - } else { - listOfActiveTimers.delete(handle); - } - } - } - - if (timeout < 0) { - timeout = 0; - } - - const nodejsTimer = setTimeout(task, timeout); - listOfActiveTimers.set(handle, nodejsTimer); - - return handle; - } - - // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing - - this.queueMicrotask = function (callback) { - callback = webIDLConversions.Function(callback); - - anyNodeVersionQueueMicrotask(() => { - try { - callback(); - } catch (e) { - reportException(window, e, window.location.href); - } - }); - }; - - // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animation-frames - - let animationFrameCallbackId = 0; - const mapOfAnimationFrameCallbacks = new Map(); - let animationFrameNodejsInterval = null; - - // Unlike the spec, where an animation frame happens every 60 Hz regardless, we optimize so that if there are no - // requestAnimationFrame() calls outstanding, we don't fire the timer. This helps us track that. - let numberOfOngoingAnimationFrameCallbacks = 0; - - if (this._pretendToBeVisual) { - this.requestAnimationFrame = function (callback) { - callback = webIDLConversions.Function(callback); - - const handle = ++animationFrameCallbackId; - mapOfAnimationFrameCallbacks.set(handle, callback); - - ++numberOfOngoingAnimationFrameCallbacks; - if (numberOfOngoingAnimationFrameCallbacks === 1) { - animationFrameNodejsInterval = setInterval(() => { - runAnimationFrameCallbacks(rawPerformance.now() - windowInitialized); - }, 1000 / 60); - } - - return handle; - }; - - this.cancelAnimationFrame = function (handle) { - handle = webIDLConversions["unsigned long"](handle); - - removeAnimationFrameCallback(handle); - }; - - function runAnimationFrameCallbacks(now) { - // Converting to an array is important to get a sync snapshot and thus match spec semantics. - const callbackHandles = [...mapOfAnimationFrameCallbacks.keys()]; - for (const handle of callbackHandles) { - // This has() can be false if a callback calls cancelAnimationFrame(). - if (mapOfAnimationFrameCallbacks.has(handle)) { - const callback = mapOfAnimationFrameCallbacks.get(handle); - removeAnimationFrameCallback(handle); - try { - callback(now); - } catch (e) { - reportException(window, e, window.location.href); - } - } - } - } - - function removeAnimationFrameCallback(handle) { - if (mapOfAnimationFrameCallbacks.has(handle)) { - --numberOfOngoingAnimationFrameCallbacks; - if (numberOfOngoingAnimationFrameCallbacks === 0) { - clearInterval(animationFrameNodejsInterval); - } - } - - mapOfAnimationFrameCallbacks.delete(handle); - } - } - - function stopAllTimers() { - for (const nodejsTimer of listOfActiveTimers.values()) { - clearTimeout(nodejsTimer); - } - listOfActiveTimers.clear(); - - clearInterval(animationFrameNodejsInterval); - } - - function Option(text, value, defaultSelected, selected) { - if (text === undefined) { - text = ""; - } - text = webIDLConversions.DOMString(text); - - if (value !== undefined) { - value = webIDLConversions.DOMString(value); - } - - defaultSelected = webIDLConversions.boolean(defaultSelected); - selected = webIDLConversions.boolean(selected); - - const option = window._document.createElement("option"); - const impl = idlUtils.implForWrapper(option); - - if (text !== "") { - impl.text = text; - } - if (value !== undefined) { - impl.setAttributeNS(null, "value", value); - } - if (defaultSelected) { - impl.setAttributeNS(null, "selected", ""); - } - impl._selectedness = selected; - - return option; - } - Object.defineProperty(Option, "prototype", { - value: this.HTMLOptionElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Option", { - value: Option, - configurable: true, - enumerable: false, - writable: true - }); - - function Image(...args) { - const img = window._document.createElement("img"); - const impl = idlUtils.implForWrapper(img); - - if (args.length > 0) { - impl.setAttributeNS(null, "width", String(args[0])); - } - if (args.length > 1) { - impl.setAttributeNS(null, "height", String(args[1])); - } - - return img; - } - Object.defineProperty(Image, "prototype", { - value: this.HTMLImageElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Image", { - value: Image, - configurable: true, - enumerable: false, - writable: true - }); - - function Audio(src) { - const audio = window._document.createElement("audio"); - const impl = idlUtils.implForWrapper(audio); - impl.setAttributeNS(null, "preload", "auto"); - - if (src !== undefined) { - impl.setAttributeNS(null, "src", String(src)); - } - - return audio; - } - Object.defineProperty(Audio, "prototype", { - value: this.HTMLAudioElement.prototype, - configurable: false, - enumerable: false, - writable: false - }); - Object.defineProperty(window, "Audio", { - value: Audio, - configurable: true, - enumerable: false, - writable: true - }); - - this.postMessage = postMessage(window); - - this.atob = function (str) { - const result = atob(str); - if (result === null) { - throw DOMException.create(window, [ - "The string to be decoded contains invalid characters.", - "InvalidCharacterError" - ]); - } - return result; - }; - - this.btoa = function (str) { - const result = btoa(str); - if (result === null) { - throw DOMException.create(window, [ - "The string to be encoded contains invalid characters.", - "InvalidCharacterError" - ]); - } - return result; - }; - - this.stop = function () { - const manager = idlUtils.implForWrapper(this._document)._requestManager; - if (manager) { - manager.close(); - } - }; - - this.close = function () { - // Recursively close child frame windows, then ourselves (depth-first). - for (let i = 0; i < this.length; ++i) { - this[i].close(); - } - - // Clear out all listeners. Any in-flight or upcoming events should not get delivered. - idlUtils.implForWrapper(this)._eventListeners = Object.create(null); - - if (this._document) { - if (this._document.body) { - this._document.body.innerHTML = ""; - } - - if (this._document.close) { - // It's especially important to clear out the listeners here because document.close() causes a "load" event to - // fire. - idlUtils.implForWrapper(this._document)._eventListeners = Object.create(null); - this._document.close(); - } - const doc = idlUtils.implForWrapper(this._document); - if (doc._requestManager) { - doc._requestManager.close(); - } - delete this._document; - } - - stopAllTimers(); - WebSocketImpl.cleanUpWindow(this); - }; - - this.getComputedStyle = function (elt, pseudoElt = undefined) { - elt = Element.convert(elt); - if (pseudoElt !== undefined && pseudoElt !== null) { - pseudoElt = webIDLConversions.DOMString(pseudoElt); - } - - if (pseudoElt !== undefined && pseudoElt !== null && pseudoElt !== "") { - // TODO: Parse pseudoElt - - if (SHADOW_DOM_PSEUDO_REGEXP.test(pseudoElt)) { - throw new TypeError("Tried to get the computed style of a Shadow DOM pseudo-element."); - } - - notImplemented("window.computedStyle(elt, pseudoElt)", this); - } - - const declaration = new CSSStyleDeclaration(); - const { forEach } = Array.prototype; - const { style } = elt; - - forEachMatchingSheetRuleOfElement(elt, rule => { - forEach.call(rule.style, property => { - declaration.setProperty( - property, - rule.style.getPropertyValue(property), - rule.style.getPropertyPriority(property) - ); - }); - }); - - // https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle - const declarations = Object.keys(propertiesWithResolvedValueImplemented); - forEach.call(declarations, property => { - declaration.setProperty(property, getResolvedValue(elt, property)); - }); - - forEach.call(style, property => { - declaration.setProperty(property, style.getPropertyValue(property), style.getPropertyPriority(property)); - }); - - return declaration; - }; - - this.getSelection = function () { - return window._document.getSelection(); - }; - - // The captureEvents() and releaseEvents() methods must do nothing - this.captureEvents = function () {}; - - this.releaseEvents = function () {}; - - // ### PUBLIC DATA PROPERTIES (TODO: should be getters) - - function wrapConsoleMethod(method) { - return (...args) => { - window._virtualConsole.emit(method, ...args); - }; - } - - this.console = { - assert: wrapConsoleMethod("assert"), - clear: wrapConsoleMethod("clear"), - count: wrapConsoleMethod("count"), - countReset: wrapConsoleMethod("countReset"), - debug: wrapConsoleMethod("debug"), - dir: wrapConsoleMethod("dir"), - dirxml: wrapConsoleMethod("dirxml"), - error: wrapConsoleMethod("error"), - group: wrapConsoleMethod("group"), - groupCollapsed: wrapConsoleMethod("groupCollapsed"), - groupEnd: wrapConsoleMethod("groupEnd"), - info: wrapConsoleMethod("info"), - log: wrapConsoleMethod("log"), - table: wrapConsoleMethod("table"), - time: wrapConsoleMethod("time"), - timeLog: wrapConsoleMethod("timeLog"), - timeEnd: wrapConsoleMethod("timeEnd"), - trace: wrapConsoleMethod("trace"), - warn: wrapConsoleMethod("warn") - }; - - function notImplementedMethod(name) { - return function () { - notImplemented(name, window); - }; - } - - define(this, { - name: "", - status: "", - devicePixelRatio: 1, - innerWidth: 1024, - innerHeight: 768, - outerWidth: 1024, - outerHeight: 768, - pageXOffset: 0, - pageYOffset: 0, - screenX: 0, - screenLeft: 0, - screenY: 0, - screenTop: 0, - scrollX: 0, - scrollY: 0, - - alert: notImplementedMethod("window.alert"), - blur: notImplementedMethod("window.blur"), - confirm: notImplementedMethod("window.confirm"), - focus: notImplementedMethod("window.focus"), - moveBy: notImplementedMethod("window.moveBy"), - moveTo: notImplementedMethod("window.moveTo"), - open: notImplementedMethod("window.open"), - print: notImplementedMethod("window.print"), - prompt: notImplementedMethod("window.prompt"), - resizeBy: notImplementedMethod("window.resizeBy"), - resizeTo: notImplementedMethod("window.resizeTo"), - scroll: notImplementedMethod("window.scroll"), - scrollBy: notImplementedMethod("window.scrollBy"), - scrollTo: notImplementedMethod("window.scrollTo") - }); - - // ### INITIALIZATION - - process.nextTick(() => { - if (!window.document) { - return; // window might've been closed already - } - - const documentImpl = idlUtils.implForWrapper(window._document); - - if (window.document.readyState === "complete") { - fireAnEvent("load", window, undefined, {}, documentImpl); - } else { - window.document.addEventListener("load", () => { - fireAnEvent("load", window, undefined, {}, documentImpl); - - if (!documentImpl._pageShowingFlag) { - documentImpl._pageShowingFlag = true; - fireAnEvent("pageshow", window, PageTransitionEvent, { persisted: false }, documentImpl); - } - }); - } - }); -} - -function contextifyWindow(window) { - if (vm.isContext(window)) { - return; - } - - vm.createContext(window); -} - - -/***/ }), - -/***/ 89489: -/***/ ((module) => { - -// Ideally, we would use -// https://html.spec.whatwg.org/multipage/rendering.html#the-css-user-agent-style-sheet-and-presentational-hints -// but for now, just use the version from blink. This file is copied from -// https://chromium.googlesource.com/chromium/blink/+/96aa3a280ab7d67178c8f122a04949ce5f8579e0/Source/core/css/html.css -// (removed a line which had octal literals inside since octal literals are not allowed in template strings) - -// We use a .js file because otherwise we can't browserify this. (brfs is unusable due to lack of ES2015 support) - -module.exports = ` -/* - * The default style sheet used to render HTML. - * - * Copyright (C) 2000 Lars Knoll (knoll@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -@namespace "http://www.w3.org/1999/xhtml"; - -html { - display: block -} - -:root { - scroll-blocks-on: start-touch wheel-event -} - -/* children of the element all have display:none */ -head { - display: none -} - -meta { - display: none -} - -title { - display: none -} - -link { - display: none -} - -style { - display: none -} - -script { - display: none -} - -/* generic block-level elements */ - -body { - display: block; - margin: 8px -} - -p { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1__qem; - -webkit-margin-start: 0; - -webkit-margin-end: 0; -} - -div { - display: block -} - -layer { - display: block -} - -article, aside, footer, header, hgroup, main, nav, section { - display: block -} - -marquee { - display: inline-block; -} - -address { - display: block -} - -blockquote { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 40px; - -webkit-margin-end: 40px; -} - -figcaption { - display: block -} - -figure { - display: block; - -webkit-margin-before: 1em; - -webkit-margin-after: 1em; - -webkit-margin-start: 40px; - -webkit-margin-end: 40px; -} - -q { - display: inline -} - -/* nwmatcher does not support ::before and ::after, so we can't render q -correctly: https://html.spec.whatwg.org/multipage/rendering.html#phrasing-content-3 -TODO: add q::before and q::after selectors -*/ - -center { - display: block; - /* special centering to be able to emulate the html4/netscape behaviour */ - text-align: -webkit-center -} - -hr { - display: block; - -webkit-margin-before: 0.5em; - -webkit-margin-after: 0.5em; - -webkit-margin-start: auto; - -webkit-margin-end: auto; - border-style: inset; - border-width: 1px; - box-sizing: border-box -} - -map { - display: inline -} - -video { - object-fit: contain; -} - -/* heading elements */ - -h1 { - display: block; - font-size: 2em; - -webkit-margin-before: 0.67__qem; - -webkit-margin-after: 0.67em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -article h1, -aside h1, -nav h1, -section h1 { - font-size: 1.5em; - -webkit-margin-before: 0.83__qem; - -webkit-margin-after: 0.83em; -} - -article article h1, -article aside h1, -article nav h1, -article section h1, -aside article h1, -aside aside h1, -aside nav h1, -aside section h1, -nav article h1, -nav aside h1, -nav nav h1, -nav section h1, -section article h1, -section aside h1, -section nav h1, -section section h1 { - font-size: 1.17em; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; -} - -/* Remaining selectors are deleted because nwmatcher does not support -:matches() and expanding the selectors manually would be far too verbose. -Also see https://html.spec.whatwg.org/multipage/rendering.html#sections-and-headings -TODO: rewrite to use :matches() when nwmatcher supports it. -*/ - -h2 { - display: block; - font-size: 1.5em; - -webkit-margin-before: 0.83__qem; - -webkit-margin-after: 0.83em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -h3 { - display: block; - font-size: 1.17em; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -h4 { - display: block; - -webkit-margin-before: 1.33__qem; - -webkit-margin-after: 1.33em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -h5 { - display: block; - font-size: .83em; - -webkit-margin-before: 1.67__qem; - -webkit-margin-after: 1.67em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -h6 { - display: block; - font-size: .67em; - -webkit-margin-before: 2.33__qem; - -webkit-margin-after: 2.33em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - font-weight: bold -} - -/* tables */ - -table { - display: table; - border-collapse: separate; - border-spacing: 2px; - border-color: gray -} - -thead { - display: table-header-group; - vertical-align: middle; - border-color: inherit -} - -tbody { - display: table-row-group; - vertical-align: middle; - border-color: inherit -} - -tfoot { - display: table-footer-group; - vertical-align: middle; - border-color: inherit -} - -/* for tables without table section elements (can happen with XHTML or dynamically created tables) */ -table > tr { - vertical-align: middle; -} - -col { - display: table-column -} - -colgroup { - display: table-column-group -} - -tr { - display: table-row; - vertical-align: inherit; - border-color: inherit -} - -td, th { - display: table-cell; - vertical-align: inherit -} - -th { - font-weight: bold -} - -caption { - display: table-caption; - text-align: -webkit-center -} - -/* lists */ - -ul, menu, dir { - display: block; - list-style-type: disc; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - -webkit-padding-start: 40px -} - -ol { - display: block; - list-style-type: decimal; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; - -webkit-padding-start: 40px -} - -li { - display: list-item; - text-align: -webkit-match-parent; -} - -ul ul, ol ul { - list-style-type: circle -} - -ol ol ul, ol ul ul, ul ol ul, ul ul ul { - list-style-type: square -} - -dd { - display: block; - -webkit-margin-start: 40px -} - -dl { - display: block; - -webkit-margin-before: 1__qem; - -webkit-margin-after: 1em; - -webkit-margin-start: 0; - -webkit-margin-end: 0; -} - -dt { - display: block -} - -ol ul, ul ol, ul ul, ol ol { - -webkit-margin-before: 0; - -webkit-margin-after: 0 -} - -/* form elements */ - -form { - display: block; - margin-top: 0__qem; -} - -label { - cursor: default; -} - -legend { - display: block; - -webkit-padding-start: 2px; - -webkit-padding-end: 2px; - border: none -} - -fieldset { - display: block; - -webkit-margin-start: 2px; - -webkit-margin-end: 2px; - -webkit-padding-before: 0.35em; - -webkit-padding-start: 0.75em; - -webkit-padding-end: 0.75em; - -webkit-padding-after: 0.625em; - border: 2px groove ThreeDFace; - min-width: -webkit-min-content; -} - -button { - -webkit-appearance: button; -} - -/* Form controls don't go vertical. */ -input, textarea, select, button, meter, progress { - -webkit-writing-mode: horizontal-tb !important; -} - -input, textarea, select, button { - margin: 0__qem; - font: -webkit-small-control; - text-rendering: auto; /* FIXME: Remove when tabs work with optimizeLegibility. */ - color: initial; - letter-spacing: normal; - word-spacing: normal; - line-height: normal; - text-transform: none; - text-indent: 0; - text-shadow: none; - display: inline-block; - text-align: start; -} - -/* TODO: Add " i" to attribute matchers to support case-insensitive matching */ -input[type="hidden"] { - display: none -} - -input { - -webkit-appearance: textfield; - padding: 1px; - background-color: white; - border: 2px inset; - -webkit-rtl-ordering: logical; - -webkit-user-select: text; - cursor: auto; -} - -input[type="search"] { - -webkit-appearance: searchfield; - box-sizing: border-box; -} - -select { - border-radius: 5px; -} - -textarea { - -webkit-appearance: textarea; - background-color: white; - border: 1px solid; - -webkit-rtl-ordering: logical; - -webkit-user-select: text; - flex-direction: column; - resize: auto; - cursor: auto; - padding: 2px; - white-space: pre-wrap; - word-wrap: break-word; -} - -input[type="password"] { - -webkit-text-security: disc !important; -} - -input[type="hidden"], input[type="image"], input[type="file"] { - -webkit-appearance: initial; - padding: initial; - background-color: initial; - border: initial; -} - -input[type="file"] { - align-items: baseline; - color: inherit; - text-align: start !important; -} - -input[type="radio"], input[type="checkbox"] { - margin: 3px 0.5ex; - padding: initial; - background-color: initial; - border: initial; -} - -input[type="button"], input[type="submit"], input[type="reset"] { - -webkit-appearance: push-button; - -webkit-user-select: none; - white-space: pre -} - -input[type="button"], input[type="submit"], input[type="reset"], button { - align-items: flex-start; - text-align: center; - cursor: default; - color: ButtonText; - padding: 2px 6px 3px 6px; - border: 2px outset ButtonFace; - background-color: ButtonFace; - box-sizing: border-box -} - -input[type="range"] { - -webkit-appearance: slider-horizontal; - padding: initial; - border: initial; - margin: 2px; - color: #909090; -} - -input[type="button"]:disabled, input[type="submit"]:disabled, input[type="reset"]:disabled, -button:disabled, select:disabled, optgroup:disabled, option:disabled, -select[disabled]>option { - color: GrayText -} - -input[type="button"]:active, input[type="submit"]:active, input[type="reset"]:active, button:active { - border-style: inset -} - -input[type="button"]:active:disabled, input[type="submit"]:active:disabled, input[type="reset"]:active:disabled, button:active:disabled { - border-style: outset -} - -datalist { - display: none -} - -area { - display: inline; - cursor: pointer; -} - -param { - display: none -} - -input[type="checkbox"] { - -webkit-appearance: checkbox; - box-sizing: border-box; -} - -input[type="radio"] { - -webkit-appearance: radio; - box-sizing: border-box; -} - -input[type="color"] { - -webkit-appearance: square-button; - width: 44px; - height: 23px; - background-color: ButtonFace; - /* Same as native_theme_base. */ - border: 1px #a9a9a9 solid; - padding: 1px 2px; -} - -input[type="color"][list] { - -webkit-appearance: menulist; - width: 88px; - height: 23px -} - -select { - -webkit-appearance: menulist; - box-sizing: border-box; - align-items: center; - border: 1px solid; - white-space: pre; - -webkit-rtl-ordering: logical; - color: black; - background-color: white; - cursor: default; -} - -optgroup { - font-weight: bolder; - display: block; -} - -option { - font-weight: normal; - display: block; - padding: 0 2px 1px 2px; - white-space: pre; - min-height: 1.2em; -} - -output { - display: inline; -} - -/* meter */ - -meter { - -webkit-appearance: meter; - box-sizing: border-box; - display: inline-block; - height: 1em; - width: 5em; - vertical-align: -0.2em; -} - -/* progress */ - -progress { - -webkit-appearance: progress-bar; - box-sizing: border-box; - display: inline-block; - height: 1em; - width: 10em; - vertical-align: -0.2em; -} - -/* inline elements */ - -u, ins { - text-decoration: underline -} - -strong, b { - font-weight: bold -} - -i, cite, em, var, address, dfn { - font-style: italic -} - -tt, code, kbd, samp { - font-family: monospace -} - -pre, xmp, plaintext, listing { - display: block; - font-family: monospace; - white-space: pre; - margin: 1__qem 0 -} - -mark { - background-color: yellow; - color: black -} - -big { - font-size: larger -} - -small { - font-size: smaller -} - -s, strike, del { - text-decoration: line-through -} - -sub { - vertical-align: sub; - font-size: smaller -} - -sup { - vertical-align: super; - font-size: smaller -} - -nobr { - white-space: nowrap -} - -/* states */ - -:focus { - outline: auto 5px -webkit-focus-ring-color -} - -/* Read-only text fields do not show a focus ring but do still receive focus */ -html:focus, body:focus, input[readonly]:focus { - outline: none -} - -embed:focus, iframe:focus, object:focus { - outline: none -} - -input:focus, textarea:focus, select:focus { - outline-offset: -2px -} - -input[type="button"]:focus, -input[type="checkbox"]:focus, -input[type="file"]:focus, -input[type="hidden"]:focus, -input[type="image"]:focus, -input[type="radio"]:focus, -input[type="reset"]:focus, -input[type="search"]:focus, -input[type="submit"]:focus { - outline-offset: 0 -} - -/* HTML5 ruby elements */ - -ruby, rt { - text-indent: 0; /* blocks used for ruby rendering should not trigger this */ -} - -rt { - line-height: normal; - -webkit-text-emphasis: none; -} - -ruby > rt { - display: block; - font-size: 50%; - text-align: start; -} - -ruby > rp { - display: none; -} - -/* other elements */ - -noframes { - display: none -} - -frameset, frame { - display: block -} - -frameset { - border-color: inherit -} - -iframe { - border: 2px inset -} - -details { - display: block -} - -summary { - display: block -} - -template { - display: none -} - -bdi, output { - unicode-bidi: -webkit-isolate; -} - -bdo { - unicode-bidi: bidi-override; -} - -textarea[dir=auto] { - unicode-bidi: -webkit-plaintext; -} - -dialog:not([open]) { - display: none -} - -dialog { - position: absolute; - left: 0; - right: 0; - width: -webkit-fit-content; - height: -webkit-fit-content; - margin: auto; - border: solid; - padding: 1em; - background: white; - color: black -} - -[hidden] { - display: none -} - -/* noscript is handled internally, as it depends on settings. */ - -`; - - -/***/ }), - -/***/ 42751: -/***/ ((module) => { - -"use strict"; - - -module.exports = function (nameForErrorMessage, window) { - if (!window) { - // Do nothing for window-less documents. - return; - } - - const error = new Error(`Not implemented: ${nameForErrorMessage}`); - error.type = "not implemented"; - - window._virtualConsole.emit("jsdomError", error); -}; - - -/***/ }), - -/***/ 53601: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const parse5 = __nccwpck_require__(65598); - -const { createElement } = __nccwpck_require__(98548); -const { HTML_NS } = __nccwpck_require__(52635); - -const DocumentType = __nccwpck_require__(53193); -const DocumentFragment = __nccwpck_require__(11490); -const Text = __nccwpck_require__(49374); -const Comment = __nccwpck_require__(56625); - -const attributes = __nccwpck_require__(35092); -const nodeTypes = __nccwpck_require__(10656); - -const serializationAdapter = __nccwpck_require__(19756); -const { - customElementReactionsStack, invokeCEReactions, lookupCEDefinition -} = __nccwpck_require__(25392); - -// Horrible monkey-patch to implement https://github.com/inikulin/parse5/issues/237 and -// https://github.com/inikulin/parse5/issues/285. -const OpenElementStack = __nccwpck_require__(64813); - -const openElementStackOriginalPush = OpenElementStack.prototype.push; -OpenElementStack.prototype.push = function (...args) { - openElementStackOriginalPush.apply(this, args); - this.treeAdapter._currentElement = this.current; - - const after = this.items[this.stackTop]; - if (after._pushedOnStackOfOpenElements) { - after._pushedOnStackOfOpenElements(); - } -}; - -const openElementStackOriginalPop = OpenElementStack.prototype.pop; -OpenElementStack.prototype.pop = function (...args) { - const before = this.items[this.stackTop]; - - openElementStackOriginalPop.apply(this, args); - this.treeAdapter._currentElement = this.current; - - if (before._poppedOffStackOfOpenElements) { - before._poppedOffStackOfOpenElements(); - } -}; - -class JSDOMParse5Adapter { - constructor(documentImpl, options = {}) { - this._documentImpl = documentImpl; - this._globalObject = documentImpl._globalObject; - this._fragment = options.fragment || false; - - // Since the createElement hook doesn't provide the parent element, we keep track of this using _currentElement: - // https://github.com/inikulin/parse5/issues/285. See above horrible monkey-patch for how this is maintained. - this._currentElement = undefined; - } - - _ownerDocument() { - const { _currentElement } = this; - - // The _currentElement is undefined when parsing elements at the root of the document. - if (_currentElement) { - return _currentElement.localName === "template" && _currentElement.namespaceURI === HTML_NS ? - _currentElement.content._ownerDocument : - _currentElement._ownerDocument; - } - - return this._documentImpl; - } - - createDocument() { - // parse5's model assumes that parse(html) will call into here to create the new Document, then return it. However, - // jsdom's model assumes we can create a Window (and through that create an empty Document), do some other setup - // stuff, and then parse, stuffing nodes into that Document as we go. So to adapt between these two models, we just - // return the already-created Document when asked by parse5 to "create" a Document. - return this._documentImpl; - } - - createDocumentFragment() { - const ownerDocument = this._ownerDocument(); - return DocumentFragment.createImpl(this._globalObject, [], { ownerDocument }); - } - - // https://html.spec.whatwg.org/#create-an-element-for-the-token - createElement(localName, namespace, attrs) { - const ownerDocument = this._ownerDocument(); - - const isAttribute = attrs.find(attr => attr.name === "is"); - const isValue = isAttribute ? isAttribute.value : null; - - const definition = lookupCEDefinition(ownerDocument, namespace, localName); - - let willExecuteScript = false; - if (definition !== null && !this._fragment) { - willExecuteScript = true; - } - - if (willExecuteScript) { - ownerDocument._throwOnDynamicMarkupInsertionCounter++; - customElementReactionsStack.push([]); - } - - const element = createElement(ownerDocument, localName, namespace, null, isValue, willExecuteScript); - this.adoptAttributes(element, attrs); - - if (willExecuteScript) { - const queue = customElementReactionsStack.pop(); - invokeCEReactions(queue); - ownerDocument._throwOnDynamicMarkupInsertionCounter--; - } - - if ("_parserInserted" in element) { - element._parserInserted = true; - } - - return element; - } - - createCommentNode(data) { - const ownerDocument = this._ownerDocument(); - return Comment.createImpl(this._globalObject, [], { data, ownerDocument }); - } - - appendChild(parentNode, newNode) { - parentNode._append(newNode); - } - - insertBefore(parentNode, newNode, referenceNode) { - parentNode._insert(newNode, referenceNode); - } - - setTemplateContent(templateElement, contentFragment) { - // This code makes the glue between jsdom and parse5 HTMLTemplateElement parsing: - // - // * jsdom during the construction of the HTMLTemplateElement (for example when create via - // `document.createElement("template")`), creates a DocumentFragment and set it into _templateContents. - // * parse5 when parsing a