From 5970bd934af6386e4434234005ae2d2fa892046e Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 01/10] chore(deps): migrate to ESM-native action runtime stack Breaking infrastructure migration to align with the actions/typescript-action template's ESM module system. Production deps: - @actions/core: ^1.10.1 -> ^3.0.1 (pure ESM, APIs unchanged) - @actions/github: ^6.0.0 -> ^9.0.0 (pure ESM, eliminates http-client v2/v4 conflict with core@3) Dev deps: - remove @vercel/ncc (replaced by rollup) - add rollup, @rollup/plugin-commonjs, @rollup/plugin-node-resolve, @rollup/plugin-json, rollup-plugin-esbuild - add rimraf, tslib, @jest/globals, ts-jest-resolver for ESM test mode Package metadata: - add "type": "module" - add "exports": {".": "./dist/index.js"} - add "engines": {"node": ">=24.0.0"} - update "main" to "dist/index.js" - bump version to 3.0.0 (major: ESM runtime migration) - build script: tsc -> tsc --noEmit (type-check only; bundling handled by rollup) - package script: ncc -> rollup - test script: add NODE_OPTIONS=--experimental-vm-modules for Jest ESM mode --- package-lock.json | 3288 +++++++++++++++++++++++++++++++++------------ package.json | 42 +- 2 files changed, 2493 insertions(+), 837 deletions(-) diff --git a/package-lock.json b/package-lock.json index 9c42fbe..e992bbd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,16 +1,16 @@ { "name": "@opsless/ms-teams-github-actions", - "version": "2.1.0", + "version": "3.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@opsless/ms-teams-github-actions", - "version": "2.1.0", + "version": "3.0.0", "license": "MIT", "dependencies": { - "@actions/core": "^1.10.1", - "@actions/github": "^6.0.0", + "@actions/core": "^3.0.1", + "@actions/github": "^9.0.0", "adaptive-expressions": "^4.20.1", "adaptivecards": "^3.0.1", "adaptivecards-templating": "^2.3.1", @@ -20,69 +20,94 @@ "@eslint/compat": "^2.0.2", "@eslint/eslintrc": "^3.3.3", "@eslint/js": "^10.0.1", + "@jest/globals": "^30.2.0", + "@rollup/plugin-commonjs": "^29.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", "@types/jest": "^30.0.0", "@types/node": "^25.2.3", "@typescript-eslint/eslint-plugin": "^8.56.0", "@typescript-eslint/parser": "^8.56.0", - "@vercel/ncc": "^0.38.0", + "esbuild": "^0.28.1", "eslint": "^10.0.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-jest": "^29.15.0", "eslint-plugin-prettier": "^5.5.5", "jest": "^30.2.0", "prettier": "^3.8.1", + "rimraf": "^6.0.1", + "rollup": "^4.57.1", + "rollup-plugin-esbuild": "^6.2.1", "ts-jest": "^29.4.6", + "ts-jest-resolver": "^2.0.1", + "tslib": "^2.8.1", "typescript": "^5.9.3" + }, + "engines": { + "node": ">=24.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-linux-x64-gnu": "*" } }, "node_modules/@actions/core": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.11.1.tgz", - "integrity": "sha512-hXJCSrkwfA46Vd9Z3q4cpEpHB1rL5NG04+/rbqW9d3+CSvtB1tYe8UTpAlixa1vj0m/ULglfEK2UKxMGxCxv5A==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-3.0.1.tgz", + "integrity": "sha512-a6d/Nwahm9fliVGRhdhofo40HjHQasUPusmc7vBfyky+7Z+P2A1J68zyFVaNcEclc/Se+eO595oAr5nwEIoIUA==", "license": "MIT", "dependencies": { - "@actions/exec": "^1.1.1", - "@actions/http-client": "^2.0.1" + "@actions/exec": "^3.0.0", + "@actions/http-client": "^4.0.0" } }, "node_modules/@actions/exec": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.1.1.tgz", - "integrity": "sha512-+sCcHHbVdk93a0XT19ECtO/gIXoxvdsgQLzb2fE2/5sIZmWQuluYyjPQtrtTHdU1YzTZ7bAPN4sITq2xi1679w==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@actions/exec/-/exec-3.0.0.tgz", + "integrity": "sha512-6xH/puSoNBXb72VPlZVm7vQ+svQpFyA96qdDBvhB8eNZOE8LtPf9L4oAsfzK/crCL8YZ+19fKYVnM63Sl+Xzlw==", "license": "MIT", "dependencies": { - "@actions/io": "^1.0.1" + "@actions/io": "^3.0.2" } }, "node_modules/@actions/github": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@actions/github/-/github-6.0.1.tgz", - "integrity": "sha512-xbZVcaqD4XnQAe35qSQqskb3SqIAfRyLBrHMd/8TuL7hJSz2QtbDwnNM8zWx4zO5l2fnGtseNE3MbEvD7BxVMw==", + "version": "9.1.1", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-9.1.1.tgz", + "integrity": "sha512-tL5JbYOBZHc0ngEnCsaDcryUizIUIlQyIMwy1Wkx93H5HzbBJ7TbiPx2PnFjBwZW0Vh05JmfFZhecE6gglYegA==", + "license": "MIT", + "dependencies": { + "@actions/http-client": "^3.0.2", + "@octokit/core": "^7.0.6", + "@octokit/plugin-paginate-rest": "^14.0.0", + "@octokit/plugin-rest-endpoint-methods": "^17.0.0", + "@octokit/request": "^10.0.7", + "@octokit/request-error": "^7.1.0", + "undici": "^6.23.0" + } + }, + "node_modules/@actions/github/node_modules/@actions/http-client": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-3.0.2.tgz", + "integrity": "sha512-JP38FYYpyqvUsz+Igqlc/JG6YO9PaKuvqjM3iGvaLqFnJ7TFmcLyy2IDrY0bI0qCQug8E9K+elv5ZNfw62ZJzA==", "license": "MIT", "dependencies": { - "@actions/http-client": "^2.2.0", - "@octokit/core": "^5.0.1", - "@octokit/plugin-paginate-rest": "^9.2.2", - "@octokit/plugin-rest-endpoint-methods": "^10.4.0", - "@octokit/request": "^8.4.1", - "@octokit/request-error": "^5.1.1", - "undici": "^5.28.5" + "tunnel": "^0.0.6", + "undici": "^6.23.0" } }, "node_modules/@actions/http-client": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz", - "integrity": "sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-4.0.1.tgz", + "integrity": "sha512-+Nvd1ImaOZBSoPbsUtEhv+1z99H12xzncCkz0a3RuehINE81FZSe2QTj3uvAPTcJX/SCzUQHQ0D1GrPMbrPitg==", "license": "MIT", "dependencies": { "tunnel": "^0.0.6", - "undici": "^5.25.4" + "undici": "^6.23.0" } }, "node_modules/@actions/io": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@actions/io/-/io-1.1.3.tgz", - "integrity": "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@actions/io/-/io-3.0.2.tgz", + "integrity": "sha512-nRBchcMM+QK1pdjO7/idu86rbJI5YHUKCvKs0KxnSYbVe3F51UfGxuZX4Qy/fWlp6l7gWFwIkrOzN+oUK03kfw==", "license": "MIT" }, "node_modules/@babel/code-frame": { @@ -635,1015 +660,1863 @@ "tslib": "^2.4.0" } }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", - "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], "dev": true, "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, + "optional": true, + "os": [ + "aix" + ], "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + "node": ">=18" } }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + "node": ">=18" } }, - "node_modules/@eslint/compat": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.0.tgz", - "integrity": "sha512-LgaSCymEpw7tF53xvDw9SNsraPb1IBHxpdABIOM0hW8UAlP8znrjYtuxfR58FSJ3L9BhwD+FaPRFQpZq84Nh6g==", + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1" - }, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "peerDependencies": { - "eslint": "^8.40 || 9 || 10" - }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } + "node": ">=18" } }, - "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/object-schema": "^3.0.5", - "debug": "^4.3.1", - "minimatch": "^10.2.4" - }, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": ">=18" } }, - "node_modules/@eslint/config-array/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "18 || 20 || >=22" + "node": ">=18" } }, - "node_modules/@eslint/config-array/node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": "18 || 20 || >=22" + "node": ">=18" } }, - "node_modules/@eslint/config-array/node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=18" } }, - "node_modules/@eslint/config-helpers": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.6.0.tgz", - "integrity": "sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA==", + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1" - }, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": ">=18" } }, - "node_modules/@eslint/core": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", - "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": ">=18" } }, - "node_modules/@eslint/eslintrc": { - "version": "3.3.5", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", - "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "ajv": "^6.14.0", - "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.1", - "minimatch": "^3.1.5", - "strip-json-comments": "^3.1.1" - }, + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" + "node": ">=18" } }, - "node_modules/@eslint/js": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", - "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "eslint": "^10.0.0" - }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } + "node": ">=18" } }, - "node_modules/@eslint/object-schema": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", - "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": ">=18" } }, - "node_modules/@eslint/plugin-kit": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.2.tgz", - "integrity": "sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==", + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/compat": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.0.tgz", + "integrity": "sha512-LgaSCymEpw7tF53xvDw9SNsraPb1IBHxpdABIOM0hW8UAlP8znrjYtuxfR58FSJ3L9BhwD+FaPRFQpZq84Nh6g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "peerDependencies": { + "eslint": "^8.40 || 9 || 10" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.5", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", + "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^10.2.4" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-array/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.6.0.tgz", + "integrity": "sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.2.tgz", + "integrity": "sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", "dev": true, "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", + "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.4.1.tgz", + "integrity": "sha512-v3bhyxUh9Hgmo5p6hAOXe14/R3ZxZDOsvHleh4B07z3m/x4/ngPUXEm9XwK4sF4u+f+P2ORb0Ge+MgpaqRMVDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "30.4.1", + "@types/node": "*", + "chalk": "^4.1.2", + "jest-message-util": "30.4.1", + "jest-util": "30.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/core": { + "version": "30.4.2", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.4.2.tgz", + "integrity": "sha512-TZJA6cPJUFxoWhxaLo8t0VX/MZX2wPWr0uIDvLSHIvN4gu9h02vSzqI2kBADG1ExqQlC+cY09xKMSreivvrChQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "30.4.1", + "@jest/pattern": "30.4.0", + "@jest/reporters": "30.4.1", + "@jest/test-result": "30.4.1", + "@jest/transform": "30.4.1", + "@jest/types": "30.4.1", + "@types/node": "*", + "ansi-escapes": "^4.3.2", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "exit-x": "^0.2.2", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.11", + "jest-changed-files": "30.4.1", + "jest-config": "30.4.2", + "jest-haste-map": "30.4.1", + "jest-message-util": "30.4.1", + "jest-regex-util": "30.4.0", + "jest-resolve": "30.4.1", + "jest-resolve-dependencies": "30.4.2", + "jest-runner": "30.4.2", + "jest-runtime": "30.4.2", + "jest-snapshot": "30.4.1", + "jest-util": "30.4.1", + "jest-validate": "30.4.1", + "jest-watcher": "30.4.1", + "pretty-format": "30.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/diff-sequences": { + "version": "30.4.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz", + "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/environment": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.4.1.tgz", + "integrity": "sha512-AK9yNRqgKxiabqMoe4oW+3/TSSeV8vkdC7BGaxZdU0AFXfOpofTLqdru2GXKZghP3sdgwE9XXpnVwfZ8JnFV4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/fake-timers": "30.4.1", + "@jest/types": "30.4.1", + "@types/node": "*", + "jest-mock": "30.4.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.4.1.tgz", + "integrity": "sha512-ginrj6TMgh2GshLUGCjO94Ptx9HhdZA/I6A9iUfyeLKFtdAjnKzHDgzgP9HYQgbxM1lbXScQ2eUBz2lGeVDPWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "expect": "30.4.1", + "jest-snapshot": "30.4.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.4.1.tgz", + "integrity": "sha512-ZBn5CglH8fBsQsvs4VWNzD4aWfUYks+IdOOQU3MEK71ol/BcVm+P+rtb1KpiFBpSWSCE27uOahyyf1vfqOVbcQ==", + "dev": true, + "license": "MIT", "dependencies": { - "@eslint/core": "^1.2.1", - "levn": "^0.4.1" + "@jest/get-type": "30.1.0" }, "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@fastify/busboy": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", - "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "node_modules/@jest/fake-timers": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.4.1.tgz", + "integrity": "sha512-iW5umdmfPeWzehrVhugFQZqCchSCud5S1l2YT0O9ZhjRR0ExclANDZkiSBwzqtnlOn0J1JXvO+HZ6rkuyOVOgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "30.4.1", + "@sinonjs/fake-timers": "^15.4.0", + "@types/node": "*", + "jest-message-util": "30.4.1", + "jest-mock": "30.4.1", + "jest-util": "30.4.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/get-type": { + "version": "30.1.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", + "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", + "dev": true, "license": "MIT", "engines": { - "node": ">=14" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@humanfs/core": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", - "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "node_modules/@jest/globals": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.4.1.tgz", + "integrity": "sha512-ZbuY4cmXC8DkxYjfvT2DbcHWL2T6vmsMhXCDcmTB2T0y0gaezBI77ufq5ZAIdcRkYZ7NEQEDg1xFeKbxUJ5v5Q==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "@humanfs/types": "^0.15.0" + "@jest/environment": "30.4.1", + "@jest/expect": "30.4.1", + "@jest/types": "30.4.1", + "jest-mock": "30.4.1" }, "engines": { - "node": ">=18.18.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@humanfs/node": { - "version": "0.16.8", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", - "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "node_modules/@jest/pattern": { + "version": "30.4.0", + "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.4.0.tgz", + "integrity": "sha512-RAWn3+f9u8BsHijKJ71uHcFp6vmyEt6VvoWXkl6hKF3qVIuWNmudVjg12DlBPGup/frIl5UcUlH5HfEuvHpEXg==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "@humanfs/core": "^0.19.2", - "@humanfs/types": "^0.15.0", - "@humanwhocodes/retry": "^0.4.0" + "@types/node": "*", + "jest-regex-util": "30.4.0" }, "engines": { - "node": ">=18.18.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@humanfs/types": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", - "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "node_modules/@jest/reporters": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.4.1.tgz", + "integrity": "sha512-/SnkPCzEQpUaBH81kjdEdDdo2WZl5hxw+BmLDGWjRkm8o7XlhjwsU36cqwe5PGBE5WYpBvDzRSdXx9rbGuJtNA==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "30.4.1", + "@jest/test-result": "30.4.1", + "@jest/transform": "30.4.1", + "@jest/types": "30.4.1", + "@jridgewell/trace-mapping": "^0.3.25", + "@types/node": "*", + "chalk": "^4.1.2", + "collect-v8-coverage": "^1.0.2", + "exit-x": "^0.2.2", + "glob": "^10.5.0", + "graceful-fs": "^4.2.11", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^6.0.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^5.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "30.4.1", + "jest-util": "30.4.1", + "jest-worker": "30.4.1", + "slash": "^3.0.0", + "string-length": "^4.0.2", + "v8-to-istanbul": "^9.0.1" + }, "engines": { - "node": ">=18.18.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } } }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "node_modules/@jest/schemas": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz", + "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.34.0" + }, "engines": { - "node": ">=12.22" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/snapshot-utils": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.4.1.tgz", + "integrity": "sha512-ObY4ljvQ95mt6iwKtVLetR/4yXiAgl3H4nJxhztr0MTjrN97TwDYrnCp/kF60Ec9HdhkWTHSu+Hg05aXfngpOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "30.4.1", + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", + "natural-compare": "^1.4.0" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", - "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "node_modules/@jest/source-map": { + "version": "30.0.1", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.0.1.tgz", + "integrity": "sha512-MIRWMUUR3sdbP36oyNyhbThLHyJ2eEDClPCiHVbrYAe5g3CHRArIVpBw7cdSB5fr+ofSfIb2Tnsw8iEHL0PYQg==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "callsites": "^3.1.0", + "graceful-fs": "^4.2.11" + }, "engines": { - "node": ">=18.18" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.4.1.tgz", + "integrity": "sha512-/ZG7pgEiOmmWkN9TplKbOu4id2N5lh7FHwRwlkgBVAzGdRH+OkkQ8wX/kIxg4zmd3ZQvAL1RwL2yWsvNYYECTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/console": "30.4.1", + "@jest/types": "30.4.1", + "@types/istanbul-lib-coverage": "^2.0.6", + "collect-v8-coverage": "^1.0.2" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "node_modules/@jest/test-sequencer": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.4.1.tgz", + "integrity": "sha512-PeYE+4td5rKjoRPxztObrXU+H8hsjZfxKMXOcmrr34JerSyB/ROOxbbicz8B7A5j9R9VayDnVPvBmedqCsFCdw==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + "@jest/test-result": "30.4.1", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.4.1.tgz", + "integrity": "sha512-Wz0LyktlTvRefoymh+n64hQ84KNXsRGcwdoZ8CSa0Ea+fgYcHZlnk+hDP7v2MS7il2bQ5uTEIxf4/NNfhMN4KQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.27.4", + "@jest/types": "30.4.1", + "@jridgewell/trace-mapping": "^0.3.25", + "babel-plugin-istanbul": "^7.0.1", + "chalk": "^4.1.2", + "convert-source-map": "^2.0.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.4.1", + "jest-regex-util": "30.4.0", + "jest-util": "30.4.1", + "pirates": "^4.0.7", + "slash": "^3.0.0", + "write-file-atomic": "^5.0.1" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/types": { + "version": "30.4.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.4.1.tgz", + "integrity": "sha512-f1x/vJXIfjOlEmejYpbkbgw1gOqpPECwMvMEtBqe47j7H2Hg8h8w3o3ikhSXq3MI15kg+oQ0exWO0uCtTNJLoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/pattern": "30.4.0", + "@jest/schemas": "30.4.1", + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-reports": "^3.0.4", + "@types/node": "*", + "@types/yargs": "^17.0.33", + "chalk": "^4.1.2" }, "engines": { - "node": ">=12" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", "dev": true, "license": "MIT", "dependencies": { - "sprintf-js": "~1.0.2" + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "dev": true, "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, "engines": { - "node": ">=8" + "node": ">=6.0.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, "license": "MIT", "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, + "node_modules/@microsoft/recognizers-text-data-types-timex-expression": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@microsoft/recognizers-text-data-types-timex-expression/-/recognizers-text-data-types-timex-expression-1.3.1.tgz", + "integrity": "sha512-jarJIFIJZBqeofy3hh0vdQo1yOmTM+jCjj6/zmo9JunsQ6LO750eZHCg9eLptQhsvq321XCt5xdRNLCwU8YeNA==", "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, "engines": { - "node": ">=8" + "node": ">=10.3.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", + "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", "dev": true, "license": "MIT", + "optional": true, "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" + "@tybys/wasm-util": "^0.10.2" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, + "node_modules/@octokit/auth-token": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-6.0.0.tgz", + "integrity": "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==", "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, "engines": { - "node": ">=8" + "node": ">= 20" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, + "node_modules/@octokit/core": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.6.tgz", + "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==", "license": "MIT", + "dependencies": { + "@octokit/auth-token": "^6.0.0", + "@octokit/graphql": "^9.0.3", + "@octokit/request": "^10.0.6", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "before-after-hook": "^4.0.0", + "universal-user-agent": "^7.0.0" + }, "engines": { - "node": ">=8" + "node": ">= 20" } }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", - "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", - "dev": true, + "node_modules/@octokit/endpoint": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.3.tgz", + "integrity": "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==", "license": "MIT", + "dependencies": { + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.2" + }, "engines": { - "node": ">=8" + "node": ">= 20" } }, - "node_modules/@jest/console": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.4.1.tgz", - "integrity": "sha512-v3bhyxUh9Hgmo5p6hAOXe14/R3ZxZDOsvHleh4B07z3m/x4/ngPUXEm9XwK4sF4u+f+P2ORb0Ge+MgpaqRMVDA==", - "dev": true, + "node_modules/@octokit/graphql": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.3.tgz", + "integrity": "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==", "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", - "@types/node": "*", - "chalk": "^4.1.2", - "jest-message-util": "30.4.1", - "jest-util": "30.4.1", - "slash": "^3.0.0" + "@octokit/request": "^10.0.6", + "@octokit/types": "^16.0.0", + "universal-user-agent": "^7.0.0" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">= 20" } }, - "node_modules/@jest/core": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.4.2.tgz", - "integrity": "sha512-TZJA6cPJUFxoWhxaLo8t0VX/MZX2wPWr0uIDvLSHIvN4gu9h02vSzqI2kBADG1ExqQlC+cY09xKMSreivvrChQ==", - "dev": true, + "node_modules/@octokit/openapi-types": { + "version": "27.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-27.0.0.tgz", + "integrity": "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-paginate-rest": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-14.0.0.tgz", + "integrity": "sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==", "license": "MIT", "dependencies": { - "@jest/console": "30.4.1", - "@jest/pattern": "30.4.0", - "@jest/reporters": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", - "@types/node": "*", - "ansi-escapes": "^4.3.2", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "exit-x": "^0.2.2", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.11", - "jest-changed-files": "30.4.1", - "jest-config": "30.4.2", - "jest-haste-map": "30.4.1", - "jest-message-util": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-resolve": "30.4.1", - "jest-resolve-dependencies": "30.4.2", - "jest-runner": "30.4.2", - "jest-runtime": "30.4.2", - "jest-snapshot": "30.4.1", - "jest-util": "30.4.1", - "jest-validate": "30.4.1", - "jest-watcher": "30.4.1", - "pretty-format": "30.4.1", - "slash": "^3.0.0" + "@octokit/types": "^16.0.0" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">= 20" }, "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } + "@octokit/core": ">=6" } }, - "node_modules/@jest/diff-sequences": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz", - "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/environment": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.4.1.tgz", - "integrity": "sha512-AK9yNRqgKxiabqMoe4oW+3/TSSeV8vkdC7BGaxZdU0AFXfOpofTLqdru2GXKZghP3sdgwE9XXpnVwfZ8JnFV4w==", - "dev": true, + "node_modules/@octokit/plugin-rest-endpoint-methods": { + "version": "17.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz", + "integrity": "sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==", "license": "MIT", "dependencies": { - "@jest/fake-timers": "30.4.1", - "@jest/types": "30.4.1", - "@types/node": "*", - "jest-mock": "30.4.1" + "@octokit/types": "^16.0.0" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" } }, - "node_modules/@jest/expect": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.4.1.tgz", - "integrity": "sha512-ginrj6TMgh2GshLUGCjO94Ptx9HhdZA/I6A9iUfyeLKFtdAjnKzHDgzgP9HYQgbxM1lbXScQ2eUBz2lGeVDPWA==", - "dev": true, + "node_modules/@octokit/request": { + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.10.tgz", + "integrity": "sha512-KxNC2pTqqhszMNrf12ZRd4PonRgyJdsM4F/jySiddQK+DsRcfBtUvqn8t7UsyZhnRJHvX46OohDt5N3VqIWC2w==", "license": "MIT", "dependencies": { - "expect": "30.4.1", - "jest-snapshot": "30.4.1" + "@octokit/endpoint": "^11.0.3", + "@octokit/request-error": "^7.0.2", + "@octokit/types": "^16.0.0", + "content-type": "^2.0.0", + "json-with-bigint": "^3.5.3", + "universal-user-agent": "^7.0.2" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">= 20" } }, - "node_modules/@jest/expect-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.4.1.tgz", - "integrity": "sha512-ZBn5CglH8fBsQsvs4VWNzD4aWfUYks+IdOOQU3MEK71ol/BcVm+P+rtb1KpiFBpSWSCE27uOahyyf1vfqOVbcQ==", - "dev": true, + "node_modules/@octokit/request-error": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.0.tgz", + "integrity": "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==", "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0" + "@octokit/types": "^16.0.0" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">= 20" } }, - "node_modules/@jest/fake-timers": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.4.1.tgz", - "integrity": "sha512-iW5umdmfPeWzehrVhugFQZqCchSCud5S1l2YT0O9ZhjRR0ExclANDZkiSBwzqtnlOn0J1JXvO+HZ6rkuyOVOgQ==", - "dev": true, + "node_modules/@octokit/types": { + "version": "16.0.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-16.0.0.tgz", + "integrity": "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==", "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", - "@sinonjs/fake-timers": "^15.4.0", - "@types/node": "*", - "jest-message-util": "30.4.1", - "jest-mock": "30.4.1", - "jest-util": "30.4.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "@octokit/openapi-types": "^27.0.0" } }, - "node_modules/@jest/get-type": { - "version": "30.1.0", - "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", - "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", "dev": true, "license": "MIT", + "optional": true, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">=14" } }, - "node_modules/@jest/globals": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.4.1.tgz", - "integrity": "sha512-ZbuY4cmXC8DkxYjfvT2DbcHWL2T6vmsMhXCDcmTB2T0y0gaezBI77ufq5ZAIdcRkYZ7NEQEDg1xFeKbxUJ5v5Q==", + "node_modules/@pkgr/core": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", "dev": true, "license": "MIT", - "dependencies": { - "@jest/environment": "30.4.1", - "@jest/expect": "30.4.1", - "@jest/types": "30.4.1", - "jest-mock": "30.4.1" - }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/pkgr" } }, - "node_modules/@jest/pattern": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.4.0.tgz", - "integrity": "sha512-RAWn3+f9u8BsHijKJ71uHcFp6vmyEt6VvoWXkl6hKF3qVIuWNmudVjg12DlBPGup/frIl5UcUlH5HfEuvHpEXg==", + "node_modules/@rollup/plugin-commonjs": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz", + "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==", "dev": true, "license": "MIT", "dependencies": { - "@types/node": "*", - "jest-regex-util": "30.4.0" + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, - "node_modules/@jest/reporters": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.4.1.tgz", - "integrity": "sha512-/SnkPCzEQpUaBH81kjdEdDdo2WZl5hxw+BmLDGWjRkm8o7XlhjwsU36cqwe5PGBE5WYpBvDzRSdXx9rbGuJtNA==", + "node_modules/@rollup/plugin-json": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-6.1.0.tgz", + "integrity": "sha512-EGI2te5ENk1coGeADSIwZ7G2Q8CJS2sF120T7jLw4xFw9n7wIOXHo+kIYRAoVpJAN+kmqZSoO3Fp4JtoNF4ReA==", "dev": true, "license": "MIT", "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", - "@jridgewell/trace-mapping": "^0.3.25", - "@types/node": "*", - "chalk": "^4.1.2", - "collect-v8-coverage": "^1.0.2", - "exit-x": "^0.2.2", - "glob": "^10.5.0", - "graceful-fs": "^4.2.11", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^5.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "30.4.1", - "jest-util": "30.4.1", - "jest-worker": "30.4.1", - "slash": "^3.0.0", - "string-length": "^4.0.2", - "v8-to-istanbul": "^9.0.1" + "@rollup/pluginutils": "^5.1.0" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">=14.0.0" }, "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "peerDependenciesMeta": { - "node-notifier": { + "rollup": { "optional": true } } }, - "node_modules/@jest/schemas": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz", - "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==", + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", "dev": true, "license": "MIT", "dependencies": { - "@sinclair/typebox": "^0.34.0" + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, - "node_modules/@jest/snapshot-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.4.1.tgz", - "integrity": "sha512-ObY4ljvQ95mt6iwKtVLetR/4yXiAgl3H4nJxhztr0MTjrN97TwDYrnCp/kF60Ec9HdhkWTHSu+Hg05aXfngpOA==", + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", - "chalk": "^4.1.2", - "graceful-fs": "^4.2.11", - "natural-compare": "^1.4.0" + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" }, "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } } }, - "node_modules/@jest/source-map": { - "version": "30.0.1", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.0.1.tgz", - "integrity": "sha512-MIRWMUUR3sdbP36oyNyhbThLHyJ2eEDClPCiHVbrYAe5g3CHRArIVpBw7cdSB5fr+ofSfIb2Tnsw8iEHL0PYQg==", + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", + "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", - "callsites": "^3.1.0", - "graceful-fs": "^4.2.11" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } + "optional": true, + "os": [ + "android" + ] }, - "node_modules/@jest/test-result": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.4.1.tgz", - "integrity": "sha512-/ZG7pgEiOmmWkN9TplKbOu4id2N5lh7FHwRwlkgBVAzGdRH+OkkQ8wX/kIxg4zmd3ZQvAL1RwL2yWsvNYYECTw==", + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz", + "integrity": "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jest/console": "30.4.1", - "@jest/types": "30.4.1", - "@types/istanbul-lib-coverage": "^2.0.6", - "collect-v8-coverage": "^1.0.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } + "optional": true, + "os": [ + "android" + ] }, - "node_modules/@jest/test-sequencer": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.4.1.tgz", - "integrity": "sha512-PeYE+4td5rKjoRPxztObrXU+H8hsjZfxKMXOcmrr34JerSyB/ROOxbbicz8B7A5j9R9VayDnVPvBmedqCsFCdw==", + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz", + "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jest/test-result": "30.4.1", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } + "optional": true, + "os": [ + "darwin" + ] }, - "node_modules/@jest/transform": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.4.1.tgz", - "integrity": "sha512-Wz0LyktlTvRefoymh+n64hQ84KNXsRGcwdoZ8CSa0Ea+fgYcHZlnk+hDP7v2MS7il2bQ5uTEIxf4/NNfhMN4KQ==", + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz", + "integrity": "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@babel/core": "^7.27.4", - "@jest/types": "30.4.1", - "@jridgewell/trace-mapping": "^0.3.25", - "babel-plugin-istanbul": "^7.0.1", - "chalk": "^4.1.2", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-util": "30.4.1", - "pirates": "^4.0.7", - "slash": "^3.0.0", - "write-file-atomic": "^5.0.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } + "optional": true, + "os": [ + "darwin" + ] }, - "node_modules/@jest/types": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.4.1.tgz", - "integrity": "sha512-f1x/vJXIfjOlEmejYpbkbgw1gOqpPECwMvMEtBqe47j7H2Hg8h8w3o3ikhSXq3MI15kg+oQ0exWO0uCtTNJLoQ==", + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz", + "integrity": "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jest/pattern": "30.4.0", - "@jest/schemas": "30.4.1", - "@types/istanbul-lib-coverage": "^2.0.6", - "@types/istanbul-reports": "^3.0.4", - "@types/node": "*", - "@types/yargs": "^17.0.33", - "chalk": "^4.1.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } + "optional": true, + "os": [ + "freebsd" + ] }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz", + "integrity": "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } + "optional": true, + "os": [ + "freebsd" + ] }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz", + "integrity": "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz", + "integrity": "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", - "engines": { - "node": ">=6.0.0" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz", + "integrity": "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==", + "cpu": [ + "arm64" + ], "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz", + "integrity": "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@microsoft/recognizers-text-data-types-timex-expression": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@microsoft/recognizers-text-data-types-timex-expression/-/recognizers-text-data-types-timex-expression-1.3.1.tgz", - "integrity": "sha512-jarJIFIJZBqeofy3hh0vdQo1yOmTM+jCjj6/zmo9JunsQ6LO750eZHCg9eLptQhsvq321XCt5xdRNLCwU8YeNA==", + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz", + "integrity": "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==", + "cpu": [ + "loong64" + ], + "dev": true, "license": "MIT", - "engines": { - "node": ">=10.3.0" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", - "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz", + "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==", + "cpu": [ + "loong64" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } + "os": [ + "linux" + ] }, - "node_modules/@octokit/auth-token": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", - "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==", + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz", + "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==", + "cpu": [ + "ppc64" + ], + "dev": true, "license": "MIT", - "engines": { - "node": ">= 18" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/core": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.2.tgz", - "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz", + "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==", + "cpu": [ + "ppc64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/auth-token": "^4.0.0", - "@octokit/graphql": "^7.1.0", - "@octokit/request": "^8.4.1", - "@octokit/request-error": "^5.1.1", - "@octokit/types": "^13.0.0", - "before-after-hook": "^2.2.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/endpoint": { - "version": "9.0.6", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz", - "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz", + "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==", + "cpu": [ + "riscv64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/types": "^13.1.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/graphql": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-7.1.1.tgz", - "integrity": "sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==", + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz", + "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==", + "cpu": [ + "riscv64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/request": "^8.4.1", - "@octokit/types": "^13.0.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/openapi-types": { - "version": "24.2.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-24.2.0.tgz", - "integrity": "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==", - "license": "MIT" + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/plugin-paginate-rest": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.2.2.tgz", - "integrity": "sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ==", + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz", + "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==", + "cpu": [ + "s390x" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/types": "^12.6.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "@octokit/core": "5" - } - }, - "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/openapi-types": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", - "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", - "license": "MIT" + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/types": { - "version": "12.6.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", - "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz", + "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==", + "cpu": [ + "x64" + ], "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^20.0.0" - } + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/plugin-rest-endpoint-methods": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", - "integrity": "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==", + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz", + "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==", + "cpu": [ + "x64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/types": "^12.6.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "@octokit/core": "5" - } - }, - "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", - "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", - "license": "MIT" + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { - "version": "12.6.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", - "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz", + "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==", + "cpu": [ + "x64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^20.0.0" - } + "optional": true, + "os": [ + "openbsd" + ] }, - "node_modules/@octokit/request": { - "version": "8.4.1", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", - "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz", + "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==", + "cpu": [ + "arm64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/endpoint": "^9.0.6", - "@octokit/request-error": "^5.1.1", - "@octokit/types": "^13.1.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } + "optional": true, + "os": [ + "openharmony" + ] }, - "node_modules/@octokit/request-error": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz", - "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz", + "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==", + "cpu": [ + "arm64" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/types": "^13.1.0", - "deprecation": "^2.0.0", - "once": "^1.4.0" - }, - "engines": { - "node": ">= 18" - } + "optional": true, + "os": [ + "win32" + ] }, - "node_modules/@octokit/types": { - "version": "13.10.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.10.0.tgz", - "integrity": "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==", + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz", + "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==", + "cpu": [ + "ia32" + ], + "dev": true, "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^24.2.0" - } + "optional": true, + "os": [ + "win32" + ] }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz", + "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", "optional": true, - "engines": { - "node": ">=14" - } + "os": [ + "win32" + ] }, - "node_modules/@pkgr/core": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", - "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz", + "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/pkgr" - } + "optional": true, + "os": [ + "win32" + ] }, "node_modules/@sinclair/typebox": { "version": "0.34.49", @@ -1754,6 +2627,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/graceful-fs": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", + "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -1815,6 +2698,13 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -2447,16 +3337,6 @@ "win32" ] }, - "node_modules/@vercel/ncc": { - "version": "0.38.4", - "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.4.tgz", - "integrity": "sha512-8LwjnlP39s08C08J5NstzriPvW1SP8Zfpp1BvC2sI35kPeZnHfxVkCwu4/+Wodgnd60UtT1n8K8zw+Mp7J9JmQ==", - "dev": true, - "license": "MIT", - "bin": { - "ncc": "dist/ncc/cli.js" - } - }, "node_modules/@xmldom/xmldom": { "version": "0.8.13", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz", @@ -2761,9 +3641,9 @@ } }, "node_modules/before-after-hook": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", - "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz", + "integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==", "license": "Apache-2.0" }, "node_modules/big-integer": { @@ -2782,8 +3662,21 @@ "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" } }, "node_modules/browserslist": { @@ -3072,6 +3965,13 @@ "dev": true, "license": "MIT" }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -3079,6 +3979,19 @@ "dev": true, "license": "MIT" }, + "node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -3166,12 +4079,6 @@ "node": ">=0.10.0" } }, - "node_modules/deprecation": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", - "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==", - "license": "ISC" - }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -3226,6 +4133,65 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -3568,6 +4534,13 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true, + "license": "MIT" + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -3724,6 +4697,19 @@ "node": ">=16.0.0" } }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -3801,6 +4787,16 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -3844,6 +4840,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/get-tsconfig": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.0.tgz", + "integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, "node_modules/glob": { "version": "10.5.0", "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", @@ -3957,6 +4966,19 @@ "node": ">=8" } }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", @@ -4057,6 +5079,22 @@ "dev": true, "license": "MIT" }, + "node_modules/is-core-module": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", + "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -4100,6 +5138,33 @@ "node": ">=0.10.0" } }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, "node_modules/is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", @@ -4430,6 +5495,16 @@ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, + "node_modules/jest-get-type": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", + "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, "node_modules/jest-haste-map": { "version": "30.4.1", "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-30.4.1.tgz", @@ -4858,6 +5933,12 @@ "dev": true, "license": "MIT" }, + "node_modules/json-with-bigint": { + "version": "3.5.8", + "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.8.tgz", + "integrity": "sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==", + "license": "MIT" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -4958,6 +6039,16 @@ "yallist": "^3.0.2" } }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/make-dir": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", @@ -4998,6 +6089,33 @@ "dev": true, "license": "MIT" }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", @@ -5122,6 +6240,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -5272,6 +6391,13 @@ "node": ">=8" } }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, "node_modules/path-scurry": { "version": "1.11.1", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", @@ -5296,6 +6422,13 @@ "dev": true, "license": "ISC" }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -5490,63 +6623,281 @@ ], "license": "MIT" }, - "node_modules/react-is-18": { - "name": "react-is", - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/react-is-18": { + "name": "react-is", + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/react-is-19": { + "name": "react-is", + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz", + "integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==", + "dev": true, + "license": "MIT" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-cwd/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.3.tgz", + "integrity": "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/rimraf": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } }, - "node_modules/react-is-19": { - "name": "react-is", - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz", - "integrity": "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==", + "node_modules/rimraf/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", "dev": true, - "license": "MIT" + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "node_modules/rimraf/node_modules/lru-cache": { + "version": "11.5.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz", + "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==", "dev": true, - "license": "MIT", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=0.10.0" + "node": "20 || >=22" } }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "node_modules/rimraf/node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "dev": true, - "license": "MIT", + "license": "BlueOak-1.0.0", "dependencies": { - "resolve-from": "^5.0.0" + "brace-expansion": "^5.0.5" }, "engines": { - "node": ">=8" + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/resolve-cwd/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "node_modules/rimraf/node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, - "license": "MIT", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, "engines": { - "node": ">=8" + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "node_modules/rollup": { + "version": "4.62.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", + "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==", "dev": true, "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, "engines": { - "node": ">=4" + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.62.2", + "@rollup/rollup-android-arm64": "4.62.2", + "@rollup/rollup-darwin-arm64": "4.62.2", + "@rollup/rollup-darwin-x64": "4.62.2", + "@rollup/rollup-freebsd-arm64": "4.62.2", + "@rollup/rollup-freebsd-x64": "4.62.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", + "@rollup/rollup-linux-arm-musleabihf": "4.62.2", + "@rollup/rollup-linux-arm64-gnu": "4.62.2", + "@rollup/rollup-linux-arm64-musl": "4.62.2", + "@rollup/rollup-linux-loong64-gnu": "4.62.2", + "@rollup/rollup-linux-loong64-musl": "4.62.2", + "@rollup/rollup-linux-ppc64-gnu": "4.62.2", + "@rollup/rollup-linux-ppc64-musl": "4.62.2", + "@rollup/rollup-linux-riscv64-gnu": "4.62.2", + "@rollup/rollup-linux-riscv64-musl": "4.62.2", + "@rollup/rollup-linux-s390x-gnu": "4.62.2", + "@rollup/rollup-linux-x64-gnu": "4.62.2", + "@rollup/rollup-linux-x64-musl": "4.62.2", + "@rollup/rollup-openbsd-x64": "4.62.2", + "@rollup/rollup-openharmony-arm64": "4.62.2", + "@rollup/rollup-win32-arm64-msvc": "4.62.2", + "@rollup/rollup-win32-ia32-msvc": "4.62.2", + "@rollup/rollup-win32-x64-gnu": "4.62.2", + "@rollup/rollup-win32-x64-msvc": "4.62.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/rollup-plugin-esbuild": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-esbuild/-/rollup-plugin-esbuild-6.2.1.tgz", + "integrity": "sha512-jTNOMGoMRhs0JuueJrJqbW8tOwxumaWYq+V5i+PD+8ecSCVkuX27tGW7BXqDgoULQ55rO7IdNxPcnsWtshz3AA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "es-module-lexer": "^1.6.0", + "get-tsconfig": "^4.10.0", + "unplugin-utils": "^0.2.4" + }, + "engines": { + "node": ">=14.18.0" + }, + "peerDependencies": { + "esbuild": ">=0.18.0", + "rollup": "^1.20.0 || ^2.0.0 || ^3.0.0 || ^4.0.0" } }, "node_modules/semver": { @@ -5858,6 +7209,19 @@ "node": ">=8" } }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/swiper": { "version": "12.2.0", "resolved": "https://registry.npmjs.org/swiper/-/swiper-12.2.0.tgz", @@ -5955,6 +7319,19 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -6021,6 +7398,249 @@ } } }, + "node_modules/ts-jest-resolver": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ts-jest-resolver/-/ts-jest-resolver-2.0.1.tgz", + "integrity": "sha512-FolE73BqVZCs8/RbLKxC67iaAtKpBWx7PeLKFW2zJQlOf9j851I7JRxSDenri2NFvVH3QP7v3S8q1AmL24Zb9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-resolve": "^29.5.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/@jest/schemas": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", + "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "^0.27.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/@jest/types": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", + "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/@sinclair/typebox": { + "version": "0.27.10", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz", + "integrity": "sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ts-jest-resolver/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ts-jest-resolver/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ts-jest-resolver/node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-haste-map": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", + "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.6.3", + "jest-util": "^29.7.0", + "jest-worker": "^29.7.0", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-regex-util": { + "version": "29.6.3", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", + "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-resolve": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", + "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.7.0", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.7.0", + "jest-validate": "^29.7.0", + "resolve": "^1.20.0", + "resolve.exports": "^2.0.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-util": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", + "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-validate": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", + "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/types": "^29.6.3", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.6.3", + "leven": "^3.1.0", + "pretty-format": "^29.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/jest-worker": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", + "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.7.0", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/ts-jest-resolver/node_modules/pretty-format": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", + "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/schemas": "^29.6.3", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/ts-jest-resolver/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, "node_modules/ts-jest/node_modules/type-fest": { "version": "4.41.0", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", @@ -6039,8 +7659,7 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD", - "optional": true + "license": "0BSD" }, "node_modules/tunnel": { "version": "0.0.6", @@ -6116,15 +7735,12 @@ } }, "node_modules/undici": { - "version": "5.29.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz", - "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==", + "version": "6.27.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.27.0.tgz", + "integrity": "sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==", "license": "MIT", - "dependencies": { - "@fastify/busboy": "^2.0.0" - }, "engines": { - "node": ">=14.0" + "node": ">=18.17" } }, "node_modules/undici-types": { @@ -6135,11 +7751,28 @@ "license": "MIT" }, "node_modules/universal-user-agent": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", - "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", + "integrity": "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==", "license": "ISC" }, + "node_modules/unplugin-utils": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/unplugin-utils/-/unplugin-utils-0.2.5.tgz", + "integrity": "sha512-gwXJnPRewT4rT7sBi/IvxKTjsms7jX7QIDLOClApuZwR49SXbrB1z2NLUZ+vDHyqCj/n58OzRRqaW+B8OZi8vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, "node_modules/unrs-resolver": { "version": "1.12.2", "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz", @@ -6390,6 +8023,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, "license": "ISC" }, "node_modules/write-file-atomic": { diff --git a/package.json b/package.json index b7ce3de..6793b0c 100644 --- a/package.json +++ b/package.json @@ -1,23 +1,32 @@ { "name": "@opsless/ms-teams-github-actions", - "version": "2.2.0", - "private": true, + "version": "3.0.0", "description": "MS Teams Github Actions integration", - "main": "lib/main.js", + "type": "module", + "private": true, + "main": "dist/index.js", + "exports": { + ".": "./dist/index.js" + }, + "engines": { + "node": ">=24.0.0" + }, "scripts": { - "build": "tsc", + "build": "tsc --noEmit", "format:write": "prettier --write .", "format:check": "prettier --check .", "lint": "eslint .", - "package": "ncc build src/main.ts -m -o dist/main", - "test": "jest", - "all": "npm run build && npm run format:write && npm run lint && npm run package && npm test" + "package": "rimraf ./dist && rollup --config rollup.config.mjs", + "package:watch": "npm run package -- --watch", + "test": "NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest", + "ci-test": "NODE_OPTIONS=--experimental-vm-modules NODE_NO_WARNINGS=1 jest", + "all": "npm run format:write && npm run lint && npm run test && npm run package" }, "author": "opsless.io team", "license": "MIT", "dependencies": { - "@actions/core": "^1.10.1", - "@actions/github": "^6.0.0", + "@actions/core": "^3.0.1", + "@actions/github": "^9.0.0", "adaptive-expressions": "^4.20.1", "adaptivecards": "^3.0.1", "adaptivecards-templating": "^2.3.1", @@ -27,18 +36,31 @@ "@eslint/compat": "^2.0.2", "@eslint/eslintrc": "^3.3.3", "@eslint/js": "^10.0.1", + "@jest/globals": "^30.2.0", + "@rollup/plugin-commonjs": "^29.0.0", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", "@types/jest": "^30.0.0", "@types/node": "^25.2.3", "@typescript-eslint/eslint-plugin": "^8.56.0", "@typescript-eslint/parser": "^8.56.0", - "@vercel/ncc": "^0.38.0", + "esbuild": "^0.28.1", "eslint": "^10.0.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-jest": "^29.15.0", "eslint-plugin-prettier": "^5.5.5", "jest": "^30.2.0", "prettier": "^3.8.1", + "rimraf": "^6.0.1", + "rollup": "^4.57.1", + "rollup-plugin-esbuild": "^16.0.0", + "rollup-plugin-esbuild": "^6.2.1", "ts-jest": "^29.4.6", + "ts-jest-resolver": "^2.0.1", + "tslib": "^2.8.1", "typescript": "^5.9.3" + }, + "optionalDependencies": { + "@rollup/rollup-linux-x64-gnu": "*" } } From 41ab872f30f0e90498cd25e073dd3ce9186bcfb0 Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 02/10] chore(tsconfig): migrate to ES2022 target with NodeNext module resolution Required for ESM package ("type": "module"). Relative imports must now use .js extensions. - target: es6 -> ES2022 - module/moduleResolution: commonjs -> NodeNext - add isolatedModules, resolveJsonModule, forceConsistentCasingInFileNames - exclude __tests__ from type-check scope (jest handles test compilation via ts-jest) --- tsconfig.json | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/tsconfig.json b/tsconfig.json index 4a6c661..e110d6c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,12 +1,26 @@ { + "$schema": "https://json.schemastore.org/tsconfig", "compilerOptions": { - "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, - "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, - "outDir": "./lib" /* Redirect output structure to the directory. */, - "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, - "strict": true /* Enable all strict type-checking options. */, - "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + "allowSyntheticDefaultImports": true, + "declaration": false, + "declarationMap": false, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true, + "lib": ["ES2022"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "newLine": "lf", + "noImplicitAny": true, + "noUnusedLocals": true, + "noUnusedParameters": false, + "outDir": "./dist", + "pretty": true, + "resolveJsonModule": true, + "strict": true, + "strictNullChecks": true, + "target": "ES2022" }, - "exclude": ["node_modules", "**/*.test.ts"] + "exclude": ["__tests__", "coverage", "dist", "lib", "node_modules"], + "include": ["src"] } From 8a305d83cf95940469042e26bb2c6402cb8b8c02 Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 03/10] chore(build): add rollup bundler configuration Replaces @vercel/ncc. Outputs ESM (format: 'es') to dist/index.js to match the actions/typescript-action template. Plugins: - rollup-plugin-esbuild: TypeScript transpilation (uses transform hook; @rollup/plugin-typescript v11/v12 use resolveId+load which silently skip entry points) - @rollup/plugin-node-resolve: resolve node_modules imports - @rollup/plugin-json: required because adaptivecards-templating does require('./../package.json') - @rollup/plugin-commonjs: convert CJS deps (adaptivecards stack) to ESM --- rollup.config.mjs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 rollup.config.mjs diff --git a/rollup.config.mjs b/rollup.config.mjs new file mode 100644 index 0000000..3e8d985 --- /dev/null +++ b/rollup.config.mjs @@ -0,0 +1,27 @@ +// The json plugin is required because adaptivecards-templating does `require('./../package.json')`. + +import commonjs from '@rollup/plugin-commonjs' +import json from '@rollup/plugin-json' +import nodeResolve from '@rollup/plugin-node-resolve' +import esbuild from 'rollup-plugin-esbuild' + +const config = { + input: 'src/main.ts', + output: { + esModule: true, + file: 'dist/index.js', + format: 'es', + sourcemap: true + }, + plugins: [ + esbuild({ + target: 'es2022', + tsconfig: './tsconfig.json' + }), + nodeResolve({preferBuiltins: true}), + json({preferConst: true}), + commonjs() + ] +} + +export default config From 4b29734eee12a5b781a639fbba9e386f64922656 Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 04/10] chore(test): switch jest config to ESM mode Convert from CJS (module.exports) to ESM (export default) since package.json now has "type": "module". - add extensionsToTreatAsEsm: ['.ts'] - add resolver: 'ts-jest-resolver' for .js -> .ts resolution in ESM imports - add useESM: true in ts-jest transform options - add testPathIgnorePatterns for /dist/ and /node_modules/ --- jest.config.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/jest.config.js b/jest.config.js index 768b636..e09bfd5 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,13 +1,21 @@ -// Jest 30 configuration. Uses ts-jest preset; jest-circus is the default -// test runner since Jest 27, so the explicit `testRunner` line was dropped. -// Stays CommonJS (`module.exports`) because package.json has no `"type": "module"`. - /** @type {import('ts-jest').JestConfigWithTsJest} */ -module.exports = { +export default { clearMocks: true, - preset: 'ts-jest', + extensionsToTreatAsEsm: ['.ts'], moduleFileExtensions: ['ts', 'js'], + preset: 'ts-jest', + resolver: 'ts-jest-resolver', testEnvironment: 'node', testMatch: ['**/__tests__/**/*.test.ts'], + testPathIgnorePatterns: ['/dist/', '/node_modules/'], + transform: { + '^.+\\.ts$': [ + 'ts-jest', + { + tsconfig: 'tsconfig.json', + useESM: true + } + ] + }, verbose: true } From 8d912931416a6ba47f68c993aa75094be4b06d6a Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 05/10] fix: add .js extensions to relative imports for NodeNext resolution Under NodeNext module resolution, relative ESM imports must include the .js extension even when the source file is .ts. TypeScript resolves the .js -> .ts mapping at compile time. - src/main.ts: './card' -> './card.js' - src/__tests__/card.test.ts: '../card' -> '../card.js' --- src/__tests__/card.test.ts | 2 +- src/main.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/__tests__/card.test.ts b/src/__tests__/card.test.ts index ee5380b..5d96774 100644 --- a/src/__tests__/card.test.ts +++ b/src/__tests__/card.test.ts @@ -1,4 +1,4 @@ -import {buildWebhookBody, CardData} from '../card' +import {buildWebhookBody, CardData} from '../card.js' const baseData: CardData = { repository: { diff --git a/src/main.ts b/src/main.ts index f6d529a..a09152f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,6 +1,6 @@ import * as core from '@actions/core' import * as github from '@actions/github' -import {buildWebhookBody, CardData} from './card' +import {buildWebhookBody, CardData} from './card.js' async function sleep(ms: number): Promise { return new Promise(resolve => { From 11273886261905d869beaf568bcf8d1372cfa486 Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 06/10] chore: update action.yml entry point to rollup output main: dist/main/index.js -> dist/index.js (rollup single-file output) --- action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/action.yml b/action.yml index 2703d4b..84da8db 100644 --- a/action.yml +++ b/action.yml @@ -10,7 +10,7 @@ inputs: description: MS Teams webhook URI runs: using: node24 - main: dist/main/index.js + main: dist/index.js branding: icon: truck color: green From bddd880557a7ceb3983c197a6240c3bd339509a7 Mon Sep 17 00:00:00 2001 From: ahanoff Date: Sat, 20 Jun 2026 02:35:51 +0800 Subject: [PATCH 07/10] chore: rebuild dist bundle with rollup Rollup ESM output replaces the ncc CJS bundle. Size: 1.7MB (ncc CJS) -> 3.8MB (rollup ESM + sourcemap). Larger because rollup does not minify by default (template doesn't either) and ESM interop code is slightly more verbose. Functionally irrelevant for GitHub Actions runtime. Build time: 4.0s (ncc) -> 2.1s (rollup). --- dist/index.js | 106539 ++++++++++++++++++++++++++++++++++++++++++ dist/index.js.map | 1 + dist/main/index.js | 655 - 3 files changed, 106540 insertions(+), 655 deletions(-) create mode 100644 dist/index.js create mode 100644 dist/index.js.map delete mode 100644 dist/main/index.js diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..cfc547a --- /dev/null +++ b/dist/index.js @@ -0,0 +1,106539 @@ +import * as os from 'os'; +import os__default, { EOL } from 'os'; +import 'crypto'; +import * as fs from 'fs'; +import { promises, existsSync, readFileSync } from 'fs'; +import 'path'; +import http from 'http'; +import https from 'https'; +import 'net'; +import require$$1$3 from 'tls'; +import events$1 from 'events'; +import require$$0$9 from 'assert'; +import require$$6 from 'util'; +import require$$0$4 from 'node:assert'; +import require$$0$6 from 'node:net'; +import require$$2$1 from 'node:http'; +import require$$0$5 from 'node:stream'; +import require$$0$3 from 'node:buffer'; +import require$$0$7 from 'node:util'; +import require$$7 from 'node:querystring'; +import require$$8 from 'node:events'; +import require$$0$8 from 'node:diagnostics_channel'; +import require$$5$1 from 'node:tls'; +import require$$1$5 from 'node:zlib'; +import require$$5$2 from 'node:perf_hooks'; +import require$$8$1 from 'node:util/types'; +import require$$1$4 from 'node:worker_threads'; +import require$$1$6 from 'node:url'; +import require$$5$3 from 'node:async_hooks'; +import require$$1$7 from 'node:console'; +import require$$1$8 from 'node:dns'; +import require$$5$4 from 'string_decoder'; +import 'child_process'; +import 'timers'; + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} + +/** + * Issues a command to the GitHub Actions runner + * + * @param command - The command name to issue + * @param properties - Additional properties for the command (key-value pairs) + * @param message - The message to include with the command + * @remarks + * This function outputs a specially formatted string to stdout that the Actions + * runner interprets as a command. These commands can control workflow behavior, + * set outputs, create annotations, mask values, and more. + * + * Command Format: + * ::name key=value,key=value::message + * + * @example + * ```typescript + * // Issue a warning annotation + * issueCommand('warning', {}, 'This is a warning message'); + * // Output: ::warning::This is a warning message + * + * // Set an environment variable + * issueCommand('set-env', { name: 'MY_VAR' }, 'some value'); + * // Output: ::set-env name=MY_VAR::some value + * + * // Add a secret mask + * issueCommand('add-mask', {}, 'secretValue123'); + * // Output: ::add-mask::secretValue123 + * ``` + * + * @internal + * This is an internal utility function that powers the public API functions + * such as setSecret, warning, error, and exportVariable. + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getAugmentedNamespace(n) { + if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + var isInstance = false; + try { + isInstance = this instanceof a; + } catch (e) {} + if (isInstance) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var tunnel$1 = {}; + +var hasRequiredTunnel$1; + +function requireTunnel$1 () { + if (hasRequiredTunnel$1) return tunnel$1; + hasRequiredTunnel$1 = 1; + var tls = require$$1$3; + var http$1 = http; + var https$1 = https; + var events = events$1; + var util = require$$6; + + + tunnel$1.httpOverHttp = httpOverHttp; + tunnel$1.httpsOverHttp = httpsOverHttp; + tunnel$1.httpOverHttps = httpOverHttps; + tunnel$1.httpsOverHttps = httpsOverHttps; + + + function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http$1.request; + return agent; + } + + function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http$1.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; + } + + function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https$1.request; + return agent; + } + + function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https$1.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; + } + + + function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http$1.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); + } + util.inherits(TunnelingAgent, events.EventEmitter); + + TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); + } + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); + }; + + TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } + }; + + TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket); + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } + }; + + function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); + } + + + function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later + } + + function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; + } + + + var debug; + if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + }; + } else { + debug = function() {}; + } + tunnel$1.debug = debug; // for test + return tunnel$1; +} + +var tunnel; +var hasRequiredTunnel; + +function requireTunnel () { + if (hasRequiredTunnel) return tunnel; + hasRequiredTunnel = 1; + tunnel = requireTunnel$1(); + return tunnel; +} + +requireTunnel(); + +var undici = {}; + +var symbols$4; +var hasRequiredSymbols$4; + +function requireSymbols$4 () { + if (hasRequiredSymbols$4) return symbols$4; + hasRequiredSymbols$4 = 1; + symbols$4 = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kBody: Symbol('abstracted request body'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kResume: Symbol('resume'), + kOnError: Symbol('on error'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable'), + kListeners: Symbol('listeners'), + kHTTPContext: Symbol('http context'), + kMaxConcurrentStreams: Symbol('max concurrent streams'), + kNoProxyAgent: Symbol('no proxy agent'), + kHttpProxyAgent: Symbol('http proxy agent'), + kHttpsProxyAgent: Symbol('https proxy agent') + }; + return symbols$4; +} + +var errors; +var hasRequiredErrors; + +function requireErrors () { + if (hasRequiredErrors) return errors; + hasRequiredErrors = 1; + + const kUndiciError = Symbol.for('undici.error.UND_ERR'); + class UndiciError extends Error { + constructor (message) { + super(message); + this.name = 'UndiciError'; + this.code = 'UND_ERR'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kUndiciError] === true + } + + [kUndiciError] = true + } + + const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT'); + class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message); + this.name = 'ConnectTimeoutError'; + this.message = message || 'Connect Timeout Error'; + this.code = 'UND_ERR_CONNECT_TIMEOUT'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kConnectTimeoutError] === true + } + + [kConnectTimeoutError] = true + } + + const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT'); + class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message); + this.name = 'HeadersTimeoutError'; + this.message = message || 'Headers Timeout Error'; + this.code = 'UND_ERR_HEADERS_TIMEOUT'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersTimeoutError] === true + } + + [kHeadersTimeoutError] = true + } + + const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW'); + class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message); + this.name = 'HeadersOverflowError'; + this.message = message || 'Headers Overflow Error'; + this.code = 'UND_ERR_HEADERS_OVERFLOW'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHeadersOverflowError] === true + } + + [kHeadersOverflowError] = true + } + + const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT'); + class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message); + this.name = 'BodyTimeoutError'; + this.message = message || 'Body Timeout Error'; + this.code = 'UND_ERR_BODY_TIMEOUT'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBodyTimeoutError] === true + } + + [kBodyTimeoutError] = true + } + + const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE'); + class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message); + this.name = 'ResponseStatusCodeError'; + this.message = message || 'Response Status Code Error'; + this.code = 'UND_ERR_RESPONSE_STATUS_CODE'; + this.body = body; + this.status = statusCode; + this.statusCode = statusCode; + this.headers = headers; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseStatusCodeError] === true + } + + [kResponseStatusCodeError] = true + } + + const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG'); + class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message); + this.name = 'InvalidArgumentError'; + this.message = message || 'Invalid Argument Error'; + this.code = 'UND_ERR_INVALID_ARG'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidArgumentError] === true + } + + [kInvalidArgumentError] = true + } + + const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE'); + class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message); + this.name = 'InvalidReturnValueError'; + this.message = message || 'Invalid Return Value Error'; + this.code = 'UND_ERR_INVALID_RETURN_VALUE'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInvalidReturnValueError] === true + } + + [kInvalidReturnValueError] = true + } + + const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT'); + class AbortError extends UndiciError { + constructor (message) { + super(message); + this.name = 'AbortError'; + this.message = message || 'The operation was aborted'; + this.code = 'UND_ERR_ABORT'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kAbortError] === true + } + + [kAbortError] = true + } + + const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED'); + class RequestAbortedError extends AbortError { + constructor (message) { + super(message); + this.name = 'AbortError'; + this.message = message || 'Request aborted'; + this.code = 'UND_ERR_ABORTED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestAbortedError] === true + } + + [kRequestAbortedError] = true + } + + const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO'); + class InformationalError extends UndiciError { + constructor (message) { + super(message); + this.name = 'InformationalError'; + this.message = message || 'Request information'; + this.code = 'UND_ERR_INFO'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kInformationalError] === true + } + + [kInformationalError] = true + } + + const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'); + class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message); + this.name = 'RequestContentLengthMismatchError'; + this.message = message || 'Request body length does not match content-length header'; + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestContentLengthMismatchError] === true + } + + [kRequestContentLengthMismatchError] = true + } + + const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH'); + class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message); + this.name = 'ResponseContentLengthMismatchError'; + this.message = message || 'Response body length does not match content-length header'; + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseContentLengthMismatchError] === true + } + + [kResponseContentLengthMismatchError] = true + } + + const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED'); + class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message); + this.name = 'ClientDestroyedError'; + this.message = message || 'The client is destroyed'; + this.code = 'UND_ERR_DESTROYED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientDestroyedError] === true + } + + [kClientDestroyedError] = true + } + + const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED'); + class ClientClosedError extends UndiciError { + constructor (message) { + super(message); + this.name = 'ClientClosedError'; + this.message = message || 'The client is closed'; + this.code = 'UND_ERR_CLOSED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kClientClosedError] === true + } + + [kClientClosedError] = true + } + + const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET'); + class SocketError extends UndiciError { + constructor (message, socket) { + super(message); + this.name = 'SocketError'; + this.message = message || 'Socket error'; + this.code = 'UND_ERR_SOCKET'; + this.socket = socket; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSocketError] === true + } + + [kSocketError] = true + } + + const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED'); + class NotSupportedError extends UndiciError { + constructor (message) { + super(message); + this.name = 'NotSupportedError'; + this.message = message || 'Not supported error'; + this.code = 'UND_ERR_NOT_SUPPORTED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kNotSupportedError] === true + } + + [kNotSupportedError] = true + } + + const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM'); + class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message); + this.name = 'MissingUpstreamError'; + this.message = message || 'No upstream has been added to the BalancedPool'; + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kBalancedPoolMissingUpstreamError] === true + } + + [kBalancedPoolMissingUpstreamError] = true + } + + const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER'); + class HTTPParserError extends Error { + constructor (message, code, data) { + super(message); + this.name = 'HTTPParserError'; + this.code = code ? `HPE_${code}` : undefined; + this.data = data ? data.toString() : undefined; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kHTTPParserError] === true + } + + [kHTTPParserError] = true + } + + const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE'); + class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message); + this.name = 'ResponseExceededMaxSizeError'; + this.message = message || 'Response content exceeded max size'; + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseExceededMaxSizeError] === true + } + + [kResponseExceededMaxSizeError] = true + } + + const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY'); + class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message); + this.name = 'RequestRetryError'; + this.message = message || 'Request retry error'; + this.code = 'UND_ERR_REQ_RETRY'; + this.statusCode = code; + this.data = data; + this.headers = headers; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kRequestRetryError] === true + } + + [kRequestRetryError] = true + } + + const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE'); + class ResponseError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message); + this.name = 'ResponseError'; + this.message = message || 'Response error'; + this.code = 'UND_ERR_RESPONSE'; + this.statusCode = code; + this.data = data; + this.headers = headers; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kResponseError] === true + } + + [kResponseError] = true + } + + const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS'); + class SecureProxyConnectionError extends UndiciError { + constructor (cause, message, options) { + super(message, { cause, ...(options ?? {}) }); + this.name = 'SecureProxyConnectionError'; + this.message = message || 'Secure Proxy Connection failed'; + this.code = 'UND_ERR_PRX_TLS'; + this.cause = cause; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kSecureProxyConnectionError] === true + } + + [kSecureProxyConnectionError] = true + } + + const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'); + class MessageSizeExceededError extends UndiciError { + constructor (message) { + super(message); + this.name = 'MessageSizeExceededError'; + this.message = message || 'Max decompressed message size exceeded'; + this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMessageSizeExceededError] === true + } + + get [kMessageSizeExceededError] () { + return true + } + } + + errors = { + AbortError, + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError, + ResponseError, + SecureProxyConnectionError, + MessageSizeExceededError + }; + return errors; +} + +var constants$4; +var hasRequiredConstants$4; + +function requireConstants$4 () { + if (hasRequiredConstants$4) return constants$4; + hasRequiredConstants$4 = 1; + + /** @type {Record} */ + const headerNameLowerCasedRecord = {}; + + // https://developer.mozilla.org/docs/Web/HTTP/Headers + const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' + ]; + + for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i]; + const lowerCasedKey = key.toLowerCase(); + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey; + } + + // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. + Object.setPrototypeOf(headerNameLowerCasedRecord, null); + + constants$4 = { + wellknownHeaderNames, + headerNameLowerCasedRecord + }; + return constants$4; +} + +var tree_1; +var hasRequiredTree$2; + +function requireTree$2 () { + if (hasRequiredTree$2) return tree_1; + hasRequiredTree$2 = 1; + + const { + wellknownHeaderNames, + headerNameLowerCasedRecord + } = requireConstants$4(); + + class TstNode { + /** @type {any} */ + value = null + /** @type {null | TstNode} */ + left = null + /** @type {null | TstNode} */ + middle = null + /** @type {null | TstNode} */ + right = null + /** @type {number} */ + code + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor (key, value, index) { + if (index === undefined || index >= key.length) { + throw new TypeError('Unreachable') + } + const code = this.code = key.charCodeAt(index); + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (key.length !== ++index) { + this.middle = new TstNode(key, value, index); + } else { + this.value = value; + } + } + + /** + * @param {string} key + * @param {any} value + */ + add (key, value) { + const length = key.length; + if (length === 0) { + throw new TypeError('Unreachable') + } + let index = 0; + let node = this; + while (true) { + const code = key.charCodeAt(index); + // check code is ascii string + if (code > 0x7F) { + throw new TypeError('key must be ascii string') + } + if (node.code === code) { + if (length === ++index) { + node.value = value; + break + } else if (node.middle !== null) { + node = node.middle; + } else { + node.middle = new TstNode(key, value, index); + break + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left; + } else { + node.left = new TstNode(key, value, index); + break + } + } else if (node.right !== null) { + node = node.right; + } else { + node.right = new TstNode(key, value, index); + break + } + } + } + + /** + * @param {Uint8Array} key + * @return {TstNode | null} + */ + search (key) { + const keylength = key.length; + let index = 0; + let node = this; + while (node !== null && index < keylength) { + let code = key[index]; + // A-Z + // First check if it is bigger than 0x5a. + // Lowercase letters have higher char codes than uppercase ones. + // Also we assume that headers will mostly contain lowercase characters. + if (code <= 0x5a && code >= 0x41) { + // Lowercase for uppercase. + code |= 32; + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + // Returns Node since it is the last key. + return node + } + node = node.middle; + break + } + node = node.code < code ? node.left : node.right; + } + } + return null + } + } + + class TernarySearchTree { + /** @type {TstNode | null} */ + node = null + + /** + * @param {string} key + * @param {any} value + * */ + insert (key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0); + } else { + this.node.add(key, value); + } + } + + /** + * @param {Uint8Array} key + * @return {any} + */ + lookup (key) { + return this.node?.search(key)?.value ?? null + } + } + + const tree = new TernarySearchTree(); + + for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]; + tree.insert(key, key); + } + + tree_1 = { + TernarySearchTree, + tree + }; + return tree_1; +} + +var util$9; +var hasRequiredUtil$9; + +function requireUtil$9 () { + if (hasRequiredUtil$9) return util$9; + hasRequiredUtil$9 = 1; + + const assert = require$$0$4; + const { kDestroyed, kBodyUsed, kListeners, kBody } = requireSymbols$4(); + const { IncomingMessage } = require$$2$1; + const stream = require$$0$5; + const net = require$$0$6; + const { Blob } = require$$0$3; + const nodeUtil = require$$0$7; + const { stringify } = require$$7; + const { EventEmitter: EE } = require$$8; + const { InvalidArgumentError } = requireErrors(); + const { headerNameLowerCasedRecord } = requireConstants$4(); + const { tree } = requireTree$2(); + + const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)); + + class BodyAsyncIterable { + constructor (body) { + this[kBody] = body; + this[kBodyUsed] = false; + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed'); + this[kBodyUsed] = true; + yield * this[kBody]; + } + } + + function wrapRequestBody (body) { + if (isStream(body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (bodyLength(body) === 0) { + body + .on('data', function () { + assert(false); + }); + } + + if (typeof body.readableDidRead !== 'boolean') { + body[kBodyUsed] = false; + EE.prototype.on.call(body, 'data', function () { + this[kBodyUsed] = true; + }); + } + + return body + } else if (body && typeof body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + return new BodyAsyncIterable(body) + } else if ( + body && + typeof body !== 'string' && + !ArrayBuffer.isView(body) && + isIterable(body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + return new BodyAsyncIterable(body) + } else { + return body + } + } + + function nop () {} + + function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' + } + + // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) + function isBlobLike (object) { + if (object === null) { + return false + } else if (object instanceof Blob) { + return true + } else if (typeof object !== 'object') { + return false + } else { + const sTag = object[Symbol.toStringTag]; + + return (sTag === 'Blob' || sTag === 'File') && ( + ('stream' in object && typeof object.stream === 'function') || + ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') + ) + } + } + + function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams); + + if (stringified) { + url += '?' + stringified; + } + + return url + } + + function isValidPort (port) { + const value = parseInt(port, 10); + return ( + value === Number(port) && + value >= 0 && + value <= 65535 + ) + } + + function isHttpOrHttpsPrefixed (value) { + return ( + value != null && + value[0] === 'h' && + value[1] === 't' && + value[2] === 't' && + value[3] === 'p' && + ( + value[4] === ':' || + ( + value[4] === 's' && + value[5] === ':' + ) + ) + ) + } + + function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url); + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80); + let origin = url.origin != null + ? url.origin + : `${url.protocol || ''}//${url.hostname || ''}:${port}`; + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}`; + + if (origin[origin.length - 1] === '/') { + origin = origin.slice(0, origin.length - 1); + } + + if (path && path[0] !== '/') { + path = `/${path}`; + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + return new URL(`${origin}${path}`) + } + + if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + function parseOrigin (url) { + url = parseURL(url); + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url + } + + function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']'); + + assert(idx !== -1); + return host.substring(1, idx) + } + + const idx = host.indexOf(':'); + if (idx === -1) return host + + return host.substring(0, idx) + } + + // IP addresses are not valid server names per RFC6066 + // > Currently, the only server names supported are DNS hostnames + function getServerName (host) { + if (!host) { + return null + } + + assert(typeof host === 'string'); + + const servername = getHostname(host); + if (net.isIP(servername)) { + return '' + } + + return servername + } + + function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) + } + + function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') + } + + function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) + } + + function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState; + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null + } + + function isDestroyed (body) { + return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) + } + + function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null; + } + + stream.destroy(err); + } else if (err) { + queueMicrotask(() => { + stream.emit('error', err); + }); + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true; + } + } + + const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; + function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR); + return m ? parseInt(m[1], 10) * 1000 : null + } + + /** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ + function headerNameToString (value) { + return typeof value === 'string' + ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() + : tree.lookup(value) ?? value.toString('latin1').toLowerCase() + } + + /** + * Receive the buffer as a string and return its lowercase value. + * @param {Buffer} value Header name + * @returns {string} + */ + function bufferToLowerCasedHeaderName (value) { + return tree.lookup(value) ?? value.toString('latin1').toLowerCase() + } + + /** + * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers + * @param {Record} [obj] + * @returns {Record} + */ + function parseHeaders (headers, obj) { + if (obj === undefined) obj = {}; + for (let i = 0; i < headers.length; i += 2) { + const key = headerNameToString(headers[i]); + let val = obj[key]; + + if (val) { + if (typeof val === 'string') { + val = [val]; + obj[key] = val; + } + val.push(headers[i + 1].toString('utf8')); + } else { + const headersValue = headers[i + 1]; + if (typeof headersValue === 'string') { + obj[key] = headersValue; + } else { + obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8'); + } + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1'); + } + + return obj + } + + function parseRawHeaders (headers) { + const len = headers.length; + const ret = new Array(len); + + let hasContentLength = false; + let contentDispositionIdx = -1; + let key; + let val; + let kLen = 0; + + for (let n = 0; n < headers.length; n += 2) { + key = headers[n]; + val = headers[n + 1]; + + typeof key !== 'string' && (key = key.toString()); + typeof val !== 'string' && (val = val.toString('utf8')); + + kLen = key.length; + if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + hasContentLength = true; + } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = n + 1; + } + ret[n] = key; + ret[n + 1] = val; + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1'); + } + + return ret + } + + function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) + } + + function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } + } + + // A body is disturbed if it has been read from and it cannot + // be re-used without losing state or data. + function isDisturbed (body) { + // TODO (fix): Why is body[kBodyUsed] needed? + return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) + } + + function isErrored (body) { + return !!(body && stream.isErrored(body)) + } + + function isReadable (body) { + return !!(body && stream.isReadable(body)) + } + + function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } + } + + /** @type {globalThis['ReadableStream']} */ + function ReadableStreamFrom (iterable) { + // We cannot use ReadableStream.from here because it does not return a byte stream. + + let iterator; + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator](); + }, + async pull (controller) { + const { done, value } = await iterator.next(); + if (done) { + queueMicrotask(() => { + controller.close(); + controller.byobRequest?.respond(0); + }); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + if (buf.byteLength) { + controller.enqueue(new Uint8Array(buf)); + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return(); + }, + type: 'bytes' + } + ) + } + + // The chunk should be a FormData instance and contains + // all the required methods. + function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) + } + + function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }); + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener); + return () => signal.removeListener('abort', listener) + } + + const hasToWellFormed = typeof String.prototype.toWellFormed === 'function'; + const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function'; + + /** + * @param {string} val + */ + function toUSVString (val) { + return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val) + } + + /** + * @param {string} val + */ + // TODO: move this to webidl + function isUSVString (val) { + return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}` + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ + function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } + } + + /** + * @param {string} characters + */ + function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true + } + + // headerCharRegex have been lifted from + // https://github.com/nodejs/node/blob/main/lib/_http_common.js + + /** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ + const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + + /** + * @param {string} characters + */ + function isValidHeaderValue (characters) { + return !headerCharRegex.test(characters) + } + + // Parsed accordingly to RFC 9110 + // https://www.rfc-editor.org/rfc/rfc9110#field.content-range + function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null + } + + function addListener (obj, name, listener) { + const listeners = (obj[kListeners] ??= []); + listeners.push([name, listener]); + obj.on(name, listener); + return obj + } + + function removeAllListeners (obj) { + for (const [name, listener] of obj[kListeners] ?? []) { + obj.removeListener(name, listener); + } + obj[kListeners] = null; + } + + function errorRequest (client, request, err) { + try { + request.onError(err); + assert(request.aborted); + } catch (err) { + client.emit('error', err); + } + } + + const kEnumerableProperty = Object.create(null); + kEnumerableProperty.enumerable = true; + + const normalizedMethodRecordsBase = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' + }; + + const normalizedMethodRecords = { + ...normalizedMethodRecordsBase, + patch: 'patch', + PATCH: 'PATCH' + }; + + // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. + Object.setPrototypeOf(normalizedMethodRecordsBase, null); + Object.setPrototypeOf(normalizedMethodRecords, null); + + util$9 = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isUSVString, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + bufferToLowerCasedHeaderName, + addListener, + removeAllListeners, + errorRequest, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + addAbortListener, + isValidHTTPToken, + isValidHeaderValue, + isTokenCharCode, + parseRangeHeader, + normalizedMethodRecordsBase, + normalizedMethodRecords, + isValidPort, + isHttpOrHttpsPrefixed, + nodeMajor, + nodeMinor, + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'], + wrapRequestBody + }; + return util$9; +} + +var diagnostics; +var hasRequiredDiagnostics; + +function requireDiagnostics () { + if (hasRequiredDiagnostics) return diagnostics; + hasRequiredDiagnostics = 1; + const diagnosticsChannel = require$$0$8; + const util = require$$0$7; + + const undiciDebugLog = util.debuglog('undici'); + const fetchDebuglog = util.debuglog('fetch'); + const websocketDebuglog = util.debuglog('websocket'); + let isClientSet = false; + const channels = { + // Client + beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), + connected: diagnosticsChannel.channel('undici:client:connected'), + connectError: diagnosticsChannel.channel('undici:client:connectError'), + sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), + // Request + create: diagnosticsChannel.channel('undici:request:create'), + bodySent: diagnosticsChannel.channel('undici:request:bodySent'), + headers: diagnosticsChannel.channel('undici:request:headers'), + trailers: diagnosticsChannel.channel('undici:request:trailers'), + error: diagnosticsChannel.channel('undici:request:error'), + // WebSocket + open: diagnosticsChannel.channel('undici:websocket:open'), + close: diagnosticsChannel.channel('undici:websocket:close'), + socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), + ping: diagnosticsChannel.channel('undici:websocket:ping'), + pong: diagnosticsChannel.channel('undici:websocket:pong') + }; + + if (undiciDebugLog.enabled || fetchDebuglog.enabled) { + const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog; + + // Track all Client events + diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt; + debuglog( + 'connecting to %s using %s%s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version + ); + }); + + diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt; + debuglog( + 'connected to %s using %s%s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version + ); + }); + + diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt; + debuglog( + 'connection to %s using %s%s errored - %s', + `${host}${port ? `:${port}` : ''}`, + protocol, + version, + error.message + ); + }); + + diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { + const { + request: { method, path, origin } + } = evt; + debuglog('sending request to %s %s/%s', method, origin, path); + }); + + // Track Request events + diagnosticsChannel.channel('undici:request:headers').subscribe(evt => { + const { + request: { method, path, origin }, + response: { statusCode } + } = evt; + debuglog( + 'received response to %s %s/%s - HTTP %d', + method, + origin, + path, + statusCode + ); + }); + + diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => { + const { + request: { method, path, origin } + } = evt; + debuglog('trailers received from %s %s/%s', method, origin, path); + }); + + diagnosticsChannel.channel('undici:request:error').subscribe(evt => { + const { + request: { method, path, origin }, + error + } = evt; + debuglog( + 'request to %s %s/%s errored - %s', + method, + origin, + path, + error.message + ); + }); + + isClientSet = true; + } + + if (websocketDebuglog.enabled) { + if (!isClientSet) { + const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog; + diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt; + debuglog( + 'connecting to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ); + }); + + diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { + const { + connectParams: { version, protocol, port, host } + } = evt; + debuglog( + 'connected to %s%s using %s%s', + host, + port ? `:${port}` : '', + protocol, + version + ); + }); + + diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { + const { + connectParams: { version, protocol, port, host }, + error + } = evt; + debuglog( + 'connection to %s%s using %s%s errored - %s', + host, + port ? `:${port}` : '', + protocol, + version, + error.message + ); + }); + + diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { + const { + request: { method, path, origin } + } = evt; + debuglog('sending request to %s %s/%s', method, origin, path); + }); + } + + // Track all WebSocket events + diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => { + const { + address: { address, port } + } = evt; + websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : ''); + }); + + diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => { + const { websocket, code, reason } = evt; + websocketDebuglog( + 'closed connection to %s - %s %s', + websocket.url, + code, + reason + ); + }); + + diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => { + websocketDebuglog('connection errored - %s', err.message); + }); + + diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => { + websocketDebuglog('ping received'); + }); + + diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => { + websocketDebuglog('pong received'); + }); + } + + diagnostics = { + channels + }; + return diagnostics; +} + +var request$2; +var hasRequiredRequest$1; + +function requireRequest$1 () { + if (hasRequiredRequest$1) return request$2; + hasRequiredRequest$1 = 1; + + const { + InvalidArgumentError, + NotSupportedError + } = requireErrors(); + const assert = require$$0$4; + const { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + isBlobLike, + buildURL, + validateHandler, + getServerName, + normalizedMethodRecords + } = requireUtil$9(); + const { channels } = requireDiagnostics(); + const { headerNameLowerCasedRecord } = requireConstants$4(); + + // Verifies that a given path is valid does not contain control chars \x00 to \x20 + const invalidPathRegex = /[^\u0021-\u00ff]/; + + const kHandler = Symbol('handler'); + + class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue, + servername + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (upgrade && !isValidHeaderValue(upgrade)) { + throw new InvalidArgumentError('invalid upgrade header') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout; + + this.bodyTimeout = bodyTimeout; + + this.throwOnError = throwOnError === true; + + this.method = method; + + this.abort = null; + + if (body == null) { + this.body = null; + } else if (isStream(body)) { + this.body = body; + + const rState = this.body._readableState; + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + destroy(this); + }; + this.body.on('end', this.endHandler); + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err); + } else { + this.error = err; + } + }; + this.body.on('error', this.errorHandler); + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null; + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null; + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null; + } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { + this.body = body; + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false; + + this.aborted = false; + + this.upgrade = upgrade || null; + + this.path = query ? buildURL(path, query) : path; + + this.origin = origin; + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent; + + this.blocking = blocking == null ? false : blocking; + + this.reset = reset == null ? null : reset; + + this.host = null; + + this.contentLength = null; + + this.contentType = null; + + this.headers = []; + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false; + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]); + } + } else if (headers && typeof headers === 'object') { + if (headers[Symbol.iterator]) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError('headers must be in key-value pair format') + } + processHeader(this, header[0], header[1]); + } + } else { + const keys = Object.keys(headers); + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]); + } + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + validateHandler(handler, method, upgrade); + + this.servername = servername || getServerName(this.host); + + this[kHandler] = handler; + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }); + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err); + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }); + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err); + } + } + } + + onConnect (abort) { + assert(!this.aborted); + assert(!this.completed); + + if (this.error) { + abort(this.error); + } else { + this.abort = abort; + return this[kHandler].onConnect(abort) + } + } + + onResponseStarted () { + return this[kHandler].onResponseStarted?.() + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted); + assert(!this.completed); + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err); + } + } + + onData (chunk) { + assert(!this.aborted); + assert(!this.completed); + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err); + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted); + assert(!this.completed); + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally(); + + assert(!this.aborted); + + this.completed = true; + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }); + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err); + } + } + + onError (error) { + this.onFinally(); + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }); + } + + if (this.aborted) { + return + } + this.aborted = true; + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler); + this.errorHandler = null; + } + + if (this.endHandler) { + this.body.off('end', this.endHandler); + this.endHandler = null; + } + } + + addHeader (key, value) { + processHeader(this, key, value); + return this + } + } + + function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + let headerName = headerNameLowerCasedRecord[key]; + + if (headerName === undefined) { + headerName = key.toLowerCase(); + if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError('invalid header key') + } + } + + if (Array.isArray(val)) { + const arr = []; + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === 'string') { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + arr.push(val[i]); + } else if (val[i] === null) { + arr.push(''); + } else if (typeof val[i] === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } else { + arr.push(`${val[i]}`); + } + } + val = arr; + } else if (typeof val === 'string') { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + } else if (val === null) { + val = ''; + } else { + val = `${val}`; + } + + if (headerName === 'host') { + if (request.host !== null) { + throw new InvalidArgumentError('duplicate host header') + } + if (typeof val !== 'string') { + throw new InvalidArgumentError('invalid host header') + } + // Consumed by Client + request.host = val; + } else if (headerName === 'content-length') { + if (request.contentLength !== null) { + throw new InvalidArgumentError('duplicate content-length header') + } + request.contentLength = parseInt(val, 10); + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if (request.contentType === null && headerName === 'content-type') { + request.contentType = val; + request.headers.push(key, val); + } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { + throw new InvalidArgumentError(`invalid ${headerName} header`) + } else if (headerName === 'connection') { + const value = typeof val === 'string' ? val.toLowerCase() : null; + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } + + if (value === 'close') { + request.reset = true; + } + } else if (headerName === 'expect') { + throw new NotSupportedError('expect header not supported') + } else { + request.headers.push(key, val); + } + } + + request$2 = Request; + return request$2; +} + +var dispatcher; +var hasRequiredDispatcher; + +function requireDispatcher () { + if (hasRequiredDispatcher) return dispatcher; + hasRequiredDispatcher = 1; + const EventEmitter = require$$8; + + class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } + + compose (...args) { + // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... + const interceptors = Array.isArray(args[0]) ? args[0] : args; + let dispatch = this.dispatch.bind(this); + + for (const interceptor of interceptors) { + if (interceptor == null) { + continue + } + + if (typeof interceptor !== 'function') { + throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) + } + + dispatch = interceptor(dispatch); + + if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { + throw new TypeError('invalid interceptor') + } + } + + return new ComposedDispatcher(this, dispatch) + } + } + + class ComposedDispatcher extends Dispatcher { + #dispatcher = null + #dispatch = null + + constructor (dispatcher, dispatch) { + super(); + this.#dispatcher = dispatcher; + this.#dispatch = dispatch; + } + + dispatch (...args) { + this.#dispatch(...args); + } + + close (...args) { + return this.#dispatcher.close(...args) + } + + destroy (...args) { + return this.#dispatcher.destroy(...args) + } + } + + dispatcher = Dispatcher; + return dispatcher; +} + +var dispatcherBase; +var hasRequiredDispatcherBase; + +function requireDispatcherBase () { + if (hasRequiredDispatcherBase) return dispatcherBase; + hasRequiredDispatcherBase = 1; + + const Dispatcher = requireDispatcher(); + const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError + } = requireErrors(); + const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = requireSymbols$4(); + + const kOnDestroyed = Symbol('onDestroyed'); + const kOnClosed = Symbol('onClosed'); + const kInterceptedDispatch = Symbol('Intercepted Dispatch'); + const kWebSocketOptions = Symbol('webSocketOptions'); + + class DispatcherBase extends Dispatcher { + constructor (opts) { + super(); + + this[kDestroyed] = false; + this[kOnDestroyed] = null; + this[kClosed] = false; + this[kOnClosed] = []; + this[kWebSocketOptions] = opts?.webSocket ?? {}; + } + + get webSocketOptions () { + return { + maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, + maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 + } + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i]; + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors; + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)); + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback); + } else { + queueMicrotask(() => callback(null, null)); + } + return + } + + this[kClosed] = true; + this[kOnClosed].push(callback); + + const onClosed = () => { + const callbacks = this[kOnClosed]; + this[kOnClosed] = null; + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null); + } + }; + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed); + }); + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err; + err = null; + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }); + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback); + } else { + queueMicrotask(() => callback(null, null)); + } + return + } + + if (!err) { + err = new ClientDestroyedError(); + } + + this[kDestroyed] = true; + this[kOnDestroyed] = this[kOnDestroyed] || []; + this[kOnDestroyed].push(callback); + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed]; + this[kOnDestroyed] = null; + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null); + } + }; + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed); + }); + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch]; + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this); + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch); + } + this[kInterceptedDispatch] = dispatch; + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err); + + return false + } + } + } + + dispatcherBase = DispatcherBase; + return dispatcherBase; +} + +var timers; +var hasRequiredTimers; + +function requireTimers () { + if (hasRequiredTimers) return timers; + hasRequiredTimers = 1; + + /** + * This module offers an optimized timer implementation designed for scenarios + * where high precision is not critical. + * + * The timer achieves faster performance by using a low-resolution approach, + * with an accuracy target of within 500ms. This makes it particularly useful + * for timers with delays of 1 second or more, where exact timing is less + * crucial. + * + * It's important to note that Node.js timers are inherently imprecise, as + * delays can occur due to the event loop being blocked by other operations. + * Consequently, timers may trigger later than their scheduled time. + */ + + /** + * The fastNow variable contains the internal fast timer clock value. + * + * @type {number} + */ + let fastNow = 0; + + /** + * RESOLUTION_MS represents the target resolution time in milliseconds. + * + * @type {number} + * @default 1000 + */ + const RESOLUTION_MS = 1e3; + + /** + * TICK_MS defines the desired interval in milliseconds between each tick. + * The target value is set to half the resolution time, minus 1 ms, to account + * for potential event loop overhead. + * + * @type {number} + * @default 499 + */ + const TICK_MS = (RESOLUTION_MS >> 1) - 1; + + /** + * fastNowTimeout is a Node.js timer used to manage and process + * the FastTimers stored in the `fastTimers` array. + * + * @type {NodeJS.Timeout} + */ + let fastNowTimeout; + + /** + * The kFastTimer symbol is used to identify FastTimer instances. + * + * @type {Symbol} + */ + const kFastTimer = Symbol('kFastTimer'); + + /** + * The fastTimers array contains all active FastTimers. + * + * @type {FastTimer[]} + */ + const fastTimers = []; + + /** + * These constants represent the various states of a FastTimer. + */ + + /** + * The `NOT_IN_LIST` constant indicates that the FastTimer is not included + * in the `fastTimers` array. Timers with this status will not be processed + * during the next tick by the `onTick` function. + * + * A FastTimer can be re-added to the `fastTimers` array by invoking the + * `refresh` method on the FastTimer instance. + * + * @type {-2} + */ + const NOT_IN_LIST = -2; + + /** + * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled + * for removal from the `fastTimers` array. A FastTimer in this state will + * be removed in the next tick by the `onTick` function and will no longer + * be processed. + * + * This status is also set when the `clear` method is called on the FastTimer instance. + * + * @type {-1} + */ + const TO_BE_CLEARED = -1; + + /** + * The `PENDING` constant signifies that the FastTimer is awaiting processing + * in the next tick by the `onTick` function. Timers with this status will have + * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. + * + * @type {0} + */ + const PENDING = 0; + + /** + * The `ACTIVE` constant indicates that the FastTimer is active and waiting + * for its timer to expire. During the next tick, the `onTick` function will + * check if the timer has expired, and if so, it will execute the associated callback. + * + * @type {1} + */ + const ACTIVE = 1; + + /** + * The onTick function processes the fastTimers array. + * + * @returns {void} + */ + function onTick () { + /** + * Increment the fastNow value by the TICK_MS value, despite the actual time + * that has passed since the last tick. This approach ensures independence + * from the system clock and delays caused by a blocked event loop. + * + * @type {number} + */ + fastNow += TICK_MS; + + /** + * The `idx` variable is used to iterate over the `fastTimers` array. + * Expired timers are removed by replacing them with the last element in the array. + * Consequently, `idx` is only incremented when the current element is not removed. + * + * @type {number} + */ + let idx = 0; + + /** + * The len variable will contain the length of the fastTimers array + * and will be decremented when a FastTimer should be removed from the + * fastTimers array. + * + * @type {number} + */ + let len = fastTimers.length; + + while (idx < len) { + /** + * @type {FastTimer} + */ + const timer = fastTimers[idx]; + + // If the timer is in the ACTIVE state and the timer has expired, it will + // be processed in the next tick. + if (timer._state === PENDING) { + // Set the _idleStart value to the fastNow value minus the TICK_MS value + // to account for the time the timer was in the PENDING state. + timer._idleStart = fastNow - TICK_MS; + timer._state = ACTIVE; + } else if ( + timer._state === ACTIVE && + fastNow >= timer._idleStart + timer._idleTimeout + ) { + timer._state = TO_BE_CLEARED; + timer._idleStart = -1; + timer._onTimeout(timer._timerArg); + } + + if (timer._state === TO_BE_CLEARED) { + timer._state = NOT_IN_LIST; + + // Move the last element to the current index and decrement len if it is + // not the only element in the array. + if (--len !== 0) { + fastTimers[idx] = fastTimers[len]; + } + } else { + ++idx; + } + } + + // Set the length of the fastTimers array to the new length and thus + // removing the excess FastTimers elements from the array. + fastTimers.length = len; + + // If there are still active FastTimers in the array, refresh the Timer. + // If there are no active FastTimers, the timer will be refreshed again + // when a new FastTimer is instantiated. + if (fastTimers.length !== 0) { + refreshTimeout(); + } + } + + function refreshTimeout () { + // If the fastNowTimeout is already set, refresh it. + if (fastNowTimeout) { + fastNowTimeout.refresh(); + // fastNowTimeout is not instantiated yet, create a new Timer. + } else { + clearTimeout(fastNowTimeout); + fastNowTimeout = setTimeout(onTick, TICK_MS); + + // If the Timer has an unref method, call it to allow the process to exit if + // there are no other active handles. + if (fastNowTimeout.unref) { + fastNowTimeout.unref(); + } + } + } + + /** + * The `FastTimer` class is a data structure designed to store and manage + * timer information. + */ + class FastTimer { + [kFastTimer] = true + + /** + * The state of the timer, which can be one of the following: + * - NOT_IN_LIST (-2) + * - TO_BE_CLEARED (-1) + * - PENDING (0) + * - ACTIVE (1) + * + * @type {-2|-1|0|1} + * @private + */ + _state = NOT_IN_LIST + + /** + * The number of milliseconds to wait before calling the callback. + * + * @type {number} + * @private + */ + _idleTimeout = -1 + + /** + * The time in milliseconds when the timer was started. This value is used to + * calculate when the timer should expire. + * + * @type {number} + * @default -1 + * @private + */ + _idleStart = -1 + + /** + * The function to be executed when the timer expires. + * @type {Function} + * @private + */ + _onTimeout + + /** + * The argument to be passed to the callback when the timer expires. + * + * @type {*} + * @private + */ + _timerArg + + /** + * @constructor + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should wait + * before the specified function or code is executed. + * @param {*} arg + */ + constructor (callback, delay, arg) { + this._onTimeout = callback; + this._idleTimeout = delay; + this._timerArg = arg; + + this.refresh(); + } + + /** + * Sets the timer's start time to the current time, and reschedules the timer + * to call its callback at the previously specified duration adjusted to the + * current time. + * Using this on a timer that has already called its callback will reactivate + * the timer. + * + * @returns {void} + */ + refresh () { + // In the special case that the timer is not in the list of active timers, + // add it back to the array to be processed in the next tick by the onTick + // function. + if (this._state === NOT_IN_LIST) { + fastTimers.push(this); + } + + // If the timer is the only active timer, refresh the fastNowTimeout for + // better resolution. + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout(); + } + + // Setting the state to PENDING will cause the timer to be reset in the + // next tick by the onTick function. + this._state = PENDING; + } + + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear () { + // Set the state to TO_BE_CLEARED to mark the timer for removal in the next + // tick by the onTick function. + this._state = TO_BE_CLEARED; + + // Reset the _idleStart value to -1 to indicate that the timer is no longer + // active. + this._idleStart = -1; + } + } + + /** + * This module exports a setTimeout and clearTimeout function that can be + * used as a drop-in replacement for the native functions. + */ + timers = { + /** + * The setTimeout() method sets a timer which executes a function once the + * timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {NodeJS.Timeout|FastTimer} + */ + setTimeout (callback, delay, arg) { + // If the delay is less than or equal to the RESOLUTION_MS value return a + // native Node.js Timer instance. + return delay <= RESOLUTION_MS + ? setTimeout(callback, delay, arg) + : new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout (timeout) { + // If the timeout is a FastTimer, call its own clear method. + if (timeout[kFastTimer]) { + /** + * @type {FastTimer} + */ + timeout.clear(); + // Otherwise it is an instance of a native NodeJS.Timeout, so call the + // Node.js native clearTimeout function. + } else { + clearTimeout(timeout); + } + }, + /** + * The setFastTimeout() method sets a fastTimer which executes a function once + * the timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {FastTimer} + */ + setFastTimeout (callback, delay, arg) { + return new FastTimer(callback, delay, arg) + }, + /** + * The clearTimeout method cancels an instantiated FastTimer previously + * created by calling setFastTimeout. + * + * @param {FastTimer} timeout + */ + clearFastTimeout (timeout) { + timeout.clear(); + }, + /** + * The now method returns the value of the internal fast timer clock. + * + * @returns {number} + */ + now () { + return fastNow + }, + /** + * Trigger the onTick function to process the fastTimers array. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + * @param {number} [delay=0] The delay in milliseconds to add to the now value. + */ + tick (delay = 0) { + fastNow += delay - RESOLUTION_MS + 1; + onTick(); + onTick(); + }, + /** + * Reset FastTimers. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + reset () { + fastNow = 0; + fastTimers.length = 0; + clearTimeout(fastNowTimeout); + fastNowTimeout = null; + }, + /** + * Exporting for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + kFastTimer + }; + return timers; +} + +var connect; +var hasRequiredConnect; + +function requireConnect () { + if (hasRequiredConnect) return connect; + hasRequiredConnect = 1; + + const net = require$$0$6; + const assert = require$$0$4; + const util = requireUtil$9(); + const { InvalidArgumentError, ConnectTimeoutError } = requireErrors(); + const timers = requireTimers(); + + function noop () {} + + let tls; // include tls conditionally since it is not always available + + // TODO: session re-use does not wait for the first + // connection to resolve the session and might therefore + // resolve the same servername multiple times even when + // re-use is enabled. + + let SessionCache; + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (commonjsGlobal.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions; + this._sessionCache = new Map(); + this._sessionRegistry = new commonjsGlobal.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key); + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key); + } + }); + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey); + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)); + this._sessionRegistry.register(session, sessionKey); + } + }; + } else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions; + this._sessionCache = new Map(); + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next(); + this._sessionCache.delete(oldestKey); + } + + this._sessionCache.set(sessionKey, session); + } + }; + } + + function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts }; + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions); + timeout = timeout == null ? 10e3 : timeout; + allowH2 = allowH2 != null ? allowH2 : false; + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket; + if (protocol === 'https:') { + if (!tls) { + tls = require$$5$1; + } + servername = servername || options.servername || util.getServerName(host) || null; + + const sessionKey = servername || hostname; + assert(sessionKey); + + const session = customSession || sessionCache.get(sessionKey) || null; + + port = port || 443; + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port, + host: hostname + }); + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session); + }); + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update'); + + port = port || 80; + + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port, + host: hostname + }); + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay; + socket.setKeepAlive(true, keepAliveInitialDelay); + } + + const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }); + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + queueMicrotask(clearConnectTimeout); + + if (callback) { + const cb = callback; + callback = null; + cb(null, this); + } + }) + .on('error', function (err) { + queueMicrotask(clearConnectTimeout); + + if (callback) { + const cb = callback; + callback = null; + cb(err); + } + }); + + return socket + } + } + + /** + * @param {WeakRef} socketWeakRef + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + * @returns {() => void} + */ + const setupConnectTimeout = process.platform === 'win32' + ? (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null; + let s2 = null; + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)); + }); + }, opts.timeout); + return () => { + timers.clearFastTimeout(fastTimer); + clearImmediate(s1); + clearImmediate(s2); + } + } + : (socketWeakRef, opts) => { + if (!opts.timeout) { + return noop + } + + let s1 = null; + const fastTimer = timers.setFastTimeout(() => { + // setImmediate is added to make sure that we prioritize socket error events over timeouts + s1 = setImmediate(() => { + onConnectTimeout(socketWeakRef.deref(), opts); + }); + }, opts.timeout); + return () => { + timers.clearFastTimeout(fastTimer); + clearImmediate(s1); + } + }; + + /** + * @param {net.Socket} socket + * @param {object} opts + * @param {number} opts.timeout + * @param {string} opts.hostname + * @param {number} opts.port + */ + function onConnectTimeout (socket, opts) { + // The socket could be already garbage collected + if (socket == null) { + return + } + + let message = 'Connect Timeout Error'; + if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { + message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`; + } else { + message += ` (attempted address: ${opts.hostname}:${opts.port},`; + } + + message += ` timeout: ${opts.timeout}ms)`; + + util.destroy(socket, new ConnectTimeoutError(message)); + } + + connect = buildConnector; + return connect; +} + +var constants$3 = {}; + +var utils = {}; + +var hasRequiredUtils$1; + +function requireUtils$1 () { + if (hasRequiredUtils$1) return utils; + hasRequiredUtils$1 = 1; + Object.defineProperty(utils, "__esModule", { value: true }); + utils.enumToMap = void 0; + function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; + } + utils.enumToMap = enumToMap; + + return utils; +} + +var hasRequiredConstants$3; + +function requireConstants$3 () { + if (hasRequiredConstants$3) return constants$3; + hasRequiredConstants$3 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; + const utils_1 = requireUtils$1(); + (function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; + })(exports.ERROR || (exports.ERROR = {})); + (function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; + })(exports.TYPE || (exports.TYPE = {})); + (function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; + })(exports.FLAGS || (exports.FLAGS = {})); + (function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; + })(exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); + var METHODS; + (function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; + })(METHODS = exports.METHODS || (exports.METHODS = {})); + exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, + ]; + exports.METHODS_ICE = [ + METHODS.SOURCE, + ]; + exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, + ]; + exports.METHOD_MAP = utils_1.enumToMap(METHODS); + exports.H_METHOD_MAP = {}; + Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } + }); + (function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; + })(exports.FINISH || (exports.FINISH = {})); + exports.ALPHA = []; + for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); + } + exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + }; + exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, + }; + exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + ]; + exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); + exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; + exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); + // TODO(indutny): use RFC + exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', + ].concat(exports.ALPHANUM); + exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); + // All characters with 0x80 bit set to 1 + for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); + } + exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); + /* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ + exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', + ].concat(exports.ALPHANUM); + exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); + /* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ + exports.HEADER_CHARS = ['\t']; + for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } + } + // ',' = \x44 + exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); + exports.MAJOR = exports.NUM_MAP; + exports.MINOR = exports.MAJOR; + var HEADER_STATE; + (function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; + })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); + exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, + }; + + } (constants$3)); + return constants$3; +} + +var llhttpWasm; +var hasRequiredLlhttpWasm; + +function requireLlhttpWasm () { + if (hasRequiredLlhttpWasm) return llhttpWasm; + hasRequiredLlhttpWasm = 1; + + const { Buffer } = require$$0$3; + + llhttpWasm = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK07MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtXACAAQRhqQgA3AwAgAEIANwMAIABBOGpCADcDACAAQTBqQgA3AwAgAEEoakIANwMAIABBIGpCADcDACAAQRBqQgA3AwAgAEEIakIANwMAIABB3QE2AhwLBgAgABAyC5otAQt/IwBBEGsiCiQAQaTQACgCACIJRQRAQeTTACgCACIFRQRAQfDTAEJ/NwIAQejTAEKAgISAgIDAADcCAEHk0wAgCkEIakFwcUHYqtWqBXMiBTYCAEH40wBBADYCAEHI0wBBADYCAAtBzNMAQYDUBDYCAEGc0ABBgNQENgIAQbDQACAFNgIAQazQAEF/NgIAQdDTAEGArAM2AgADQCABQcjQAGogAUG80ABqIgI2AgAgAiABQbTQAGoiAzYCACABQcDQAGogAzYCACABQdDQAGogAUHE0ABqIgM2AgAgAyACNgIAIAFB2NAAaiABQczQAGoiAjYCACACIAM2AgAgAUHU0ABqIAI2AgAgAUEgaiIBQYACRw0AC0GM1ARBwasDNgIAQajQAEH00wAoAgA2AgBBmNAAQcCrAzYCAEGk0ABBiNQENgIAQcz/B0E4NgIAQYjUBCEJCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFNBEBBjNAAKAIAIgZBECAAQRNqQXBxIABBC0kbIgRBA3YiAHYiAUEDcQRAAkAgAUEBcSAAckEBcyICQQN0IgBBtNAAaiIBIABBvNAAaigCACIAKAIIIgNGBEBBjNAAIAZBfiACd3E2AgAMAQsgASADNgIIIAMgATYCDAsgAEEIaiEBIAAgAkEDdCICQQNyNgIEIAAgAmoiACAAKAIEQQFyNgIEDBELQZTQACgCACIIIARPDQEgAQRAAkBBAiAAdCICQQAgAmtyIAEgAHRxaCIAQQN0IgJBtNAAaiIBIAJBvNAAaigCACICKAIIIgNGBEBBjNAAIAZBfiAAd3EiBjYCAAwBCyABIAM2AgggAyABNgIMCyACIARBA3I2AgQgAEEDdCIAIARrIQUgACACaiAFNgIAIAIgBGoiBCAFQQFyNgIEIAgEQCAIQXhxQbTQAGohAEGg0AAoAgAhAwJ/QQEgCEEDdnQiASAGcUUEQEGM0AAgASAGcjYCACAADAELIAAoAggLIgEgAzYCDCAAIAM2AgggAyAANgIMIAMgATYCCAsgAkEIaiEBQaDQACAENgIAQZTQACAFNgIADBELQZDQACgCACILRQ0BIAtoQQJ0QbzSAGooAgAiACgCBEF4cSAEayEFIAAhAgNAAkAgAigCECIBRQRAIAJBFGooAgAiAUUNAQsgASgCBEF4cSAEayIDIAVJIQIgAyAFIAIbIQUgASAAIAIbIQAgASECDAELCyAAKAIYIQkgACgCDCIDIABHBEBBnNAAKAIAGiADIAAoAggiATYCCCABIAM2AgwMEAsgAEEUaiICKAIAIgFFBEAgACgCECIBRQ0DIABBEGohAgsDQCACIQcgASIDQRRqIgIoAgAiAQ0AIANBEGohAiADKAIQIgENAAsgB0EANgIADA8LQX8hBCAAQb9/Sw0AIABBE2oiAUFwcSEEQZDQACgCACIIRQ0AQQAgBGshBQJAAkACQAJ/QQAgBEGAAkkNABpBHyAEQf///wdLDQAaIARBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgZBAnRBvNIAaigCACICRQRAQQAhAUEAIQMMAQtBACEBIARBGSAGQQF2a0EAIAZBH0cbdCEAQQAhAwNAAkAgAigCBEF4cSAEayIHIAVPDQAgAiEDIAciBQ0AQQAhBSACIQEMAwsgASACQRRqKAIAIgcgByACIABBHXZBBHFqQRBqKAIAIgJGGyABIAcbIQEgAEEBdCEAIAINAAsLIAEgA3JFBEBBACEDQQIgBnQiAEEAIABrciAIcSIARQ0DIABoQQJ0QbzSAGooAgAhAQsgAUUNAQsDQCABKAIEQXhxIARrIgIgBUkhACACIAUgABshBSABIAMgABshAyABKAIQIgAEfyAABSABQRRqKAIACyIBDQALCyADRQ0AIAVBlNAAKAIAIARrTw0AIAMoAhghByADIAMoAgwiAEcEQEGc0AAoAgAaIAAgAygCCCIBNgIIIAEgADYCDAwOCyADQRRqIgIoAgAiAUUEQCADKAIQIgFFDQMgA0EQaiECCwNAIAIhBiABIgBBFGoiAigCACIBDQAgAEEQaiECIAAoAhAiAQ0ACyAGQQA2AgAMDQtBlNAAKAIAIgMgBE8EQEGg0AAoAgAhAQJAIAMgBGsiAkEQTwRAIAEgBGoiACACQQFyNgIEIAEgA2ogAjYCACABIARBA3I2AgQMAQsgASADQQNyNgIEIAEgA2oiACAAKAIEQQFyNgIEQQAhAEEAIQILQZTQACACNgIAQaDQACAANgIAIAFBCGohAQwPC0GY0AAoAgAiAyAESwRAIAQgCWoiACADIARrIgFBAXI2AgRBpNAAIAA2AgBBmNAAIAE2AgAgCSAEQQNyNgIEIAlBCGohAQwPC0EAIQEgBAJ/QeTTACgCAARAQezTACgCAAwBC0Hw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBDGpBcHFB2KrVqgVzNgIAQfjTAEEANgIAQcjTAEEANgIAQYCABAsiACAEQccAaiIFaiIGQQAgAGsiB3EiAk8EQEH80wBBMDYCAAwPCwJAQcTTACgCACIBRQ0AQbzTACgCACIIIAJqIQAgACABTSAAIAhLcQ0AQQAhAUH80wBBMDYCAAwPC0HI0wAtAABBBHENBAJAAkAgCQRAQczTACEBA0AgASgCACIAIAlNBEAgACABKAIEaiAJSw0DCyABKAIIIgENAAsLQQAQMyIAQX9GDQUgAiEGQejTACgCACIBQQFrIgMgAHEEQCACIABrIAAgA2pBACABa3FqIQYLIAQgBk8NBSAGQf7///8HSw0FQcTTACgCACIDBEBBvNMAKAIAIgcgBmohASABIAdNDQYgASADSw0GCyAGEDMiASAARw0BDAcLIAYgA2sgB3EiBkH+////B0sNBCAGEDMhACAAIAEoAgAgASgCBGpGDQMgACEBCwJAIAYgBEHIAGpPDQAgAUF/Rg0AQezTACgCACIAIAUgBmtqQQAgAGtxIgBB/v///wdLBEAgASEADAcLIAAQM0F/RwRAIAAgBmohBiABIQAMBwtBACAGaxAzGgwECyABIgBBf0cNBQwDC0EAIQMMDAtBACEADAoLIABBf0cNAgtByNMAQcjTACgCAEEEcjYCAAsgAkH+////B0sNASACEDMhAEEAEDMhASAAQX9GDQEgAUF/Rg0BIAAgAU8NASABIABrIgYgBEE4ak0NAQtBvNMAQbzTACgCACAGaiIBNgIAQcDTACgCACABSQRAQcDTACABNgIACwJAAkACQEGk0AAoAgAiAgRAQczTACEBA0AgACABKAIAIgMgASgCBCIFakYNAiABKAIIIgENAAsMAgtBnNAAKAIAIgFBAEcgACABT3FFBEBBnNAAIAA2AgALQQAhAUHQ0wAgBjYCAEHM0wAgADYCAEGs0ABBfzYCAEGw0ABB5NMAKAIANgIAQdjTAEEANgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBeCAAa0EPcSIBIABqIgIgBkE4ayIDIAFrIgFBAXI2AgRBqNAAQfTTACgCADYCAEGY0AAgATYCAEGk0AAgAjYCACAAIANqQTg2AgQMAgsgACACTQ0AIAIgA0kNACABKAIMQQhxDQBBeCACa0EPcSIAIAJqIgNBmNAAKAIAIAZqIgcgAGsiAEEBcjYCBCABIAUgBmo2AgRBqNAAQfTTACgCADYCAEGY0AAgADYCAEGk0AAgAzYCACACIAdqQTg2AgQMAQsgAEGc0AAoAgBJBEBBnNAAIAA2AgALIAAgBmohA0HM0wAhAQJAAkACQANAIAMgASgCAEcEQCABKAIIIgENAQwCCwsgAS0ADEEIcUUNAQtBzNMAIQEDQCABKAIAIgMgAk0EQCADIAEoAgRqIgUgAksNAwsgASgCCCEBDAALAAsgASAANgIAIAEgASgCBCAGajYCBCAAQXggAGtBD3FqIgkgBEEDcjYCBCADQXggA2tBD3FqIgYgBCAJaiIEayEBIAIgBkYEQEGk0AAgBDYCAEGY0ABBmNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEDAgLQaDQACgCACAGRgRAQaDQACAENgIAQZTQAEGU0AAoAgAgAWoiADYCACAEIABBAXI2AgQgACAEaiAANgIADAgLIAYoAgQiBUEDcUEBRw0GIAVBeHEhCCAFQf8BTQRAIAVBA3YhAyAGKAIIIgAgBigCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBwsgAiAANgIIIAAgAjYCDAwGCyAGKAIYIQcgBiAGKAIMIgBHBEAgACAGKAIIIgI2AgggAiAANgIMDAULIAZBFGoiAigCACIFRQRAIAYoAhAiBUUNBCAGQRBqIQILA0AgAiEDIAUiAEEUaiICKAIAIgUNACAAQRBqIQIgACgCECIFDQALIANBADYCAAwEC0F4IABrQQ9xIgEgAGoiByAGQThrIgMgAWsiAUEBcjYCBCAAIANqQTg2AgQgAiAFQTcgBWtBD3FqQT9rIgMgAyACQRBqSRsiA0EjNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAc2AgAgA0EQakHU0wApAgA3AgAgA0HM0wApAgA3AghB1NMAIANBCGo2AgBB0NMAIAY2AgBBzNMAIAA2AgBB2NMAQQA2AgAgA0EkaiEBA0AgAUEHNgIAIAUgAUEEaiIBSw0ACyACIANGDQAgAyADKAIEQX5xNgIEIAMgAyACayIFNgIAIAIgBUEBcjYCBCAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIDcUUEQEGM0AAgASADcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEGQ0AAoAgAiA0EBIAF0IgZxRQRAIAAgAjYCAEGQ0AAgAyAGcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQMCQANAIAMiACgCBEF4cSAFRg0BIAFBHXYhAyABQQF0IQEgACADQQRxakEQaiIGKAIAIgMNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAtBmNAAKAIAIgEgBE0NAEGk0AAoAgAiACAEaiICIAEgBGsiAUEBcjYCBEGY0AAgATYCAEGk0AAgAjYCACAAIARBA3I2AgQgAEEIaiEBDAgLQQAhAUH80wBBMDYCAAwHC0EAIQALIAdFDQACQCAGKAIcIgJBAnRBvNIAaiIDKAIAIAZGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAdBEEEUIAcoAhAgBkYbaiAANgIAIABFDQELIAAgBzYCGCAGKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAGQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAIaiEBIAYgCGoiBigCBCEFCyAGIAVBfnE2AgQgASAEaiABNgIAIAQgAUEBcjYCBCABQf8BTQRAIAFBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASABQQN2dCIBcUUEQEGM0AAgASACcjYCACAADAELIAAoAggLIgEgBDYCDCAAIAQ2AgggBCAANgIMIAQgATYCCAwBC0EfIQUgAUH///8HTQRAIAFBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohBQsgBCAFNgIcIARCADcCECAFQQJ0QbzSAGohAEGQ0AAoAgAiAkEBIAV0IgNxRQRAIAAgBDYCAEGQ0AAgAiADcjYCACAEIAA2AhggBCAENgIIIAQgBDYCDAwBCyABQRkgBUEBdmtBACAFQR9HG3QhBSAAKAIAIQACQANAIAAiAigCBEF4cSABRg0BIAVBHXYhACAFQQF0IQUgAiAAQQRxakEQaiIDKAIAIgANAAsgAyAENgIAIAQgAjYCGCAEIAQ2AgwgBCAENgIIDAELIAIoAggiACAENgIMIAIgBDYCCCAEQQA2AhggBCACNgIMIAQgADYCCAsgCUEIaiEBDAILAkAgB0UNAAJAIAMoAhwiAUECdEG80gBqIgIoAgAgA0YEQCACIAA2AgAgAA0BQZDQACAIQX4gAXdxIgg2AgAMAgsgB0EQQRQgBygCECADRhtqIAA2AgAgAEUNAQsgACAHNgIYIAMoAhAiAQRAIAAgATYCECABIAA2AhgLIANBFGooAgAiAUUNACAAQRRqIAE2AgAgASAANgIYCwJAIAVBD00EQCADIAQgBWoiAEEDcjYCBCAAIANqIgAgACgCBEEBcjYCBAwBCyADIARqIgIgBUEBcjYCBCADIARBA3I2AgQgAiAFaiAFNgIAIAVB/wFNBEAgBUF4cUG00ABqIQACf0GM0AAoAgAiAUEBIAVBA3Z0IgVxRQRAQYzQACABIAVyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRBvNIAaiEAQQEgAXQiBCAIcUUEQCAAIAI2AgBBkNAAIAQgCHI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEEAkADQCAEIgAoAgRBeHEgBUYNASABQR12IQQgAUEBdCEBIAAgBEEEcWpBEGoiBigCACIEDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLIANBCGohAQwBCwJAIAlFDQACQCAAKAIcIgFBAnRBvNIAaiICKAIAIABGBEAgAiADNgIAIAMNAUGQ0AAgC0F+IAF3cTYCAAwCCyAJQRBBFCAJKAIQIABGG2ogAzYCACADRQ0BCyADIAk2AhggACgCECIBBEAgAyABNgIQIAEgAzYCGAsgAEEUaigCACIBRQ0AIANBFGogATYCACABIAM2AhgLAkAgBUEPTQRAIAAgBCAFaiIBQQNyNgIEIAAgAWoiASABKAIEQQFyNgIEDAELIAAgBGoiByAFQQFyNgIEIAAgBEEDcjYCBCAFIAdqIAU2AgAgCARAIAhBeHFBtNAAaiEBQaDQACgCACEDAn9BASAIQQN2dCICIAZxRQRAQYzQACACIAZyNgIAIAEMAQsgASgCCAsiAiADNgIMIAEgAzYCCCADIAE2AgwgAyACNgIIC0Gg0AAgBzYCAEGU0AAgBTYCAAsgAEEIaiEBCyAKQRBqJAAgAQtDACAARQRAPwBBEHQPCwJAIABB//8DcQ0AIABBAEgNACAAQRB2QAAiAEF/RgRAQfzTAEEwNgIAQX8PCyAAQRB0DwsACwvcPyIAQYAICwkBAAAAAgAAAAMAQZQICwUEAAAABQBBpAgLCQYAAAAHAAAACABB3AgLii1JbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AFJlc3BvbnNlIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zAFVzZXIgY2FsbGJhY2sgZXJyb3IAYG9uX3Jlc2V0YCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfaGVhZGVyYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9iZWdpbmAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3N0YXR1c19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3ZlcnNpb25fY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl91cmxfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXRob2RfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfZmllbGRfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fbmFtZWAgY2FsbGJhY2sgZXJyb3IAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzZXJ2ZXIASW52YWxpZCBoZWFkZXIgdmFsdWUgY2hhcgBJbnZhbGlkIGhlYWRlciBmaWVsZCBjaGFyAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdmVyc2lvbgBJbnZhbGlkIG1pbm9yIHZlcnNpb24ASW52YWxpZCBtYWpvciB2ZXJzaW9uAEV4cGVjdGVkIHNwYWNlIGFmdGVyIHZlcnNpb24ARXhwZWN0ZWQgQ1JMRiBhZnRlciB2ZXJzaW9uAEludmFsaWQgSFRUUCB2ZXJzaW9uAEludmFsaWQgaGVhZGVyIHRva2VuAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdXJsAEludmFsaWQgY2hhcmFjdGVycyBpbiB1cmwAVW5leHBlY3RlZCBzdGFydCBjaGFyIGluIHVybABEb3VibGUgQCBpbiB1cmwARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgARHVwbGljYXRlIENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhciBpbiB1cmwgcGF0aABDb250ZW50LUxlbmd0aCBjYW4ndCBiZSBwcmVzZW50IHdpdGggVHJhbnNmZXItRW5jb2RpbmcASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgc2l6ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl92YWx1ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBQYXVzZWQgYnkgb25faGVhZGVyc19jb21wbGV0ZQBJbnZhbGlkIEVPRiBzdGF0ZQBvbl9yZXNldCBwYXVzZQBvbl9jaHVua19oZWFkZXIgcGF1c2UAb25fbWVzc2FnZV9iZWdpbiBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fdmFsdWUgcGF1c2UAb25fc3RhdHVzX2NvbXBsZXRlIHBhdXNlAG9uX3ZlcnNpb25fY29tcGxldGUgcGF1c2UAb25fdXJsX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXNzYWdlX2NvbXBsZXRlIHBhdXNlAG9uX21ldGhvZF9jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfZmllbGRfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUgcGF1c2UAVW5leHBlY3RlZCBzcGFjZSBhZnRlciBzdGFydCBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAFBhdXNlIG9uIENPTk5FQ1QvVXBncmFkZQBQYXVzZSBvbiBQUkkvVXBncmFkZQBFeHBlY3RlZCBIVFRQLzIgQ29ubmVjdGlvbiBQcmVmYWNlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fbWV0aG9kAEV4cGVjdGVkIHNwYWNlIGFmdGVyIG1ldGhvZABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl9maWVsZABQYXVzZWQASW52YWxpZCB3b3JkIGVuY291bnRlcmVkAEludmFsaWQgbWV0aG9kIGVuY291bnRlcmVkAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2NoZW1hAFJlcXVlc3QgaGFzIGludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYABTV0lUQ0hfUFJPWFkAVVNFX1BST1hZAE1LQUNUSVZJVFkAVU5QUk9DRVNTQUJMRV9FTlRJVFkAQ09QWQBNT1ZFRF9QRVJNQU5FTlRMWQBUT09fRUFSTFkATk9USUZZAEZBSUxFRF9ERVBFTkRFTkNZAEJBRF9HQVRFV0FZAFBMQVkAUFVUAENIRUNLT1VUAEdBVEVXQVlfVElNRU9VVABSRVFVRVNUX1RJTUVPVVQATkVUV09SS19DT05ORUNUX1RJTUVPVVQAQ09OTkVDVElPTl9USU1FT1VUAExPR0lOX1RJTUVPVVQATkVUV09SS19SRUFEX1RJTUVPVVQAUE9TVABNSVNESVJFQ1RFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX0xPQURfQkFMQU5DRURfUkVRVUVTVABCQURfUkVRVUVTVABIVFRQX1JFUVVFU1RfU0VOVF9UT19IVFRQU19QT1JUAFJFUE9SVABJTV9BX1RFQVBPVABSRVNFVF9DT05URU5UAE5PX0NPTlRFTlQAUEFSVElBTF9DT05URU5UAEhQRV9JTlZBTElEX0NPTlNUQU5UAEhQRV9DQl9SRVNFVABHRVQASFBFX1NUUklDVABDT05GTElDVABURU1QT1JBUllfUkVESVJFQ1QAUEVSTUFORU5UX1JFRElSRUNUAENPTk5FQ1QATVVMVElfU1RBVFVTAEhQRV9JTlZBTElEX1NUQVRVUwBUT09fTUFOWV9SRVFVRVNUUwBFQVJMWV9ISU5UUwBVTkFWQUlMQUJMRV9GT1JfTEVHQUxfUkVBU09OUwBPUFRJT05TAFNXSVRDSElOR19QUk9UT0NPTFMAVkFSSUFOVF9BTFNPX05FR09USUFURVMATVVMVElQTEVfQ0hPSUNFUwBJTlRFUk5BTF9TRVJWRVJfRVJST1IAV0VCX1NFUlZFUl9VTktOT1dOX0VSUk9SAFJBSUxHVU5fRVJST1IASURFTlRJVFlfUFJPVklERVJfQVVUSEVOVElDQVRJT05fRVJST1IAU1NMX0NFUlRJRklDQVRFX0VSUk9SAElOVkFMSURfWF9GT1JXQVJERURfRk9SAFNFVF9QQVJBTUVURVIAR0VUX1BBUkFNRVRFUgBIUEVfVVNFUgBTRUVfT1RIRVIASFBFX0NCX0NIVU5LX0hFQURFUgBNS0NBTEVOREFSAFNFVFVQAFdFQl9TRVJWRVJfSVNfRE9XTgBURUFSRE9XTgBIUEVfQ0xPU0VEX0NPTk5FQ1RJT04ASEVVUklTVElDX0VYUElSQVRJT04ARElTQ09OTkVDVEVEX09QRVJBVElPTgBOT05fQVVUSE9SSVRBVElWRV9JTkZPUk1BVElPTgBIUEVfSU5WQUxJRF9WRVJTSU9OAEhQRV9DQl9NRVNTQUdFX0JFR0lOAFNJVEVfSVNfRlJPWkVOAEhQRV9JTlZBTElEX0hFQURFUl9UT0tFTgBJTlZBTElEX1RPS0VOAEZPUkJJRERFTgBFTkhBTkNFX1lPVVJfQ0FMTQBIUEVfSU5WQUxJRF9VUkwAQkxPQ0tFRF9CWV9QQVJFTlRBTF9DT05UUk9MAE1LQ09MAEFDTABIUEVfSU5URVJOQUwAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRV9VTk9GRklDSUFMAEhQRV9PSwBVTkxJTksAVU5MT0NLAFBSSQBSRVRSWV9XSVRIAEhQRV9JTlZBTElEX0NPTlRFTlRfTEVOR1RIAEhQRV9VTkVYUEVDVEVEX0NPTlRFTlRfTEVOR1RIAEZMVVNIAFBST1BQQVRDSABNLVNFQVJDSABVUklfVE9PX0xPTkcAUFJPQ0VTU0lORwBNSVNDRUxMQU5FT1VTX1BFUlNJU1RFTlRfV0FSTklORwBNSVNDRUxMQU5FT1VTX1dBUk5JTkcASFBFX0lOVkFMSURfVFJBTlNGRVJfRU5DT0RJTkcARXhwZWN0ZWQgQ1JMRgBIUEVfSU5WQUxJRF9DSFVOS19TSVpFAE1PVkUAQ09OVElOVUUASFBFX0NCX1NUQVRVU19DT01QTEVURQBIUEVfQ0JfSEVBREVSU19DT01QTEVURQBIUEVfQ0JfVkVSU0lPTl9DT01QTEVURQBIUEVfQ0JfVVJMX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8AAF4TAAAmEwAAMBAAAPAXAACdEwAAFRIAADkXAADwEgAAChAAAHUSAACtEgAAghMAAE8UAAB/EAAAoBUAACMUAACJEgAAixQAAE0VAADUEQAAzxQAABAYAADJFgAA3BYAAMERAADgFwAAuxQAAHQUAAB8FQAA5RQAAAgXAAAfEAAAZRUAAKMUAAAoFQAAAhUAAJkVAAAsEAAAixkAAE8PAADUDgAAahAAAM4QAAACFwAAiQ4AAG4TAAAcEwAAZhQAAFYXAADBEwAAzRMAAGwTAABoFwAAZhcAAF8XAAAiEwAAzg8AAGkOAADYDgAAYxYAAMsTAACqDgAAKBcAACYXAADFEwAAXRYAAOgRAABnEwAAZRMAAPIWAABzEwAAHRcAAPkWAADzEQAAzw4AAM4VAAAMEgAAsxEAAKURAABhEAAAMhcAALsTAEH5NQsBAQBBkDYL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB/TcLAQEAQZE4C14CAwICAgICAAACAgACAgACAgICAgICAgICAAQAAAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEH9OQsBAQBBkToLXgIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAQfA7Cw1sb3NlZWVwLWFsaXZlAEGJPAsBAQBBoDwL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBiT4LAQEAQaA+C+cBAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAEGwwAALXwEBAAEBAQEBAAABAQABAQABAQEBAQEBAQEBAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAEGQwgALIWVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgBBwMIACy1yYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AQfnCAAsFAQIAAQMAQZDDAAvgAQQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH5xAALBQECAAEDAEGQxQAL4AEEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cYACwQBAAABAEGRxwAL3wEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH6yAALBAEAAAIAQZDJAAtfAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64'); + return llhttpWasm; +} + +var llhttp_simdWasm; +var hasRequiredLlhttp_simdWasm; + +function requireLlhttp_simdWasm () { + if (hasRequiredLlhttp_simdWasm) return llhttp_simdWasm; + hasRequiredLlhttp_simdWasm = 1; + + const { Buffer } = require$$0$3; + + llhttp_simdWasm = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK77MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtzACAAQRBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAA/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQTBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQSBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQd0BNgIcCwYAIAAQMguaLQELfyMAQRBrIgokAEGk0AAoAgAiCUUEQEHk0wAoAgAiBUUEQEHw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBCGpBcHFB2KrVqgVzIgU2AgBB+NMAQQA2AgBByNMAQQA2AgALQczTAEGA1AQ2AgBBnNAAQYDUBDYCAEGw0AAgBTYCAEGs0ABBfzYCAEHQ0wBBgKwDNgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBjNQEQcGrAzYCAEGo0ABB9NMAKAIANgIAQZjQAEHAqwM2AgBBpNAAQYjUBDYCAEHM/wdBODYCAEGI1AQhCQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQewBTQRAQYzQACgCACIGQRAgAEETakFwcSAAQQtJGyIEQQN2IgB2IgFBA3EEQAJAIAFBAXEgAHJBAXMiAkEDdCIAQbTQAGoiASAAQbzQAGooAgAiACgCCCIDRgRAQYzQACAGQX4gAndxNgIADAELIAEgAzYCCCADIAE2AgwLIABBCGohASAAIAJBA3QiAkEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwRC0GU0AAoAgAiCCAETw0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAEEDdCICQbTQAGoiASACQbzQAGooAgAiAigCCCIDRgRAQYzQACAGQX4gAHdxIgY2AgAMAQsgASADNgIIIAMgATYCDAsgAiAEQQNyNgIEIABBA3QiACAEayEFIAAgAmogBTYCACACIARqIgQgBUEBcjYCBCAIBEAgCEF4cUG00ABqIQBBoNAAKAIAIQMCf0EBIAhBA3Z0IgEgBnFFBEBBjNAAIAEgBnI2AgAgAAwBCyAAKAIICyIBIAM2AgwgACADNgIIIAMgADYCDCADIAE2AggLIAJBCGohAUGg0AAgBDYCAEGU0AAgBTYCAAwRC0GQ0AAoAgAiC0UNASALaEECdEG80gBqKAIAIgAoAgRBeHEgBGshBSAAIQIDQAJAIAIoAhAiAUUEQCACQRRqKAIAIgFFDQELIAEoAgRBeHEgBGsiAyAFSSECIAMgBSACGyEFIAEgACACGyEAIAEhAgwBCwsgACgCGCEJIAAoAgwiAyAARwRAQZzQACgCABogAyAAKAIIIgE2AgggASADNgIMDBALIABBFGoiAigCACIBRQRAIAAoAhAiAUUNAyAAQRBqIQILA0AgAiEHIAEiA0EUaiICKAIAIgENACADQRBqIQIgAygCECIBDQALIAdBADYCAAwPC0F/IQQgAEG/f0sNACAAQRNqIgFBcHEhBEGQ0AAoAgAiCEUNAEEAIARrIQUCQAJAAkACf0EAIARBgAJJDQAaQR8gBEH///8HSw0AGiAEQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qCyIGQQJ0QbzSAGooAgAiAkUEQEEAIQFBACEDDAELQQAhASAEQRkgBkEBdmtBACAGQR9HG3QhAEEAIQMDQAJAIAIoAgRBeHEgBGsiByAFTw0AIAIhAyAHIgUNAEEAIQUgAiEBDAMLIAEgAkEUaigCACIHIAcgAiAAQR12QQRxakEQaigCACICRhsgASAHGyEBIABBAXQhACACDQALCyABIANyRQRAQQAhA0ECIAZ0IgBBACAAa3IgCHEiAEUNAyAAaEECdEG80gBqKAIAIQELIAFFDQELA0AgASgCBEF4cSAEayICIAVJIQAgAiAFIAAbIQUgASADIAAbIQMgASgCECIABH8gAAUgAUEUaigCAAsiAQ0ACwsgA0UNACAFQZTQACgCACAEa08NACADKAIYIQcgAyADKAIMIgBHBEBBnNAAKAIAGiAAIAMoAggiATYCCCABIAA2AgwMDgsgA0EUaiICKAIAIgFFBEAgAygCECIBRQ0DIANBEGohAgsDQCACIQYgASIAQRRqIgIoAgAiAQ0AIABBEGohAiAAKAIQIgENAAsgBkEANgIADA0LQZTQACgCACIDIARPBEBBoNAAKAIAIQECQCADIARrIgJBEE8EQCABIARqIgAgAkEBcjYCBCABIANqIAI2AgAgASAEQQNyNgIEDAELIAEgA0EDcjYCBCABIANqIgAgACgCBEEBcjYCBEEAIQBBACECC0GU0AAgAjYCAEGg0AAgADYCACABQQhqIQEMDwtBmNAAKAIAIgMgBEsEQCAEIAlqIgAgAyAEayIBQQFyNgIEQaTQACAANgIAQZjQACABNgIAIAkgBEEDcjYCBCAJQQhqIQEMDwtBACEBIAQCf0Hk0wAoAgAEQEHs0wAoAgAMAQtB8NMAQn83AgBB6NMAQoCAhICAgMAANwIAQeTTACAKQQxqQXBxQdiq1aoFczYCAEH40wBBADYCAEHI0wBBADYCAEGAgAQLIgAgBEHHAGoiBWoiBkEAIABrIgdxIgJPBEBB/NMAQTA2AgAMDwsCQEHE0wAoAgAiAUUNAEG80wAoAgAiCCACaiEAIAAgAU0gACAIS3ENAEEAIQFB/NMAQTA2AgAMDwtByNMALQAAQQRxDQQCQAJAIAkEQEHM0wAhAQNAIAEoAgAiACAJTQRAIAAgASgCBGogCUsNAwsgASgCCCIBDQALC0EAEDMiAEF/Rg0FIAIhBkHo0wAoAgAiAUEBayIDIABxBEAgAiAAayAAIANqQQAgAWtxaiEGCyAEIAZPDQUgBkH+////B0sNBUHE0wAoAgAiAwRAQbzTACgCACIHIAZqIQEgASAHTQ0GIAEgA0sNBgsgBhAzIgEgAEcNAQwHCyAGIANrIAdxIgZB/v///wdLDQQgBhAzIQAgACABKAIAIAEoAgRqRg0DIAAhAQsCQCAGIARByABqTw0AIAFBf0YNAEHs0wAoAgAiACAFIAZrakEAIABrcSIAQf7///8HSwRAIAEhAAwHCyAAEDNBf0cEQCAAIAZqIQYgASEADAcLQQAgBmsQMxoMBAsgASIAQX9HDQUMAwtBACEDDAwLQQAhAAwKCyAAQX9HDQILQcjTAEHI0wAoAgBBBHI2AgALIAJB/v///wdLDQEgAhAzIQBBABAzIQEgAEF/Rg0BIAFBf0YNASAAIAFPDQEgASAAayIGIARBOGpNDQELQbzTAEG80wAoAgAgBmoiATYCAEHA0wAoAgAgAUkEQEHA0wAgATYCAAsCQAJAAkBBpNAAKAIAIgIEQEHM0wAhAQNAIAAgASgCACIDIAEoAgQiBWpGDQIgASgCCCIBDQALDAILQZzQACgCACIBQQBHIAAgAU9xRQRAQZzQACAANgIAC0EAIQFB0NMAIAY2AgBBzNMAIAA2AgBBrNAAQX82AgBBsNAAQeTTACgCADYCAEHY0wBBADYCAANAIAFByNAAaiABQbzQAGoiAjYCACACIAFBtNAAaiIDNgIAIAFBwNAAaiADNgIAIAFB0NAAaiABQcTQAGoiAzYCACADIAI2AgAgAUHY0ABqIAFBzNAAaiICNgIAIAIgAzYCACABQdTQAGogAjYCACABQSBqIgFBgAJHDQALQXggAGtBD3EiASAAaiICIAZBOGsiAyABayIBQQFyNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAI2AgAgACADakE4NgIEDAILIAAgAk0NACACIANJDQAgASgCDEEIcQ0AQXggAmtBD3EiACACaiIDQZjQACgCACAGaiIHIABrIgBBAXI2AgQgASAFIAZqNgIEQajQAEH00wAoAgA2AgBBmNAAIAA2AgBBpNAAIAM2AgAgAiAHakE4NgIEDAELIABBnNAAKAIASQRAQZzQACAANgIACyAAIAZqIQNBzNMAIQECQAJAAkADQCADIAEoAgBHBEAgASgCCCIBDQEMAgsLIAEtAAxBCHFFDQELQczTACEBA0AgASgCACIDIAJNBEAgAyABKAIEaiIFIAJLDQMLIAEoAgghAQwACwALIAEgADYCACABIAEoAgQgBmo2AgQgAEF4IABrQQ9xaiIJIARBA3I2AgQgA0F4IANrQQ9xaiIGIAQgCWoiBGshASACIAZGBEBBpNAAIAQ2AgBBmNAAQZjQACgCACABaiIANgIAIAQgAEEBcjYCBAwIC0Gg0AAoAgAgBkYEQEGg0AAgBDYCAEGU0ABBlNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEIAAgBGogADYCAAwICyAGKAIEIgVBA3FBAUcNBiAFQXhxIQggBUH/AU0EQCAFQQN2IQMgBigCCCIAIAYoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAcLIAIgADYCCCAAIAI2AgwMBgsgBigCGCEHIAYgBigCDCIARwRAIAAgBigCCCICNgIIIAIgADYCDAwFCyAGQRRqIgIoAgAiBUUEQCAGKAIQIgVFDQQgBkEQaiECCwNAIAIhAyAFIgBBFGoiAigCACIFDQAgAEEQaiECIAAoAhAiBQ0ACyADQQA2AgAMBAtBeCAAa0EPcSIBIABqIgcgBkE4ayIDIAFrIgFBAXI2AgQgACADakE4NgIEIAIgBUE3IAVrQQ9xakE/ayIDIAMgAkEQakkbIgNBIzYCBEGo0ABB9NMAKAIANgIAQZjQACABNgIAQaTQACAHNgIAIANBEGpB1NMAKQIANwIAIANBzNMAKQIANwIIQdTTACADQQhqNgIAQdDTACAGNgIAQczTACAANgIAQdjTAEEANgIAIANBJGohAQNAIAFBBzYCACAFIAFBBGoiAUsNAAsgAiADRg0AIAMgAygCBEF+cTYCBCADIAMgAmsiBTYCACACIAVBAXI2AgQgBUH/AU0EQCAFQXhxQbTQAGohAAJ/QYzQACgCACIBQQEgBUEDdnQiA3FFBEBBjNAAIAEgA3I2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEG80gBqIQBBkNAAKAIAIgNBASABdCIGcUUEQCAAIAI2AgBBkNAAIAMgBnI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEDAkADQCADIgAoAgRBeHEgBUYNASABQR12IQMgAUEBdCEBIAAgA0EEcWpBEGoiBigCACIDDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLQZjQACgCACIBIARNDQBBpNAAKAIAIgAgBGoiAiABIARrIgFBAXI2AgRBmNAAIAE2AgBBpNAAIAI2AgAgACAEQQNyNgIEIABBCGohAQwIC0EAIQFB/NMAQTA2AgAMBwtBACEACyAHRQ0AAkAgBigCHCICQQJ0QbzSAGoiAygCACAGRgRAIAMgADYCACAADQFBkNAAQZDQACgCAEF+IAJ3cTYCAAwCCyAHQRBBFCAHKAIQIAZGG2ogADYCACAARQ0BCyAAIAc2AhggBigCECICBEAgACACNgIQIAIgADYCGAsgBkEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgCGohASAGIAhqIgYoAgQhBQsgBiAFQX5xNgIEIAEgBGogATYCACAEIAFBAXI2AgQgAUH/AU0EQCABQXhxQbTQAGohAAJ/QYzQACgCACICQQEgAUEDdnQiAXFFBEBBjNAAIAEgAnI2AgAgAAwBCyAAKAIICyIBIAQ2AgwgACAENgIIIAQgADYCDCAEIAE2AggMAQtBHyEFIAFB////B00EQCABQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qIQULIAQgBTYCHCAEQgA3AhAgBUECdEG80gBqIQBBkNAAKAIAIgJBASAFdCIDcUUEQCAAIAQ2AgBBkNAAIAIgA3I2AgAgBCAANgIYIAQgBDYCCCAEIAQ2AgwMAQsgAUEZIAVBAXZrQQAgBUEfRxt0IQUgACgCACEAAkADQCAAIgIoAgRBeHEgAUYNASAFQR12IQAgBUEBdCEFIAIgAEEEcWpBEGoiAygCACIADQALIAMgBDYCACAEIAI2AhggBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAlBCGohAQwCCwJAIAdFDQACQCADKAIcIgFBAnRBvNIAaiICKAIAIANGBEAgAiAANgIAIAANAUGQ0AAgCEF+IAF3cSIINgIADAILIAdBEEEUIAcoAhAgA0YbaiAANgIAIABFDQELIAAgBzYCGCADKAIQIgEEQCAAIAE2AhAgASAANgIYCyADQRRqKAIAIgFFDQAgAEEUaiABNgIAIAEgADYCGAsCQCAFQQ9NBEAgAyAEIAVqIgBBA3I2AgQgACADaiIAIAAoAgRBAXI2AgQMAQsgAyAEaiICIAVBAXI2AgQgAyAEQQNyNgIEIAIgBWogBTYCACAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIFcUUEQEGM0AAgASAFcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEEBIAF0IgQgCHFFBEAgACACNgIAQZDQACAEIAhyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhBAJAA0AgBCIAKAIEQXhxIAVGDQEgAUEddiEEIAFBAXQhASAAIARBBHFqQRBqIgYoAgAiBA0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIICyADQQhqIQEMAQsCQCAJRQ0AAkAgACgCHCIBQQJ0QbzSAGoiAigCACAARgRAIAIgAzYCACADDQFBkNAAIAtBfiABd3E2AgAMAgsgCUEQQRQgCSgCECAARhtqIAM2AgAgA0UNAQsgAyAJNgIYIAAoAhAiAQRAIAMgATYCECABIAM2AhgLIABBFGooAgAiAUUNACADQRRqIAE2AgAgASADNgIYCwJAIAVBD00EQCAAIAQgBWoiAUEDcjYCBCAAIAFqIgEgASgCBEEBcjYCBAwBCyAAIARqIgcgBUEBcjYCBCAAIARBA3I2AgQgBSAHaiAFNgIAIAgEQCAIQXhxQbTQAGohAUGg0AAoAgAhAwJ/QQEgCEEDdnQiAiAGcUUEQEGM0AAgAiAGcjYCACABDAELIAEoAggLIgIgAzYCDCABIAM2AgggAyABNgIMIAMgAjYCCAtBoNAAIAc2AgBBlNAAIAU2AgALIABBCGohAQsgCkEQaiQAIAELQwAgAEUEQD8AQRB0DwsCQCAAQf//A3ENACAAQQBIDQAgAEEQdkAAIgBBf0YEQEH80wBBMDYCAEF/DwsgAEEQdA8LAAsL3D8iAEGACAsJAQAAAAIAAAADAEGUCAsFBAAAAAUAQaQICwkGAAAABwAAAAgAQdwIC4otSW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwBB+TULAQEAQZA2C+ABAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQf03CwEBAEGROAteAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgBB/TkLAQEAQZE6C14CAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEHwOwsNbG9zZWVlcC1hbGl2ZQBBiTwLAQEAQaA8C+ABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQYk+CwEBAEGgPgvnAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZABBsMAAC18BAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBBkMIACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQcDCAAstcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQoNClNNDQoNClRUUC9DRS9UU1AvAEH5wgALBQECAAEDAEGQwwAL4AEEAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cQACwUBAgABAwBBkMUAC+ABBAEBBQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQfnGAAsEAQAAAQBBkccAC98BAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+sgACwQBAAACAEGQyQALXwMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAEH6ygALBAEAAAEAQZDLAAsBAQBBqssAC0ECAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB+swACwQBAAABAEGQzQALAQEAQZrNAAsGAgAAAAACAEGxzQALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64'); + return llhttp_simdWasm; +} + +var constants$2; +var hasRequiredConstants$2; + +function requireConstants$2 () { + if (hasRequiredConstants$2) return constants$2; + hasRequiredConstants$2 = 1; + + const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']); + const corsSafeListedMethodsSet = new Set(corsSafeListedMethods); + + const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]); + + const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]); + const redirectStatusSet = new Set(redirectStatus); + + /** + * @see https://fetch.spec.whatwg.org/#block-bad-port + */ + const badPorts = /** @type {const} */ ([ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', + '6697', '10080' + ]); + const badPortsSet = new Set(badPorts); + + /** + * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies + */ + const referrerPolicy = /** @type {const} */ ([ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' + ]); + const referrerPolicySet = new Set(referrerPolicy); + + const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']); + + const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']); + const safeMethodsSet = new Set(safeMethods); + + const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']); + + const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']); + + const requestCache = /** @type {const} */ ([ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' + ]); + + /** + * @see https://fetch.spec.whatwg.org/#request-body-header-name + */ + const requestBodyHeader = /** @type {const} */ ([ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' + ]); + + /** + * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex + */ + const requestDuplex = /** @type {const} */ ([ + 'half' + ]); + + /** + * @see http://fetch.spec.whatwg.org/#forbidden-method + */ + const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']); + const forbiddenMethodsSet = new Set(forbiddenMethods); + + const subresource = /** @type {const} */ ([ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' + ]); + const subresourceSet = new Set(subresource); + + constants$2 = { + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet + }; + return constants$2; +} + +var global$2; +var hasRequiredGlobal$1; + +function requireGlobal$1 () { + if (hasRequiredGlobal$1) return global$2; + hasRequiredGlobal$1 = 1; + + // In case of breaking changes, increase the version + // number to avoid conflicts. + const globalOrigin = Symbol.for('undici.globalOrigin.1'); + + function getGlobalOrigin () { + return globalThis[globalOrigin] + } + + function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }); + + return + } + + const parsedURL = new URL(newOrigin); + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }); + } + + global$2 = { + getGlobalOrigin, + setGlobalOrigin + }; + return global$2; +} + +var dataUrl; +var hasRequiredDataUrl; + +function requireDataUrl () { + if (hasRequiredDataUrl) return dataUrl; + hasRequiredDataUrl = 1; + + const assert = require$$0$4; + + const encoder = new TextEncoder(); + + /** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ + const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/; + const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/; // eslint-disable-line + const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g; // eslint-disable-line + /** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ + const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/; // eslint-disable-line + + // https://fetch.spec.whatwg.org/#data-url-processor + /** @param {URL} dataURL */ + function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:'); + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true); + + // 3. Remove the leading "data:" string from input. + input = input.slice(5); + + // 4. Let position point at the start of input. + const position = { position: 0 }; + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ); + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length; + mimeType = removeASCIIWhitespace(mimeType, true, true); + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++; + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1); + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody); + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body); + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody); + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6); + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, ''); + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1); + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType; + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType); + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII'); + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } + } + + // https://url.spec.whatwg.org/#concept-url-serializer + /** + * @param {URL} url + * @param {boolean} excludeFragment + */ + function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href; + const hashLength = url.hash.length; + + const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength); + + if (!hashLength && href.endsWith('#')) { + return serialized.slice(0, -1) + } + + return serialized + } + + // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points + /** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ + function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = ''; + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position]; + + // 2. Advance position by 1. + position.position++; + } + + // 3. Return result. + return result + } + + /** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ + function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position); + const start = position.position; + + if (idx === -1) { + position.position = input.length; + return input.slice(start) + } + + position.position = idx; + return input.slice(start, position.position) + } + + // https://url.spec.whatwg.org/#string-percent-decode + /** @param {string} input */ + function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input); + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) + } + + /** + * @param {number} byte + */ + function isHexCharByte (byte) { + // 0-9 A-F a-f + return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) + } + + /** + * @param {number} byte + */ + function hexByteToNumber (byte) { + return ( + // 0-9 + byte >= 0x30 && byte <= 0x39 + ? (byte - 48) + // Convert to uppercase + // ((byte & 0xDF) - 65) + 10 + : ((byte & 0xDF) - 55) + ) + } + + // https://url.spec.whatwg.org/#percent-decode + /** @param {Uint8Array} input */ + function percentDecode (input) { + const length = input.length; + // 1. Let output be an empty byte sequence. + /** @type {Uint8Array} */ + const output = new Uint8Array(length); + let j = 0; + // 2. For each byte byte in input: + for (let i = 0; i < length; ++i) { + const byte = input[i]; + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output[j++] = byte; + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) + ) { + output[j++] = 0x25; + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + // 2. Append a byte whose value is bytePoint to output. + output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]); + + // 3. Skip the next two bytes in input. + i += 2; + } + } + + // 3. Return output. + return length === j ? output : output.subarray(0, j) + } + + // https://mimesniff.spec.whatwg.org/#parse-a-mime-type + /** @param {string} input */ + function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true); + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 }; + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ); + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++; + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true); + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase(); + const subtypeLowercase = subtype.toLowerCase(); + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + }; + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++; + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ); + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ); + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase(); + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++; + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null; + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true); + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true); + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue); + } + } + + // 12. Return mimeType. + return mimeType + } + + // https://infra.spec.whatwg.org/#forgiving-base64-decode + /** @param {string} data */ + function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, ''); // eslint-disable-line + + let dataLength = data.length; + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (dataLength % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength; + if (data.charCodeAt(dataLength - 1) === 0x003D) { + --dataLength; + } + } + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (dataLength % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { + return 'failure' + } + + const buffer = Buffer.from(data, 'base64'); + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) + } + + // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string + // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string + /** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ + function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position; + + // 2. Let value be the empty string. + let value = ''; + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"'); + + // 4. Advance position by 1. + position.position++; + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ); + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position]; + + // 4. Advance position by 1. + position.position++; + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\'; + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position]; + + // 3. Advance position by 1. + position.position++; + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"'); + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) + } + + /** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ + function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure'); + const { parameters, essence } = mimeType; + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence; + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';'; + + // 2. Append name to serialization. + serialization += name; + + // 3. Append U+003D (=) to serialization. + serialization += '='; + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurrence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1'); + + // 2. Prepend U+0022 (") to value. + value = '"' + value; + + // 3. Append U+0022 (") to value. + value += '"'; + } + + // 5. Append value to serialization. + serialization += value; + } + + // 3. Return serialization. + return serialization + } + + /** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {number} char + */ + function isHTTPWhiteSpace (char) { + // "\r\n\t " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 + } + + /** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ + function removeHTTPWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isHTTPWhiteSpace) + } + + /** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {number} char + */ + function isASCIIWhitespace (char) { + // "\r\n\t\f " + return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 + } + + /** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + * @param {string} str + * @param {boolean} [leading=true] + * @param {boolean} [trailing=true] + */ + function removeASCIIWhitespace (str, leading = true, trailing = true) { + return removeChars(str, leading, trailing, isASCIIWhitespace) + } + + /** + * @param {string} str + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns + */ + function removeChars (str, leading, trailing, predicate) { + let lead = 0; + let trail = str.length - 1; + + if (leading) { + while (lead < str.length && predicate(str.charCodeAt(lead))) lead++; + } + + if (trailing) { + while (trail > 0 && predicate(str.charCodeAt(trail))) trail--; + } + + return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) + } + + /** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {Uint8Array} input + * @returns {string} + */ + function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + const length = input.length; + if ((2 << 15) - 1 > length) { + return String.fromCharCode.apply(null, input) + } + let result = ''; let i = 0; + let addition = (2 << 15) - 1; + while (i < length) { + if (i + addition > length) { + addition = length - i; + } + result += String.fromCharCode.apply(null, input.subarray(i, i += addition)); + } + return result + } + + /** + * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type + * @param {Exclude, 'failure'>} mimeType + */ + function minimizeSupportedMimeType (mimeType) { + switch (mimeType.essence) { + case 'application/ecmascript': + case 'application/javascript': + case 'application/x-ecmascript': + case 'application/x-javascript': + case 'text/ecmascript': + case 'text/javascript': + case 'text/javascript1.0': + case 'text/javascript1.1': + case 'text/javascript1.2': + case 'text/javascript1.3': + case 'text/javascript1.4': + case 'text/javascript1.5': + case 'text/jscript': + case 'text/livescript': + case 'text/x-ecmascript': + case 'text/x-javascript': + // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". + return 'text/javascript' + case 'application/json': + case 'text/json': + // 2. If mimeType is a JSON MIME type, then return "application/json". + return 'application/json' + case 'image/svg+xml': + // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". + return 'image/svg+xml' + case 'text/xml': + case 'application/xml': + // 4. If mimeType is an XML MIME type, then return "application/xml". + return 'application/xml' + } + + // 2. If mimeType is a JSON MIME type, then return "application/json". + if (mimeType.subtype.endsWith('+json')) { + return 'application/json' + } + + // 4. If mimeType is an XML MIME type, then return "application/xml". + if (mimeType.subtype.endsWith('+xml')) { + return 'application/xml' + } + + // 5. If mimeType is supported by the user agent, then return mimeType’s essence. + // Technically, node doesn't support any mimetypes. + + // 6. Return the empty string. + return '' + } + + dataUrl = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType, + removeChars, + removeHTTPWhitespace, + minimizeSupportedMimeType, + HTTP_TOKEN_CODEPOINTS, + isomorphicDecode + }; + return dataUrl; +} + +var webidl_1; +var hasRequiredWebidl; + +function requireWebidl () { + if (hasRequiredWebidl) return webidl_1; + hasRequiredWebidl = 1; + + const { types, inspect } = require$$0$7; + const { markAsUncloneable } = require$$1$4; + const { toUSVString } = requireUtil$9(); + + /** @type {import('../../../types/webidl').Webidl} */ + const webidl = {}; + webidl.converters = {}; + webidl.util = {}; + webidl.errors = {}; + + webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) + }; + + webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of'; + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.`; + + return webidl.errors.exception({ + header: context.prefix, + message + }) + }; + + webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) + }; + + // https://webidl.spec.whatwg.org/#implements + webidl.brandCheck = function (V, I, opts) { + if (opts?.strict !== false) { + if (!(V instanceof I)) { + const err = new TypeError('Illegal invocation'); + err.code = 'ERR_INVALID_THIS'; // node compat. + throw err + } + } else { + if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) { + const err = new TypeError('Illegal invocation'); + err.code = 'ERR_INVALID_THIS'; // node compat. + throw err + } + } + }; + + webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + header: ctx + }) + } + }; + + webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) + }; + + // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } + }; + + webidl.util.markAsUncloneable = markAsUncloneable || (() => {}); + // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { + let upperBound; + let lowerBound; + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1; + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0; + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1; + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0; + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1; + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1; + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1; + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V); + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0; + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts?.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x); + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts?.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound); + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x); + } else { + x = Math.ceil(x); + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x); + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength); + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x + }; + + // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart + webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)); + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r + }; + + webidl.util.Stringify = function (V) { + const type = webidl.util.Type(V); + + switch (type) { + case 'Symbol': + return `Symbol(${V.description})` + case 'Object': + return inspect(V) + case 'String': + return `"${V}"` + default: + return `${V}` + } + }; + + // https://webidl.spec.whatwg.org/#es-sequence + webidl.sequenceConverter = function (converter) { + return (V, prefix, argument, Iterable) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.(); + const seq = []; + let index = 0; + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is not iterable.` + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next(); + + if (done) { + break + } + + seq.push(converter(value, prefix, `${argument}[${index++}]`)); + } + + return seq + } + }; + + // https://webidl.spec.whatwg.org/#es-to-record + webidl.recordConverter = function (keyConverter, valueConverter) { + return (O, prefix, argument) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} ("${webidl.util.Type(O)}") is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {}; + + if (!types.isProxy(O)) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]; + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument); + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument); + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue; + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O); + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key); + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key, prefix, argument); + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key], prefix, argument); + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue; + } + } + + // 5. Return result. + return result + } + }; + + webidl.interfaceConverter = function (i) { + return (V, prefix, argument, opts) => { + if (opts?.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.` + }) + } + + return V + } + }; + + webidl.dictionaryConverter = function (converters) { + return (dictionary, prefix, argument) => { + const type = webidl.util.Type(dictionary); + const dict = {}; + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: prefix, + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options; + + if (required === true) { + if (!Object.hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: prefix, + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key]; + const hasDefault = Object.hasOwn(options, 'defaultValue'); + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value ??= defaultValue(); + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value, prefix, `${argument}.${key}`); + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: prefix, + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value; + } + } + + return dict + } + }; + + webidl.nullableConverter = function (converter) { + return (V, prefix, argument) => { + if (V === null) { + return V + } + + return converter(V, prefix, argument) + } + }; + + // https://webidl.spec.whatwg.org/#es-DOMString + webidl.converters.DOMString = function (V, prefix, argument, opts) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts?.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw webidl.errors.exception({ + header: prefix, + message: `${argument} is a symbol, which cannot be converted to a DOMString.` + }) + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) + }; + + // https://webidl.spec.whatwg.org/#es-ByteString + webidl.converters.ByteString = function (V, prefix, argument) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V, prefix, argument); + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-USVString + // TODO: rewrite this so we can control the errors thrown + webidl.converters.USVString = toUSVString; + + // https://webidl.spec.whatwg.org/#es-boolean + webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V); + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-any + webidl.converters.any = function (V) { + return V + }; + + // https://webidl.spec.whatwg.org/#es-long-long + webidl.converters['long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument); + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-long-long + webidl.converters['unsigned long long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument); + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-long + webidl.converters['unsigned long'] = function (V, prefix, argument) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument); + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-short + webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument); + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#idl-ArrayBuffer + webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${argument} ("${webidl.util.Stringify(V)}")`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + if (V.resizable || V.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V + }; + + webidl.converters.TypedArray = function (V, T, prefix, name, opts) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix, + argument: `${name} ("${webidl.util.Stringify(V)}")`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V + }; + + webidl.converters.DataView = function (V, prefix, name, opts) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: prefix, + message: `${name} is not a DataView.` + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (V.buffer.resizable || V.buffer.growable) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'Received a resizable ArrayBuffer.' + }) + } + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V + }; + + // https://webidl.spec.whatwg.org/#BufferSource + webidl.converters.BufferSource = function (V, prefix, name, opts) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false }) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false }) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false }) + } + + throw webidl.errors.conversionFailed({ + prefix, + argument: `${name} ("${webidl.util.Stringify(V)}")`, + types: ['BufferSource'] + }) + }; + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString + ); + + webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] + ); + + webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString + ); + + webidl_1 = { + webidl + }; + return webidl_1; +} + +var util$8; +var hasRequiredUtil$8; + +function requireUtil$8 () { + if (hasRequiredUtil$8) return util$8; + hasRequiredUtil$8 = 1; + + const { Transform } = require$$0$5; + const zlib = require$$1$5; + const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = requireConstants$2(); + const { getGlobalOrigin } = requireGlobal$1(); + const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = requireDataUrl(); + const { performance } = require$$5$2; + const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = requireUtil$9(); + const assert = require$$0$4; + const { isUint8Array } = require$$8$1; + const { webidl } = requireWebidl(); + + let supportedHashes = []; + + // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable + /** @type {import('crypto')} */ + let crypto; + try { + crypto = require('node:crypto'); + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']; + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)); + /* c8 ignore next 3 */ + } catch { + + } + + function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList; + const length = urlList.length; + return length === 0 ? null : urlList[length - 1].toString() + } + + // https://fetch.spec.whatwg.org/#concept-response-location-url + function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location', true); + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + if (!isValidEncodedURL(location)) { + // Some websites respond location header in UTF-8 form without encoding them as ASCII + // and major browsers redirect them to correctly UTF-8 encoded addresses. + // Here, we handle that behavior in the same way. + location = normalizeBinaryStringToUtf8(location); + } + location = new URL(location, responseURL(response)); + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment; + } + + // 5. Return location. + return location + } + + /** + * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 + * @param {string} url + * @returns {boolean} + */ + function isValidEncodedURL (url) { + for (let i = 0; i < url.length; ++i) { + const code = url.charCodeAt(i); + + if ( + code > 0x7E || // Non-US-ASCII + DEL + code < 0x20 // Control characters NUL - US + ) { + return false + } + } + return true + } + + /** + * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. + * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. + * @param {string} value + * @returns {string} + */ + function normalizeBinaryStringToUtf8 (value) { + return Buffer.from(value, 'binary').toString('utf8') + } + + /** @returns {URL} */ + function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] + } + + function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request); + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' + } + + function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) + } + + // Check whether |statusText| is a ByteString and + // matches the Reason-Phrase token production. + // RFC 2616: https://tools.ietf.org/html/rfc2616 + // RFC 7230: https://tools.ietf.org/html/rfc7230 + // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" + // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 + function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i); + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true + } + + /** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ + const isValidHeaderName = isValidHTTPToken; + + /** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ + function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + return ( + potentialValue[0] === '\t' || + potentialValue[0] === ' ' || + potentialValue[potentialValue.length - 1] === '\t' || + potentialValue[potentialValue.length - 1] === ' ' || + potentialValue.includes('\n') || + potentialValue.includes('\r') || + potentialValue.includes('\0') + ) === false + } + + // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect + function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse; + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(','); + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = ''; + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim(); + if (referrerPolicyTokens.has(token)) { + policy = token; + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy; + } + } + + // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check + function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' + } + + // https://fetch.spec.whatwg.org/#concept-cors-check + function corsCheck () { + // TODO + return 'success' + } + + // https://fetch.spec.whatwg.org/#concept-tao-check + function TAOCheck () { + // TODO + return 'success' + } + + function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null; + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode; + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header, true); + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO + } + + // https://fetch.spec.whatwg.org/#append-a-request-origin-header + function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin + // with request. + // TODO: implement "byte-serializing a request origin" + let serializedOrigin = request.origin; + + // - "'client' is changed to an origin during fetching." + // This doesn't happen in undici (in most cases) because undici, by default, + // has no concept of origin. + // - request.origin can also be set to request.client.origin (client being + // an environment settings object), which is undefined without using + // setGlobalOrigin. + if (serializedOrigin === 'client' || serializedOrigin === undefined) { + return + } + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", + // then append (`Origin`, serializedOrigin) to request’s header list. + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + request.headersList.append('origin', serializedOrigin, true); + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null; + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and + // request’s current URL’s scheme is not "https", then set + // serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null; + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s + // origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null; + } + break + // Do nothing. + } + + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin, true); + } + } + + // https://w3c.github.io/hr-time/#dfn-coarsen-time + function coarsenTime (timestamp, crossOriginIsolatedCapability) { + // TODO + return timestamp + } + + // https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info + function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { + if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { + return { + domainLookupStartTime: defaultStartTime, + domainLookupEndTime: defaultStartTime, + connectionStartTime: defaultStartTime, + connectionEndTime: defaultStartTime, + secureConnectionStartTime: defaultStartTime, + ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol + } + } + + return { + domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime), + domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime), + connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime), + connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime), + secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime), + ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol + } + } + + // https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time + function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + return coarsenTime(performance.now()) + } + + // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info + function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } + } + + // https://html.spec.whatwg.org/multipage/origin.html#policy-container + function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } + } + + // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container + function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } + } + + // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer + function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy; + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy); + + // 2. Let environment be request’s client. + + let referrerSource = null; + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin(); + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin); + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer; + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource); + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true); + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + + const areSameOrigin = sameOrigin(request, referrerURL); + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url); + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request); + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } + } + + /** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ + function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL); + + url = new URL(url); + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = ''; + + // 4. Set url’s password to the empty string. + url.password = ''; + + // 5. Set url’s fragment to null. + url.hash = ''; + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = ''; + + // 2. Set url’s query to null. + url.search = ''; + } + + // 7. Return url. + return url + } + + function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin); + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } + } + + /** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ + function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList); + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If response is not eligible for integrity validation, return false. + // TODO + + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata); + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest); + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo; + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash; + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64'); + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2); + } else { + actualValue = actualValue.slice(0, -1); + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } + + // 7. Return false. + return false + } + + // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options + // https://www.w3.org/TR/CSP2/#source-list-syntax + // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 + const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i; + + /** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ + function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = []; + + // 2. Let empty be equal to true. + let empty = true; + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false; + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token); + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase(); + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups); + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result + } + + /** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ + function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo; + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i]; + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512'; + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384'; + } + } + return algorithm + } + + function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } + + let pos = 0; + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i]; + } + } + + metadataList.length = pos; + + return metadataList + } + + /** + * Compares two base64 strings, allowing for base64url + * in the second string. + * + * @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ + function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + } + + return true + } + + // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request + function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO + } + + /** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ + function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false + } + + function createDeferredPromise () { + let res; + let rej; + const promise = new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + + return { promise, resolve: res, reject: rej } + } + + function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' + } + + function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ + function normalizeMethod (method) { + return normalizedMethodRecordsBase[method.toLowerCase()] ?? method + } + + // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string + function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value); + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string'); + + // 4. Return result. + return result + } + + // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object + const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); + + /** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {symbol} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ + function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { + class FastIterableIterator { + /** @type {any} */ + #target + /** @type {'key' | 'value' | 'key+value'} */ + #kind + /** @type {number} */ + #index + + /** + * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + */ + constructor (target, kind) { + this.#target = target; + this.#kind = kind; + this.#index = 0; + } + + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + // 2. Let thisValue be the this value. + // 3. Let object be ? ToObject(thisValue). + // 4. If object is a platform object, then perform a security + // check, passing: + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (typeof this !== 'object' || this === null || !(#target in this)) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const index = this.#index; + const values = this.#target[kInternalIterator]; + + // 9. Let len be the length of values. + const len = values.length; + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { + value: undefined, + done: true + } + } + + // 11. Let pair be the entry in values at index index. + const { [keyIndex]: key, [valueIndex]: value } = values[index]; + + // 12. Set object’s index to index + 1. + this.#index = index + 1; + + // 13. Return the iterator result for pair and kind. + + // https://webidl.spec.whatwg.org/#iterator-result + + // 1. Let result be a value determined by the value of kind: + let result; + switch (this.#kind) { + case 'key': + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = key; + break + case 'value': + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = value; + break + case 'key+value': + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = [key, value]; + break + } + + // 2. Return CreateIterResultObject(result, false). + return { + value: result, + done: false + } + } + } + + // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + // @ts-ignore + delete FastIterableIterator.prototype.constructor; + + Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype); + + Object.defineProperties(FastIterableIterator.prototype, { + [Symbol.toStringTag]: { + writable: false, + enumerable: false, + configurable: true, + value: `${name} Iterator` + }, + next: { writable: true, enumerable: true, configurable: true } + }); + + /** + * @param {unknown} target + * @param {'key' | 'value' | 'key+value'} kind + * @returns {IterableIterator} + */ + return function (target, kind) { + return new FastIterableIterator(target, kind) + } + } + + /** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {string} name name of the instance + * @param {any} object class + * @param {symbol} kInternalIterator + * @param {string | number} [keyIndex] + * @param {string | number} [valueIndex] + */ + function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { + const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex); + + const properties = { + keys: { + writable: true, + enumerable: true, + configurable: true, + value: function keys () { + webidl.brandCheck(this, object); + return makeIterator(this, 'key') + } + }, + values: { + writable: true, + enumerable: true, + configurable: true, + value: function values () { + webidl.brandCheck(this, object); + return makeIterator(this, 'value') + } + }, + entries: { + writable: true, + enumerable: true, + configurable: true, + value: function entries () { + webidl.brandCheck(this, object); + return makeIterator(this, 'key+value') + } + }, + forEach: { + writable: true, + enumerable: true, + configurable: true, + value: function forEach (callbackfn, thisArg = globalThis) { + webidl.brandCheck(this, object); + webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`); + if (typeof callbackfn !== 'function') { + throw new TypeError( + `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` + ) + } + for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { + callbackfn.call(thisArg, value, key, this); + } + } + } + }; + + return Object.defineProperties(object.prototype, { + ...properties, + [Symbol.iterator]: { + writable: true, + enumerable: false, + configurable: true, + value: properties.entries.value + } + }) + } + + /** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ + async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody; + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError; + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader; + + try { + reader = body.stream.getReader(); + } catch (e) { + errorSteps(e); + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + successSteps(await readAllBytes(reader)); + } catch (e) { + errorSteps(e); + } + } + + function isReadableStreamLike (stream) { + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) + } + + /** + * @param {ReadableStreamController} controller + */ + function readableStreamClose (controller) { + try { + controller.close(); + controller.byobRequest?.respond(0); + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { + throw err + } + } + } + + const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/; // eslint-disable-line + + /** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ + function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + assert(!invalidIsomorphicEncodeValueRegex.test(input)); + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input + } + + /** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ + async function readAllBytes (reader) { + const bytes = []; + let byteLength = 0; + + while (true) { + const { done, value: chunk } = await reader.read(); + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk); + byteLength += chunk.length; + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } + } + + /** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ + function urlIsLocal (url) { + assert('protocol' in url); // ensure it's a url object + + const protocol = url.protocol; + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' + } + + /** + * @param {string|URL} url + * @returns {boolean} + */ + function urlHasHttpsScheme (url) { + return ( + ( + typeof url === 'string' && + url[5] === ':' && + url[0] === 'h' && + url[1] === 't' && + url[2] === 't' && + url[3] === 'p' && + url[4] === 's' + ) || + url.protocol === 'https:' + ) + } + + /** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ + function urlIsHttpHttpsScheme (url) { + assert('protocol' in url); // ensure it's a url object + + const protocol = url.protocol; + + return protocol === 'http:' || protocol === 'https:' + } + + /** + * @see https://fetch.spec.whatwg.org/#simple-range-header-value + * @param {string} value + * @param {boolean} allowWhitespace + */ + function simpleRangeHeaderValue (value, allowWhitespace) { + // 1. Let data be the isomorphic decoding of value. + // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, + // nothing more. We obviously don't need to do that if value is a string already. + const data = value; + + // 2. If data does not start with "bytes", then return failure. + if (!data.startsWith('bytes')) { + return 'failure' + } + + // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. + const position = { position: 5 }; + + // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ); + } + + // 5. If the code point at position within data is not U+003D (=), then return failure. + if (data.charCodeAt(position.position) !== 0x3D) { + return 'failure' + } + + // 6. Advance position by 1. + position.position++; + + // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from + // data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ); + } + + // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, + // from data given position. + const rangeStart = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0); + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ); + + // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the + // empty string; otherwise null. + const rangeStartValue = rangeStart.length ? Number(rangeStart) : null; + + // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, + // from data given position. + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ); + } + + // 11. If the code point at position within data is not U+002D (-), then return failure. + if (data.charCodeAt(position.position) !== 0x2D) { + return 'failure' + } + + // 12. Advance position by 1. + position.position++; + + // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab + // or space, from data given position. + // Note from Khafra: its the same step as in #8 again lol + if (allowWhitespace) { + collectASequenceOfCodePoints( + (char) => char === '\t' || char === ' ', + data, + position + ); + } + + // 14. Let rangeEnd be the result of collecting a sequence of code points that are + // ASCII digits, from data given position. + // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 + const rangeEnd = collectASequenceOfCodePoints( + (char) => { + const code = char.charCodeAt(0); + + return code >= 0x30 && code <= 0x39 + }, + data, + position + ); + + // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd + // is not the empty string; otherwise null. + // Note from Khafra: THE SAME STEP, AGAIN!!! + // Note: why interpret as a decimal if we only collect ascii digits? + const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null; + + // 16. If position is not past the end of data, then return failure. + if (position.position < data.length) { + return 'failure' + } + + // 17. If rangeEndValue and rangeStartValue are null, then return failure. + if (rangeEndValue === null && rangeStartValue === null) { + return 'failure' + } + + // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is + // greater than rangeEndValue, then return failure. + // Note: ... when can they not be numbers? + if (rangeStartValue > rangeEndValue) { + return 'failure' + } + + // 19. Return (rangeStartValue, rangeEndValue). + return { rangeStartValue, rangeEndValue } + } + + /** + * @see https://fetch.spec.whatwg.org/#build-a-content-range + * @param {number} rangeStart + * @param {number} rangeEnd + * @param {number} fullLength + */ + function buildContentRange (rangeStart, rangeEnd, fullLength) { + // 1. Let contentRange be `bytes `. + let contentRange = 'bytes '; + + // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. + contentRange += isomorphicEncode(`${rangeStart}`); + + // 3. Append 0x2D (-) to contentRange. + contentRange += '-'; + + // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${rangeEnd}`); + + // 5. Append 0x2F (/) to contentRange. + contentRange += '/'; + + // 6. Append fullLength, serialized and isomorphic encoded to contentRange. + contentRange += isomorphicEncode(`${fullLength}`); + + // 7. Return contentRange. + return contentRange + } + + // A Stream, which pipes the response to zlib.createInflate() or + // zlib.createInflateRaw() depending on the first byte of the Buffer. + // If the lower byte of the first byte is 0x08, then the stream is + // interpreted as a zlib stream, otherwise it's interpreted as a + // raw deflate stream. + class InflateStream extends Transform { + #zlibOptions + + /** @param {zlib.ZlibOptions} [zlibOptions] */ + constructor (zlibOptions) { + super(); + this.#zlibOptions = zlibOptions; + } + + _transform (chunk, encoding, callback) { + if (!this._inflateStream) { + if (chunk.length === 0) { + callback(); + return + } + this._inflateStream = (chunk[0] & 0x0F) === 0x08 + ? zlib.createInflate(this.#zlibOptions) + : zlib.createInflateRaw(this.#zlibOptions); + + this._inflateStream.on('data', this.push.bind(this)); + this._inflateStream.on('end', () => this.push(null)); + this._inflateStream.on('error', (err) => this.destroy(err)); + } + + this._inflateStream.write(chunk, encoding, callback); + } + + _final (callback) { + if (this._inflateStream) { + this._inflateStream.end(); + this._inflateStream = null; + } + callback(); + } + } + + /** + * @param {zlib.ZlibOptions} [zlibOptions] + * @returns {InflateStream} + */ + function createInflate (zlibOptions) { + return new InflateStream(zlibOptions) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type + * @param {import('./headers').HeadersList} headers + */ + function extractMimeType (headers) { + // 1. Let charset be null. + let charset = null; + + // 2. Let essence be null. + let essence = null; + + // 3. Let mimeType be null. + let mimeType = null; + + // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. + const values = getDecodeSplit('content-type', headers); + + // 5. If values is null, then return failure. + if (values === null) { + return 'failure' + } + + // 6. For each value of values: + for (const value of values) { + // 6.1. Let temporaryMimeType be the result of parsing value. + const temporaryMimeType = parseMIMEType(value); + + // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. + if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { + continue + } + + // 6.3. Set mimeType to temporaryMimeType. + mimeType = temporaryMimeType; + + // 6.4. If mimeType’s essence is not essence, then: + if (mimeType.essence !== essence) { + // 6.4.1. Set charset to null. + charset = null; + + // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to + // mimeType’s parameters["charset"]. + if (mimeType.parameters.has('charset')) { + charset = mimeType.parameters.get('charset'); + } + + // 6.4.3. Set essence to mimeType’s essence. + essence = mimeType.essence; + } else if (!mimeType.parameters.has('charset') && charset !== null) { + // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and + // charset is non-null, set mimeType’s parameters["charset"] to charset. + mimeType.parameters.set('charset', charset); + } + } + + // 7. If mimeType is null, then return failure. + if (mimeType == null) { + return 'failure' + } + + // 8. Return mimeType. + return mimeType + } + + /** + * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split + * @param {string|null} value + */ + function gettingDecodingSplitting (value) { + // 1. Let input be the result of isomorphic decoding value. + const input = value; + + // 2. Let position be a position variable for input, initially pointing at the start of input. + const position = { position: 0 }; + + // 3. Let values be a list of strings, initially empty. + const values = []; + + // 4. Let temporaryValue be the empty string. + let temporaryValue = ''; + + // 5. While position is not past the end of input: + while (position.position < input.length) { + // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") + // or U+002C (,) from input, given position, to temporaryValue. + temporaryValue += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== ',', + input, + position + ); + + // 5.2. If position is not past the end of input, then: + if (position.position < input.length) { + // 5.2.1. If the code point at position within input is U+0022 ("), then: + if (input.charCodeAt(position.position) === 0x22) { + // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. + temporaryValue += collectAnHTTPQuotedString( + input, + position + ); + + // 5.2.1.2. If position is not past the end of input, then continue. + if (position.position < input.length) { + continue + } + } else { + // 5.2.2. Otherwise: + + // 5.2.2.1. Assert: the code point at position within input is U+002C (,). + assert(input.charCodeAt(position.position) === 0x2C); + + // 5.2.2.2. Advance position by 1. + position.position++; + } + } + + // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. + temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20); + + // 5.4. Append temporaryValue to values. + values.push(temporaryValue); + + // 5.6. Set temporaryValue to the empty string. + temporaryValue = ''; + } + + // 6. Return values. + return values + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split + * @param {string} name lowercase header name + * @param {import('./headers').HeadersList} list + */ + function getDecodeSplit (name, list) { + // 1. Let value be the result of getting name from list. + const value = list.get(name, true); + + // 2. If value is null, then return null. + if (value === null) { + return null + } + + // 3. Return the result of getting, decoding, and splitting value. + return gettingDecodingSplitting(value) + } + + const textDecoder = new TextDecoder(); + + /** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ + function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3); + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer); + + // 4. Return output. + return output + } + + class EnvironmentSettingsObjectBase { + get baseUrl () { + return getGlobalOrigin() + } + + get origin () { + return this.baseUrl?.origin + } + + policyContainer = makePolicyContainer() + } + + class EnvironmentSettingsObject { + settingsObject = new EnvironmentSettingsObjectBase() + } + + const environmentSettingsObject = new EnvironmentSettingsObject(); + + util$8 = { + isAborted, + isCancelled, + isValidEncodedURL, + createDeferredPromise, + ReadableStreamFrom, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + clampAndCoarsenConnectionTimingInfo, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + iteratorMixin, + createIterator, + isValidHeaderName, + isValidHeaderValue, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + simpleRangeHeaderValue, + buildContentRange, + parseMetadata, + createInflate, + extractMimeType, + getDecodeSplit, + utf8DecodeBytes, + environmentSettingsObject + }; + return util$8; +} + +var symbols$3; +var hasRequiredSymbols$3; + +function requireSymbols$3 () { + if (hasRequiredSymbols$3) return symbols$3; + hasRequiredSymbols$3 = 1; + + symbols$3 = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kDispatcher: Symbol('dispatcher') + }; + return symbols$3; +} + +var file; +var hasRequiredFile; + +function requireFile () { + if (hasRequiredFile) return file; + hasRequiredFile = 1; + + const { Blob, File } = require$$0$3; + const { kState } = requireSymbols$3(); + const { webidl } = requireWebidl(); + + // TODO(@KhafraDev): remove + class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName; + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type; + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now(); + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + }; + } + + stream (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike); + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike); + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } + } + + webidl.converters.Blob = webidl.interfaceConverter(Blob); + + // If this function is moved to ./util.js, some tools (such as + // rollup) will warn about circular dependencies. See: + // https://github.com/nodejs/undici/issues/1629 + function isFileLike (object) { + return ( + (object instanceof File) || + ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) + } + + file = { FileLike, isFileLike }; + return file; +} + +var formdata; +var hasRequiredFormdata; + +function requireFormdata () { + if (hasRequiredFormdata) return formdata; + hasRequiredFormdata = 1; + + const { isBlobLike, iteratorMixin } = requireUtil$8(); + const { kState } = requireSymbols$3(); + const { kEnumerableProperty } = requireUtil$9(); + const { FileLike, isFileLike } = requireFile(); + const { webidl } = requireWebidl(); + const { File: NativeFile } = require$$0$3; + const nodeUtil = require$$0$7; + + /** @type {globalThis['File']} */ + const File = globalThis.File ?? NativeFile; + + // https://xhr.spec.whatwg.org/#formdata + class FormData { + constructor (form) { + webidl.util.markAsUncloneable(this); + + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = []; + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.append'; + webidl.argumentLengthCheck(arguments, 2, prefix); + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name, prefix, 'name'); + value = isBlobLike(value) + ? webidl.converters.Blob(value, prefix, 'value', { strict: false }) + : webidl.converters.USVString(value, prefix, 'value'); + filename = arguments.length === 3 + ? webidl.converters.USVString(filename, prefix, 'filename') + : undefined; + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename); + + // 3. Append entry to this’s entry list. + this[kState].push(entry); + } + + delete (name) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.delete'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + name = webidl.converters.USVString(name, prefix, 'name'); + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name); + } + + get (name) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.get'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + name = webidl.converters.USVString(name, prefix, 'name'); + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name); + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.getAll'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + name = webidl.converters.USVString(name, prefix, 'name'); + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.has'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + name = webidl.converters.USVString(name, prefix, 'name'); + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData); + + const prefix = 'FormData.set'; + webidl.argumentLengthCheck(arguments, 2, prefix); + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name, prefix, 'name'); + value = isBlobLike(value) + ? webidl.converters.Blob(value, prefix, 'name', { strict: false }) + : webidl.converters.USVString(value, prefix, 'name'); + filename = arguments.length === 3 + ? webidl.converters.USVString(filename, prefix, 'name') + : undefined; + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename); + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name); + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ]; + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry); + } + } + + [nodeUtil.inspect.custom] (depth, options) { + const state = this[kState].reduce((a, b) => { + if (a[b.name]) { + if (Array.isArray(a[b.name])) { + a[b.name].push(b.value); + } else { + a[b.name] = [a[b.name], b.value]; + } + } else { + a[b.name] = b.value; + } + + return a + }, { __proto__: null }); + + options.depth ??= depth; + options.colors ??= true; + + const output = nodeUtil.formatWithOptions(options, state); + + // remove [Object null prototype] + return `FormData ${output.slice(output.indexOf(']') + 2)}` + } + } + + iteratorMixin('FormData', FormData, kState, 'name', 'value'); + + Object.defineProperties(FormData.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + getAll: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } + }); + + /** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ + function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // Note: This operation was done by the webidl converter USVString. + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') ; else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }); + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + }; + + value = value instanceof NativeFile + ? new File([value], filename, options) + : new FileLike(value, filename, options); + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } + } + + formdata = { FormData, makeEntry }; + return formdata; +} + +var formdataParser; +var hasRequiredFormdataParser; + +function requireFormdataParser () { + if (hasRequiredFormdataParser) return formdataParser; + hasRequiredFormdataParser = 1; + + const { isUSVString, bufferToLowerCasedHeaderName } = requireUtil$9(); + const { utf8DecodeBytes } = requireUtil$8(); + const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = requireDataUrl(); + const { isFileLike } = requireFile(); + const { makeEntry } = requireFormdata(); + const assert = require$$0$4; + const { File: NodeFile } = require$$0$3; + + const File = globalThis.File ?? NodeFile; + + const formDataNameBuffer = Buffer.from('form-data; name="'); + const filenameBuffer = Buffer.from('; filename'); + const dd = Buffer.from('--'); + const ddcrlf = Buffer.from('--\r\n'); + + /** + * @param {string} chars + */ + function isAsciiString (chars) { + for (let i = 0; i < chars.length; ++i) { + if ((chars.charCodeAt(i) & -128) !== 0) { + return false + } + } + return true + } + + /** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary + * @param {string} boundary + */ + function validateBoundary (boundary) { + const length = boundary.length; + + // - its length is greater or equal to 27 and lesser or equal to 70, and + if (length < 27 || length > 70) { + return false + } + + // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or + // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), + // 0x2D (-) or 0x5F (_). + for (let i = 0; i < length; ++i) { + const cp = boundary.charCodeAt(i); + + if (!( + (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x5a) || + (cp >= 0x61 && cp <= 0x7a) || + cp === 0x27 || + cp === 0x2d || + cp === 0x5f + )) { + return false + } + } + + return true + } + + /** + * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser + * @param {Buffer} input + * @param {ReturnType} mimeType + */ + function multipartFormDataParser (input, mimeType) { + // 1. Assert: mimeType’s essence is "multipart/form-data". + assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data'); + + const boundaryString = mimeType.parameters.get('boundary'); + + // 2. If mimeType’s parameters["boundary"] does not exist, return failure. + // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s + // parameters["boundary"]. + if (boundaryString === undefined) { + return 'failure' + } + + const boundary = Buffer.from(`--${boundaryString}`, 'utf8'); + + // 3. Let entry list be an empty entry list. + const entryList = []; + + // 4. Let position be a pointer to a byte in input, initially pointing at + // the first byte. + const position = { position: 0 }; + + // Note: undici addition, allows leading and trailing CRLFs. + while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + position.position += 2; + } + + let trailing = input.length; + + while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { + trailing -= 2; + } + + if (trailing !== input.length) { + input = input.subarray(0, trailing); + } + + // 5. While true: + while (true) { + // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D + // (`--`) followed by boundary, advance position by 2 + the length of + // boundary. Otherwise, return failure. + // Note: boundary is padded with 2 dashes already, no need to add 2. + if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { + position.position += boundary.length; + } else { + return 'failure' + } + + // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A + // (`--` followed by CR LF) followed by the end of input, return entry list. + // Note: a body does NOT need to end with CRLF. It can end with --. + if ( + (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || + (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) + ) { + return entryList + } + + // 5.3. If position does not point to a sequence of bytes starting with 0x0D + // 0x0A (CR LF), return failure. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + return 'failure' + } + + // 5.4. Advance position by 2. (This skips past the newline.) + position.position += 2; + + // 5.5. Let name, filename and contentType be the result of parsing + // multipart/form-data headers on input and position, if the result + // is not failure. Otherwise, return failure. + const result = parseMultipartFormDataHeaders(input, position); + + if (result === 'failure') { + return 'failure' + } + + let { name, filename, contentType, encoding } = result; + + // 5.6. Advance position by 2. (This skips past the empty line that marks + // the end of the headers.) + position.position += 2; + + // 5.7. Let body be the empty byte sequence. + let body; + + // 5.8. Body loop: While position is not past the end of input: + // TODO: the steps here are completely wrong + { + const boundaryIndex = input.indexOf(boundary.subarray(2), position.position); + + if (boundaryIndex === -1) { + return 'failure' + } + + body = input.subarray(position.position, boundaryIndex - 4); + + position.position += body.length; + + // Note: position must be advanced by the body's length before being + // decoded, otherwise the parsing will fail. + if (encoding === 'base64') { + body = Buffer.from(body.toString(), 'base64'); + } + } + + // 5.9. If position does not point to a sequence of bytes starting with + // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. + if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { + return 'failure' + } else { + position.position += 2; + } + + // 5.10. If filename is not null: + let value; + + if (filename !== null) { + // 5.10.1. If contentType is null, set contentType to "text/plain". + contentType ??= 'text/plain'; + + // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. + + // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. + // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. + if (!isAsciiString(contentType)) { + contentType = ''; + } + + // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. + value = new File([body], filename, { type: contentType }); + } else { + // 5.11. Otherwise: + + // 5.11.1. Let value be the UTF-8 decoding without BOM of body. + value = utf8DecodeBytes(Buffer.from(body)); + } + + // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. + assert(isUSVString(name)); + assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value)); + + // 5.13. Create an entry with name and value, and append it to entry list. + entryList.push(makeEntry(name, value, filename)); + } + } + + /** + * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers + * @param {Buffer} input + * @param {{ position: number }} position + */ + function parseMultipartFormDataHeaders (input, position) { + // 1. Let name, filename and contentType be null. + let name = null; + let filename = null; + let contentType = null; + let encoding = null; + + // 2. While true: + while (true) { + // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): + if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { + // 2.1.1. If name is null, return failure. + if (name === null) { + return 'failure' + } + + // 2.1.2. Return name, filename and contentType. + return { name, filename, contentType, encoding } + } + + // 2.2. Let header name be the result of collecting a sequence of bytes that are + // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. + let headerName = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, + input, + position + ); + + // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. + headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20); + + // 2.4. If header name does not match the field-name token production, return failure. + if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { + return 'failure' + } + + // 2.5. If the byte at position is not 0x3A (:), return failure. + if (input[position.position] !== 0x3a) { + return 'failure' + } + + // 2.6. Advance position by 1. + position.position++; + + // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char === 0x20 || char === 0x09, + input, + position + ); + + // 2.8. Byte-lowercase header name and switch on the result: + switch (bufferToLowerCasedHeaderName(headerName)) { + case 'content-disposition': { + // 1. Set name and filename to null. + name = filename = null; + + // 2. If position does not point to a sequence of bytes starting with + // `form-data; name="`, return failure. + if (!bufferStartsWith(input, formDataNameBuffer, position)) { + return 'failure' + } + + // 3. Advance position so it points at the byte after the next 0x22 (") + // byte (the one in the sequence of bytes matched above). + position.position += 17; + + // 4. Set name to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return + // failure. + name = parseMultipartFormDataName(input, position); + + if (name === null) { + return 'failure' + } + + // 5. If position points to a sequence of bytes starting with `; filename="`: + if (bufferStartsWith(input, filenameBuffer, position)) { + // Note: undici also handles filename* + let check = position.position + filenameBuffer.length; + + if (input[check] === 0x2a) { + position.position += 1; + check += 1; + } + + if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // =" + return 'failure' + } + + // 1. Advance position so it points at the byte after the next 0x22 (") byte + // (the one in the sequence of bytes matched above). + position.position += 12; + + // 2. Set filename to the result of parsing a multipart/form-data name given + // input and position, if the result is not failure. Otherwise, return failure. + filename = parseMultipartFormDataName(input, position); + + if (filename === null) { + return 'failure' + } + } + + break + } + case 'content-type': { + // 1. Let header value be the result of collecting a sequence of bytes that are + // not 0x0A (LF) or 0x0D (CR), given position. + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ); + + // 2. Remove any HTTP tab or space bytes from the end of header value. + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20); + + // 3. Set contentType to the isomorphic decoding of header value. + contentType = isomorphicDecode(headerValue); + + break + } + case 'content-transfer-encoding': { + let headerValue = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ); + + headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20); + + encoding = isomorphicDecode(headerValue); + + break + } + default: { + // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. + // (Do nothing with those bytes.) + collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d, + input, + position + ); + } + } + + // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A + // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). + if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { + return 'failure' + } else { + position.position += 2; + } + } + } + + /** + * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name + * @param {Buffer} input + * @param {{ position: number }} position + */ + function parseMultipartFormDataName (input, position) { + // 1. Assert: The byte at (position - 1) is 0x22 ("). + assert(input[position.position - 1] === 0x22); + + // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. + /** @type {string | Buffer} */ + let name = collectASequenceOfBytes( + (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, + input, + position + ); + + // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. + if (input[position.position] !== 0x22) { + return null // name could be 'failure' + } else { + position.position++; + } + + // 4. Replace any occurrence of the following subsequences in name with the given byte: + // - `%0A`: 0x0A (LF) + // - `%0D`: 0x0D (CR) + // - `%22`: 0x22 (") + name = new TextDecoder().decode(name) + .replace(/%0A/ig, '\n') + .replace(/%0D/ig, '\r') + .replace(/%22/g, '"'); + + // 5. Return the UTF-8 decoding without BOM of name. + return name + } + + /** + * @param {(char: number) => boolean} condition + * @param {Buffer} input + * @param {{ position: number }} position + */ + function collectASequenceOfBytes (condition, input, position) { + let start = position.position; + + while (start < input.length && condition(input[start])) { + ++start; + } + + return input.subarray(position.position, (position.position = start)) + } + + /** + * @param {Buffer} buf + * @param {boolean} leading + * @param {boolean} trailing + * @param {(charCode: number) => boolean} predicate + * @returns {Buffer} + */ + function removeChars (buf, leading, trailing, predicate) { + let lead = 0; + let trail = buf.length - 1; + + if (leading) { + while (lead < buf.length && predicate(buf[lead])) lead++; + } + + { + while (trail > 0 && predicate(buf[trail])) trail--; + } + + return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) + } + + /** + * Checks if {@param buffer} starts with {@param start} + * @param {Buffer} buffer + * @param {Buffer} start + * @param {{ position: number }} position + */ + function bufferStartsWith (buffer, start, position) { + if (buffer.length < start.length) { + return false + } + + for (let i = 0; i < start.length; i++) { + if (start[i] !== buffer[position.position + i]) { + return false + } + } + + return true + } + + formdataParser = { + multipartFormDataParser, + validateBoundary + }; + return formdataParser; +} + +var body; +var hasRequiredBody; + +function requireBody () { + if (hasRequiredBody) return body; + hasRequiredBody = 1; + + const util = requireUtil$9(); + const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody, + extractMimeType, + utf8DecodeBytes + } = requireUtil$8(); + const { FormData } = requireFormdata(); + const { kState } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { Blob } = require$$0$3; + const assert = require$$0$4; + const { isErrored, isDisturbed } = require$$0$5; + const { isArrayBuffer } = require$$8$1; + const { serializeAMimeType } = requireDataUrl(); + const { multipartFormDataParser } = requireFormdataParser(); + let random; + + try { + const crypto = require('node:crypto'); + random = (max) => crypto.randomInt(0, max); + } catch { + random = (max) => Math.floor(Math.random(max)); + } + + const textEncoder = new TextEncoder(); + function noop () {} + + const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0; + let streamRegistry; + + if (hasFinalizationRegistry) { + streamRegistry = new FinalizationRegistry((weakRef) => { + const stream = weakRef.deref(); + if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { + stream.cancel('Response object has been garbage collected').catch(noop); + } + }); + } + + // https://fetch.spec.whatwg.org/#concept-bodyinit-extract + function extractBody (object, keepalive = false) { + // 1. Let stream be null. + let stream = null; + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object; + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream(); + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream with byte reading support. + stream = new ReadableStream({ + async pull (controller) { + const buffer = typeof source === 'string' ? textEncoder.encode(source) : source; + + if (buffer.byteLength) { + controller.enqueue(buffer); + } + + queueMicrotask(() => readableStreamClose(controller)); + }, + start () {}, + type: 'bytes' + }); + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)); + + // 6. Let action be null. + let action = null; + + // 7. Let source be null. + let source = null; + + // 8. Let length be null. + let length = null; + + // 9. Let type be null. + let type = null; + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object; + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8'; + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString(); + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()); + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)); + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`; + const prefix = `--${boundary}\r\nContent-Disposition: form-data`; + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22'); + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n'); + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = []; + const rn = new Uint8Array([13, 10]); // '\r\n' + length = 0; + let hasUnknownSizeValue = false; + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`); + blobParts.push(chunk); + length += chunk.byteLength; + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`); + blobParts.push(chunk, value, rn); + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength; + } else { + hasUnknownSizeValue = true; + } + } + } + + // CRLF is appended to the body to function with legacy servers and match other implementations. + // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 + // https://github.com/form-data/form-data/issues/63 + const chunk = textEncoder.encode(`--${boundary}--\r\n`); + blobParts.push(chunk); + length += chunk.byteLength; + if (hasUnknownSizeValue) { + length = null; + } + + // Set source to object. + source = object; + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream(); + } else { + yield part; + } + } + }; + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = `multipart/form-data; boundary=${boundary}`; + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object; + + // Set length to object’s size. + length = object.size; + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type; + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object); + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source); + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator; + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator](); + }, + async pull (controller) { + const { value, done } = await iterator.next(); + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close(); + controller.byobRequest?.respond(0); + }); + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + const buffer = new Uint8Array(value); + if (buffer.byteLength) { + controller.enqueue(buffer); + } + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return(); + }, + type: 'bytes' + }); + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length }; + + // 14. Return (body, type). + return [body, type] + } + + // https://fetch.spec.whatwg.org/#bodyinit-safely-extract + function safelyExtractBody (object, keepalive = false) { + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.'); + // istanbul ignore next + assert(!object.locked, 'The stream is locked.'); + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) + } + + function cloneBody (instance, body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee(); + + // 2. Set body’s stream to out1. + body.stream = out1; + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: out2, + length: body.length, + source: body.source + } + } + + function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } + } + + function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return consumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this); + + if (mimeType === null) { + mimeType = ''; + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType); + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return consumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return consumeBody(this, parseJSONFromBytes, instance) + }, + + formData () { + // The formData() method steps are to return the result of running + // consume body with this and the following step given a byte sequence bytes: + return consumeBody(this, (value) => { + // 1. Let mimeType be the result of get the MIME type with this. + const mimeType = bodyMimeType(this); + + // 2. If mimeType is non-null, then switch on mimeType’s essence and run + // the corresponding steps: + if (mimeType !== null) { + switch (mimeType.essence) { + case 'multipart/form-data': { + // 1. ... [long step] + const parsed = multipartFormDataParser(value, mimeType); + + // 2. If that fails for some reason, then throw a TypeError. + if (parsed === 'failure') { + throw new TypeError('Failed to parse body as FormData.') + } + + // 3. Return a new FormData object, appending each entry, + // resulting from the parsing operation, to its entry list. + const fd = new FormData(); + fd[kState] = parsed; + + return fd + } + case 'application/x-www-form-urlencoded': { + // 1. Let entries be the result of parsing bytes. + const entries = new URLSearchParams(value.toString()); + + // 2. If entries is failure, then throw a TypeError. + + // 3. Return a new FormData object whose entry list is entries. + const fd = new FormData(); + + for (const [name, value] of entries) { + fd.append(name, value); + } + + return fd + } + } + } + + // 3. Throw a TypeError. + throw new TypeError( + 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' + ) + }, instance) + }, + + bytes () { + // The bytes() method steps are to return the result of running consume body + // with this and the following step given a byte sequence bytes: return the + // result of creating a Uint8Array from bytes in this’s relevant realm. + return consumeBody(this, (bytes) => { + return new Uint8Array(bytes) + }, instance) + } + }; + + return methods + } + + function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)); + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ + async function consumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance); + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object)) { + throw new TypeError('Body is unusable: Body has already been read') + } + + throwIfAborted(object[kState]); + + // 2. Let promise be a new promise. + const promise = createDeferredPromise(); + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error); + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)); + } catch (e) { + errorSteps(e); + } + }; + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(Buffer.allocUnsafe(0)); + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps); + + // 7. Return promise. + return promise.promise + } + + // https://fetch.spec.whatwg.org/#body-unusable + function bodyUnusable (object) { + const body = object[kState].body; + + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) + } + + /** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ + function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} requestOrResponse + */ + function bodyMimeType (requestOrResponse) { + // 1. Let headers be null. + // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. + // 3. Otherwise, set headers to requestOrResponse’s response’s header list. + /** @type {import('./headers').HeadersList} */ + const headers = requestOrResponse[kState].headersList; + + // 4. Let mimeType be the result of extracting a MIME type from headers. + const mimeType = extractMimeType(headers); + + // 5. If mimeType is failure, then return null. + if (mimeType === 'failure') { + return null + } + + // 6. Return mimeType. + return mimeType + } + + body = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody, + streamRegistry, + hasFinalizationRegistry, + bodyUnusable + }; + return body; +} + +var clientH1; +var hasRequiredClientH1; + +function requireClientH1 () { + if (hasRequiredClientH1) return clientH1; + hasRequiredClientH1 = 1; + + /* global WebAssembly */ + + const assert = require$$0$4; + const util = requireUtil$9(); + const { channels } = requireDiagnostics(); + const timers = requireTimers(); + const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError + } = requireErrors(); + const { + kUrl, + kReset, + kClient, + kParser, + kBlocking, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kMaxRequests, + kCounter, + kMaxResponseSize, + kOnError, + kResume, + kHTTPContext + } = requireSymbols$4(); + + const constants = requireConstants$3(); + const EMPTY_BUF = Buffer.alloc(0); + const FastBuffer = Buffer[Symbol.species]; + const addListener = util.addListener; + const removeAllListeners = util.removeAllListeners; + const kIdleSocketValidation = Symbol('kIdleSocketValidation'); + const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout'); + const kSocketUsed = Symbol('kSocketUsed'); + + let extractBody; + + async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? requireLlhttpWasm() : undefined; + + let mod; + try { + mod = await WebAssembly.compile(requireLlhttp_simdWasm()); + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(llhttpWasmData || requireLlhttpWasm()); + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert(currentParser.ptr === p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert(currentParser.ptr === p); + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert(currentParser.ptr === p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert(currentParser.ptr === p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert(currentParser.ptr === p); + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert(currentParser.ptr === p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert(currentParser.ptr === p); + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) + } + + let llhttpInstance = null; + let llhttpPromise = lazyllhttp(); + llhttpPromise.catch(); + + let currentParser = null; + let currentBufferRef = null; + let currentBufferSize = 0; + let currentBufferPtr = null; + + const USE_NATIVE_TIMER = 0; + const USE_FAST_TIMER = 1; + + // Use fast timers for headers and body to take eventual event loop + // latency into account. + const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER; + const TIMEOUT_BODY = 4 | USE_FAST_TIMER; + + // Use native timers to ignore event loop latency for keep-alive + // handling. + const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER; + + class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0); + + this.llhttp = exports; + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE); + this.client = client; + this.socket = socket; + this.timeout = null; + this.timeoutValue = null; + this.timeoutType = null; + this.statusCode = null; + this.statusText = ''; + this.upgrade = false; + this.headers = []; + this.headersSize = 0; + this.headersMaxSize = client[kMaxHeadersSize]; + this.shouldKeepAlive = false; + this.paused = false; + this.resume = this.resume.bind(this); + + this.bytesRead = 0; + + this.keepAlive = ''; + this.contentLength = ''; + this.connection = ''; + this.maxResponseSize = client[kMaxResponseSize]; + } + + setTimeout (delay, type) { + // If the existing timer and the new timer are of different timer type + // (fast or native) or have different delay, we need to clear the existing + // timer and set a new one. + if ( + delay !== this.timeoutValue || + (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) + ) { + // If a timeout is already set, clear it with clearTimeout of the fast + // timer implementation, as it can clear fast and native timers. + if (this.timeout) { + timers.clearTimeout(this.timeout); + this.timeout = null; + } + + if (delay) { + if (type & USE_FAST_TIMER) { + this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)); + } else { + this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)); + this.timeout.unref(); + } + } + + this.timeoutValue = delay; + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + this.timeoutType = type; + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null); + assert(currentParser == null); + + this.llhttp.llhttp_resume(this.ptr); + + assert(this.timeoutType === TIMEOUT_BODY); + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + this.paused = false; + this.execute(this.socket.read() || EMPTY_BUF); // Flush parser. + this.readMore(); + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read(); + if (chunk === null) { + break + } + this.execute(chunk); + } + } + + execute (data) { + assert(this.ptr != null); + assert(currentParser == null); + assert(!this.paused); + + const { socket, llhttp } = this; + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr); + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096; + currentBufferPtr = llhttp.malloc(currentBufferSize); + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data); + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret; + + try { + currentBufferRef = data; + currentParser = this; + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length); + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null; + currentBufferRef = null; + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; + + if (ret !== constants.ERROR.OK) { + const body = data.subarray(offset); + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(body); + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true; + socket.unshift(body); + } else { + throw this.createError(ret, body) + } + } + } catch (err) { + util.destroy(socket, err); + } + } + + finish () { + assert(currentParser === null); + assert(this.ptr != null); + assert(!this.paused); + + const { llhttp } = this; + + let ret; + + try { + currentParser = this; + ret = llhttp.llhttp_finish(this.ptr); + } finally { + currentParser = null; + } + + if (ret === constants.ERROR.OK) { + return null + } + + if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) { + this.paused = true; + return null + } + + return this.createError(ret, EMPTY_BUF) + } + + createError (ret, data) { + const { llhttp, contentLength, bytesRead } = this; + + if (contentLength && bytesRead !== parseInt(contentLength, 10)) { + return new ResponseContentLengthMismatchError() + } + + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ''; + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')'; + } + + return new HTTPParserError(message, constants.ERROR[ret], data) + } + + destroy () { + assert(this.ptr != null); + assert(currentParser == null); + + this.llhttp.llhttp_free(this.ptr); + this.ptr = null; + + this.timeout && timers.clearTimeout(this.timeout); + this.timeout = null; + this.timeoutValue = null; + this.timeoutType = null; + + this.paused = false; + } + + onStatus (buf) { + this.statusText = buf.toString(); + } + + onMessageBegin () { + const { socket, client } = this; + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + if (client[kRunning] === 0) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))); + return -1 + } + + const request = client[kQueue][client[kRunningIdx]]; + if (!request) { + return -1 + } + request.onResponseStarted(); + } + + onHeaderField (buf) { + const len = this.headers.length; + + if ((len & 1) === 0) { + this.headers.push(buf); + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]); + } + + this.trackHeader(buf.length); + } + + onHeaderValue (buf) { + let len = this.headers.length; + + if ((len & 1) === 1) { + this.headers.push(buf); + len += 1; + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]); + } + + const key = this.headers[len - 2]; + if (key.length === 10) { + const headerName = util.bufferToLowerCasedHeaderName(key); + if (headerName === 'keep-alive') { + this.keepAlive += buf.toString(); + } else if (headerName === 'connection') { + this.connection += buf.toString(); + } + } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { + this.contentLength += buf.toString(); + } + + this.trackHeader(buf.length); + } + + trackHeader (len) { + this.headersSize += len; + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()); + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this; + + assert(upgrade); + assert(client[kSocket] === socket); + assert(!socket.destroyed); + assert(!this.paused); + assert((headers.length & 1) === 0); + + const request = client[kQueue][client[kRunningIdx]]; + assert(request); + assert(request.upgrade || request.method === 'CONNECT'); + + this.statusCode = null; + this.statusText = ''; + this.shouldKeepAlive = null; + + this.headers = []; + this.headersSize = 0; + + socket.unshift(head); + + socket[kParser].destroy(); + socket[kParser] = null; + + socket[kClient] = null; + socket[kError] = null; + + removeAllListeners(socket); + + client[kSocket] = null; + client[kHTTPContext] = null; // TODO (fix): This is hacky... + client[kQueue][client[kRunningIdx]++] = null; + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')); + + try { + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util.destroy(socket, err); + } + + client[kResume](); + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this; + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + if (client[kRunning] === 0) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))); + return -1 + } + + const request = client[kQueue][client[kRunningIdx]]; + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade); + assert(this.statusCode < 200); + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))); + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))); + return -1 + } + + assert(this.timeoutType === TIMEOUT_HEADERS); + + this.statusCode = statusCode; + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ); + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout]; + this.setTimeout(bodyTimeout, TIMEOUT_BODY); + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1); + this.upgrade = true; + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1); + this.upgrade = true; + return 2 + } + + assert((this.headers.length & 1) === 0); + this.headers = []; + this.headersSize = 0; + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null; + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ); + if (timeout <= 0) { + socket[kReset] = true; + } else { + client[kKeepAliveTimeoutValue] = timeout; + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]; + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true; + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false; + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false; + client[kResume](); + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this; + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]]; + assert(request); + + assert(this.timeoutType === TIMEOUT_BODY); + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + assert(statusCode >= 200); + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()); + return -1 + } + + this.bytesRead += buf.length; + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this; + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + assert(statusCode >= 100); + assert((this.headers.length & 1) === 0); + + const request = client[kQueue][client[kRunningIdx]]; + assert(request); + + this.statusCode = null; + this.statusText = ''; + this.bytesRead = 0; + this.contentLength = ''; + this.keepAlive = ''; + this.connection = ''; + + this.headers = []; + this.headersSize = 0; + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()); + return -1 + } + + request.onComplete(headers); + + client[kQueue][client[kRunningIdx]++] = null; + socket[kSocketUsed] = true; + + if (socket[kWriting]) { + assert(client[kRunning] === 0); + // Response completed before request. + util.destroy(socket, new InformationalError('reset')); + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')); + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')); + return constants.ERROR.PAUSED + } else if (client[kPipelining] == null || client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(() => client[kResume]()); + } else { + client[kResume](); + } + } + } + + function onParserTimeout (parser) { + const { socket, timeoutType, client, paused } = parser.deref(); + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!paused, 'cannot be paused while waiting for headers'); + util.destroy(socket, new HeadersTimeoutError()); + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!paused) { + util.destroy(socket, new BodyTimeoutError()); + } + } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]); + util.destroy(socket, new InformationalError('socket idle timeout')); + } + } + + async function connectH1 (client, socket) { + client[kSocket] = socket; + + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise; + llhttpPromise = null; + } + + socket[kNoRef] = false; + socket[kWriting] = false; + socket[kReset] = false; + socket[kBlocking] = false; + socket[kIdleSocketValidation] = 0; + socket[kIdleSocketValidationTimeout] = null; + socket[kSocketUsed] = false; + socket[kParser] = new Parser(client, socket, llhttpInstance); + + addListener(socket, 'error', function (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID'); + + const parser = this[kParser]; + + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + const parserErr = parser.finish(); + if (parserErr) { + this[kError] = parserErr; + this[kClient][kOnError](parserErr); + } + return + } + + this[kError] = err; + + this[kClient][kOnError](err); + }); + addListener(socket, 'readable', function () { + const parser = this[kParser]; + + if (parser) { + parser.readMore(); + } + }); + addListener(socket, 'end', function () { + const parser = this[kParser]; + + if (parser.statusCode && !parser.shouldKeepAlive) { + const parserErr = parser.finish(); + if (parserErr) { + util.destroy(this, parserErr); + } + return + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))); + }); + addListener(socket, 'close', function () { + const client = this[kClient]; + const parser = this[kParser]; + + clearIdleSocketValidation(this); + + if (parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + this[kError] = parser.finish() || this[kError]; + } + + this[kParser].destroy(); + this[kParser] = null; + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)); + + client[kSocket] = null; + client[kHTTPContext] = null; // TODO (fix): This is hacky... + + if (client.destroyed) { + assert(client[kPending] === 0); + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + util.errorRequest(client, request, err); + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]]; + client[kQueue][client[kRunningIdx]++] = null; + + util.errorRequest(client, request, err); + } + + client[kPendingIdx] = client[kRunningIdx]; + + assert(client[kRunning] === 0); + + client.emit('disconnect', client[kUrl], [client], err); + + client[kResume](); + }); + + let closed = false; + socket.on('close', () => { + closed = true; + }); + + return { + version: 'h1', + defaultPipelining: 1, + write (...args) { + return writeH1(client, ...args) + }, + resume () { + resumeH1(client); + }, + destroy (err, callback) { + if (closed) { + queueMicrotask(callback); + } else { + socket.destroy(err).on('close', callback); + } + }, + get destroyed () { + return socket.destroyed + }, + busy (request) { + if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { + return true + } + + if (request) { + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return true + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return true + } + } + + return false + } + } + } + + function clearIdleSocketValidation (socket) { + if (socket[kIdleSocketValidationTimeout]) { + clearTimeout(socket[kIdleSocketValidationTimeout]); + socket[kIdleSocketValidationTimeout] = null; + } + + socket[kIdleSocketValidation] = 0; + } + + function scheduleIdleSocketValidation (client, socket) { + socket[kIdleSocketValidation] = 1; + socket[kIdleSocketValidationTimeout] = setTimeout(() => { + socket[kIdleSocketValidationTimeout] = null; + socket[kIdleSocketValidation] = 2; + + if (client[kSocket] === socket && !socket.destroyed) { + client[kResume](); + } + }, 0); + socket[kIdleSocketValidationTimeout].unref?.(); + } + + /** + * @param {import('./client.js')} client + */ + function resumeH1 (client) { + const socket = client[kSocket]; + + if (socket && !socket.destroyed) { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref(); + socket[kNoRef] = true; + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref(); + socket[kNoRef] = false; + } + + if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { + if (socket[kIdleSocketValidation] === 0) { + scheduleIdleSocketValidation(client, socket); + socket[kParser].readMore(); + if (socket.destroyed) { + return + } + return + } + + if (socket[kIdleSocketValidation] === 1) { + socket[kParser].readMore(); + if (socket.destroyed) { + return + } + return + } + } + + if (client[kRunning] === 0) { + socket[kParser].readMore(); + if (socket.destroyed) { + return + } + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]]; + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout]; + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS); + } + } + } + } + + // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 + function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' + } + + function writeH1 (client, request) { + const { method, path, host, upgrade, blocking, reset } = request; + + let { body, headers, contentLength } = request; + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' || + method === 'QUERY' || + method === 'PROPFIND' || + method === 'PROPPATCH' + ); + + if (util.isFormDataLike(body)) { + if (!extractBody) { + extractBody = requireBody().extractBody; + } + + const [bodyStream, contentType] = extractBody(body); + if (request.contentType == null) { + headers.push('content-type', contentType); + } + body = bodyStream.stream; + contentLength = bodyStream.length; + } else if (util.isBlobLike(body) && request.contentType == null && body.type) { + headers.push('content-type', body.type); + } + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0); + } + + const bodyLength = util.bodyLength(body); + + contentLength = bodyLength ?? contentLength; + + if (contentLength === null) { + contentLength = request.contentLength; + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null; + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()); + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()); + } + + const socket = client[kSocket]; + clearIdleSocketValidation(socket); + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + util.errorRequest(client, request, err || new RequestAbortedError()); + + util.destroy(body); + util.destroy(socket, new InformationalError('aborted')); + }; + + try { + request.onConnect(abort); + } catch (err) { + util.errorRequest(client, request, err); + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true; + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true; + } + + if (reset != null) { + socket[kReset] = reset; + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true; + } + + if (blocking) { + socket[kBlocking] = true; + } + + let header = `${method} ${path} HTTP/1.1\r\n`; + + if (typeof host === 'string') { + header += `host: ${host}\r\n`; + } else { + header += client[kHostHeader]; + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`; + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n'; + } else { + header += 'connection: close\r\n'; + } + + if (Array.isArray(headers)) { + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0]; + const val = headers[n + 1]; + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + header += `${key}: ${val[i]}\r\n`; + } + } else { + header += `${key}: ${val}\r\n`; + } + } + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }); + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload); + } else if (util.isBuffer(body)) { + writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload); + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload); + } else { + writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload); + } + } else if (util.isStream(body)) { + writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload); + } else if (util.isIterable(body)) { + writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload); + } else { + assert(false); + } + + return true + } + + function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined'); + + let finished = false; + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }); + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause(); + } + } catch (err) { + util.destroy(this, err); + } + }; + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume(); + } + }; + const onClose = function () { + // 'close' might be emitted *before* 'error' for + // broken streams. Wait a tick to avoid this case. + queueMicrotask(() => { + // It's only safe to remove 'error' listener after + // 'close'. + body.removeListener('error', onFinished); + }); + + if (!finished) { + const err = new RequestAbortedError(); + queueMicrotask(() => onFinished(err)); + } + }; + const onFinished = function (err) { + if (finished) { + return + } + + finished = true; + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)); + + socket + .off('drain', onDrain) + .off('error', onFinished); + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('close', onClose); + + if (!err) { + try { + writer.end(); + } catch (er) { + err = er; + } + } + + writer.destroy(err); + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err); + } else { + util.destroy(body); + } + }; + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onClose); + + if (body.resume) { + body.resume(); + } + + socket + .on('drain', onDrain) + .on('error', onFinished); + + if (body.errorEmitted ?? body.errored) { + setImmediate(() => onFinished(body.errored)); + } else if (body.endEmitted ?? body.readableEnded) { + setImmediate(() => onFinished(null)); + } + + if (body.closeEmitted ?? body.closed) { + setImmediate(onClose); + } + } + + function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { + try { + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1'); + } else { + assert(contentLength === null, 'no body must not have content length'); + socket.write(`${header}\r\n`, 'latin1'); + } + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length'); + + socket.cork(); + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + socket.write(body); + socket.uncork(); + request.onBodySent(body); + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true; + } + } + request.onRequestSent(); + + client[kResume](); + } catch (err) { + abort(err); + } + } + + async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length'); + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()); + + socket.cork(); + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + socket.write(buffer); + socket.uncork(); + + request.onBodySent(buffer); + request.onRequestSent(); + + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true; + } + + client[kResume](); + } catch (err) { + abort(err); + } + } + + async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined'); + + let callback = null; + function onDrain () { + if (callback) { + const cb = callback; + callback = null; + cb(); + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null); + + if (socket[kError]) { + reject(socket[kError]); + } else { + callback = resolve; + } + }); + + socket + .on('close', onDrain) + .on('drain', onDrain); + + const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }); + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain(); + } + } + + writer.end(); + } catch (err) { + writer.destroy(err); + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain); + } + } + + class AsyncWriter { + constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket; + this.request = request; + this.contentLength = contentLength; + this.client = client; + this.bytesWritten = 0; + this.expectsPayload = expectsPayload; + this.header = header; + this.abort = abort; + + socket[kWriting] = true; + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this; + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk); + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()); + } + + socket.cork(); + + if (bytesWritten === 0) { + if (!expectsPayload && request.reset !== false) { + socket[kReset] = true; + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1'); + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1'); + } + + this.bytesWritten += len; + + const ret = socket.write(chunk); + + socket.uncork(); + + request.onBodySent(chunk); + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh(); + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this; + request.onRequestSent(); + + socket[kWriting] = false; + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1'); + } else { + socket.write(`${header}\r\n`, 'latin1'); + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1'); + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()); + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh(); + } + } + + client[kResume](); + } + + destroy (err) { + const { socket, client, abort } = this; + + socket[kWriting] = false; + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request'); + abort(err); + } + } + } + + clientH1 = connectH1; + return clientH1; +} + +var clientH2; +var hasRequiredClientH2; + +function requireClientH2 () { + if (hasRequiredClientH2) return clientH2; + hasRequiredClientH2 = 1; + + const assert = require$$0$4; + const { pipeline } = require$$0$5; + const util = requireUtil$9(); + const { + RequestContentLengthMismatchError, + RequestAbortedError, + SocketError, + InformationalError + } = requireErrors(); + const { + kUrl, + kReset, + kClient, + kRunning, + kPending, + kQueue, + kPendingIdx, + kRunningIdx, + kError, + kSocket, + kStrictContentLength, + kOnError, + kMaxConcurrentStreams, + kHTTP2Session, + kResume, + kSize, + kHTTPContext + } = requireSymbols$4(); + + const kOpenStreams = Symbol('open streams'); + + let extractBody; + + // Experimental + let h2ExperimentalWarned = false; + + /** @type {import('http2')} */ + let http2; + try { + http2 = require('node:http2'); + } catch { + // @ts-ignore + http2 = { constants: {} }; + } + + const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } + } = http2; + + function parseH2Headers (headers) { + const result = []; + + for (const [name, value] of Object.entries(headers)) { + // h2 may concat the header value by array + // e.g. Set-Cookie + if (Array.isArray(value)) { + for (const subvalue of value) { + // we need to provide each header value of header name + // because the headers handler expect name-value pair + result.push(Buffer.from(name), Buffer.from(subvalue)); + } + } else { + result.push(Buffer.from(name), Buffer.from(value)); + } + } + + return result + } + + async function connectH2 (client, socket) { + client[kSocket] = socket; + + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true; + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }); + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kMaxConcurrentStreams] + }); + + session[kOpenStreams] = 0; + session[kClient] = client; + session[kSocket] = socket; + + util.addListener(session, 'error', onHttp2SessionError); + util.addListener(session, 'frameError', onHttp2FrameError); + util.addListener(session, 'end', onHttp2SessionEnd); + util.addListener(session, 'goaway', onHTTP2GoAway); + util.addListener(session, 'close', function () { + const { [kClient]: client } = this; + const { [kSocket]: socket } = client; + + const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)); + + client[kHTTP2Session] = null; + + if (client.destroyed) { + assert(client[kPending] === 0); + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + util.errorRequest(client, request, err); + } + } + }); + + session.unref(); + + client[kHTTP2Session] = session; + socket[kHTTP2Session] = session; + + util.addListener(socket, 'error', function (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID'); + + this[kError] = err; + + this[kClient][kOnError](err); + }); + + util.addListener(socket, 'end', function () { + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))); + }); + + util.addListener(socket, 'close', function () { + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)); + + client[kSocket] = null; + + if (this[kHTTP2Session] != null) { + this[kHTTP2Session].destroy(err); + } + + client[kPendingIdx] = client[kRunningIdx]; + + assert(client[kRunning] === 0); + + client.emit('disconnect', client[kUrl], [client], err); + + client[kResume](); + }); + + let closed = false; + socket.on('close', () => { + closed = true; + }); + + return { + version: 'h2', + defaultPipelining: Infinity, + write (...args) { + return writeH2(client, ...args) + }, + resume () { + resumeH2(client); + }, + destroy (err, callback) { + if (closed) { + queueMicrotask(callback); + } else { + // Destroying the socket will trigger the session close + socket.destroy(err).on('close', callback); + } + }, + get destroyed () { + return socket.destroyed + }, + busy () { + return false + } + } + } + + function resumeH2 (client) { + const socket = client[kSocket]; + + if (socket?.destroyed === false) { + if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) { + socket.unref(); + client[kHTTP2Session].unref(); + } else { + socket.ref(); + client[kHTTP2Session].ref(); + } + } + } + + function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID'); + + this[kSocket][kError] = err; + this[kClient][kOnError](err); + } + + function onHttp2FrameError (type, code, id) { + if (id === 0) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`); + this[kSocket][kError] = err; + this[kClient][kOnError](err); + } + } + + function onHttp2SessionEnd () { + const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])); + this.destroy(err); + util.destroy(this[kSocket], err); + } + + /** + * This is the root cause of #3011 + * We need to handle GOAWAY frames properly, and trigger the session close + * along with the socket right away + */ + function onHTTP2GoAway (code) { + // We cannot recover, so best to close the session and the socket + const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this)); + const client = this[kClient]; + + client[kSocket] = null; + client[kHTTPContext] = null; + + if (this[kHTTP2Session] != null) { + this[kHTTP2Session].destroy(err); + this[kHTTP2Session] = null; + } + + util.destroy(this[kSocket], err); + + // Fail head of pipeline. + if (client[kRunningIdx] < client[kQueue].length) { + const request = client[kQueue][client[kRunningIdx]]; + client[kQueue][client[kRunningIdx]++] = null; + util.errorRequest(client, request, err); + client[kPendingIdx] = client[kRunningIdx]; + } + + assert(client[kRunning] === 0); + + client.emit('disconnect', client[kUrl], [client], err); + + client[kResume](); + } + + // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 + function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' + } + + function writeH2 (client, request) { + const session = client[kHTTP2Session]; + const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request; + let { body } = request; + + if (upgrade) { + util.errorRequest(client, request, new Error('Upgrade not supported for H2')); + return false + } + + const headers = {}; + for (let n = 0; n < reqHeaders.length; n += 2) { + const key = reqHeaders[n + 0]; + const val = reqHeaders[n + 1]; + + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (headers[key]) { + headers[key] += `,${val[i]}`; + } else { + headers[key] = val[i]; + } + } + } else { + headers[key] = val; + } + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream; + + const { hostname, port } = client[kUrl]; + + headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`; + headers[HTTP2_HEADER_METHOD] = method; + + const abort = (err) => { + if (request.aborted || request.completed) { + return + } + + err = err || new RequestAbortedError(); + + util.errorRequest(client, request, err); + + if (stream != null) { + util.destroy(stream, err); + } + + // We do not destroy the socket as we can continue using the session + // the stream get's destroyed and the session remains to create new streams + util.destroy(body, err); + client[kQueue][client[kRunningIdx]++] = null; + client[kResume](); + }; + + try { + // We are already connected, streams are pending. + // We can call on connect, and wait for abort + request.onConnect(abort); + } catch (err) { + util.errorRequest(client, request, err); + } + + if (request.aborted) { + return false + } + + if (method === 'CONNECT') { + session.ref(); + // We are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }); + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream); + ++session[kOpenStreams]; + client[kQueue][client[kRunningIdx]++] = null; + }); + } + + stream.once('close', () => { + session[kOpenStreams] -= 1; + if (session[kOpenStreams] === 0) session.unref(); + }); + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omitted when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path; + headers[HTTP2_HEADER_SCHEME] = 'https'; + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ); + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0); + } + + let contentLength = util.bodyLength(body); + + if (util.isFormDataLike(body)) { + extractBody ??= requireBody().extractBody; + + const [bodyStream, contentType] = extractBody(body); + headers['content-type'] = contentType; + + body = bodyStream.stream; + contentLength = bodyStream.length; + } + + if (contentLength == null) { + contentLength = request.contentLength; + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null; + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + util.errorRequest(client, request, new RequestContentLengthMismatchError()); + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()); + } + + if (contentLength != null) { + assert(body, 'no body must not have content length'); + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`; + } + + session.ref(); + + const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null; + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue'; + stream = session.request(headers, { endStream: shouldEndStream, signal }); + + stream.once('continue', writeBodyH2); + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }); + writeBodyH2(); + } + + // Increment counter as we have new streams open + ++session[kOpenStreams]; + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers; + request.onResponseStarted(); + + // Due to the stream nature, it is possible we face a race condition + // where the stream has been assigned, but the request has been aborted + // the request remains in-flight and headers hasn't been received yet + // for those scenarios, best effort is to destroy the stream immediately + // as there's no value to keep it open. + if (request.aborted) { + const err = new RequestAbortedError(); + util.errorRequest(client, request, err); + util.destroy(stream, err); + return + } + + if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { + stream.pause(); + } + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause(); + } + }); + }); + + stream.once('end', () => { + // When state is null, it means we haven't consumed body and the stream still do not have + // a state. + // Present specially when using pipeline or stream + if (stream.state?.state == null || stream.state.state < 6) { + request.onComplete([]); + } + + if (session[kOpenStreams] === 0) { + // Stream is closed or half-closed-remote (6), decrement counter and cleanup + // It does not have sense to continue working with the stream as we do not + // have yet RST_STREAM support on client-side + + session.unref(); + } + + abort(new InformationalError('HTTP/2: stream half-closed (remote)')); + client[kQueue][client[kRunningIdx]++] = null; + client[kPendingIdx] = client[kRunningIdx]; + client[kResume](); + }); + + stream.once('close', () => { + session[kOpenStreams] -= 1; + if (session[kOpenStreams] === 0) { + session.unref(); + } + }); + + stream.once('error', function (err) { + abort(err); + }); + + stream.once('frameError', (type, code) => { + abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)); + }); + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Support push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body || contentLength === 0) { + writeBuffer( + abort, + stream, + null, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ); + } else if (util.isBuffer(body)) { + writeBuffer( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ); + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable( + abort, + stream, + body.stream(), + client, + request, + client[kSocket], + contentLength, + expectsPayload + ); + } else { + writeBlob( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ); + } + } else if (util.isStream(body)) { + writeStream( + abort, + client[kSocket], + expectsPayload, + stream, + body, + client, + request, + contentLength + ); + } else if (util.isIterable(body)) { + writeIterable( + abort, + stream, + body, + client, + request, + client[kSocket], + contentLength, + expectsPayload + ); + } else { + assert(false); + } + } + } + + function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + try { + if (body != null && util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length'); + h2stream.cork(); + h2stream.write(body); + h2stream.uncork(); + h2stream.end(); + + request.onBodySent(body); + } + + if (!expectsPayload) { + socket[kReset] = true; + } + + request.onRequestSent(); + client[kResume](); + } catch (error) { + abort(error); + } + } + + function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined'); + + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(pipe, err); + abort(err); + } else { + util.removeAllListeners(pipe); + request.onRequestSent(); + + if (!expectsPayload) { + socket[kReset] = true; + } + + client[kResume](); + } + } + ); + + util.addListener(pipe, 'data', onPipeData); + + function onPipeData (chunk) { + request.onBodySent(chunk); + } + } + + async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength === body.size, 'blob body must have content length'); + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()); + + h2stream.cork(); + h2stream.write(buffer); + h2stream.uncork(); + h2stream.end(); + + request.onBodySent(buffer); + request.onRequestSent(); + + if (!expectsPayload) { + socket[kReset] = true; + } + + client[kResume](); + } catch (err) { + abort(err); + } + } + + async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined'); + + let callback = null; + function onDrain () { + if (callback) { + const cb = callback; + callback = null; + cb(); + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null); + + if (socket[kError]) { + reject(socket[kError]); + } else { + callback = resolve; + } + }); + + h2stream + .on('close', onDrain) + .on('drain', onDrain); + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk); + request.onBodySent(chunk); + if (!res) { + await waitForDrain(); + } + } + + h2stream.end(); + + request.onRequestSent(); + + if (!expectsPayload) { + socket[kReset] = true; + } + + client[kResume](); + } catch (err) { + abort(err); + } finally { + h2stream + .off('close', onDrain) + .off('drain', onDrain); + } + } + + clientH2 = connectH2; + return clientH2; +} + +var redirectHandler; +var hasRequiredRedirectHandler; + +function requireRedirectHandler () { + if (hasRequiredRedirectHandler) return redirectHandler; + hasRequiredRedirectHandler = 1; + + const util = requireUtil$9(); + const { kBodyUsed } = requireSymbols$4(); + const assert = require$$0$4; + const { InvalidArgumentError } = requireErrors(); + const EE = require$$8; + + const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]; + + const kBody = Symbol('body'); + + class BodyAsyncIterable { + constructor (body) { + this[kBody] = body; + this[kBodyUsed] = false; + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed'); + this[kBodyUsed] = true; + yield * this[kBody]; + } + } + + class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade); + + this.dispatch = dispatch; + this.location = null; + this.abort = null; + this.opts = { ...opts, maxRedirections: 0 }; // opts must be a copy + this.maxRedirections = maxRedirections; + this.handler = handler; + this.history = []; + this.redirectionLimitReached = false; + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false); + }); + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false; + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true; + }); + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body); + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body); + } + } + + onConnect (abort) { + this.abort = abort; + this.handler.onConnect(abort, { history: this.history }); + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket); + } + + onError (error) { + this.handler.onError(error); + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers); + + if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { + if (this.request) { + this.request.abort(new Error('max redirects')); + } + + this.redirectionLimitReached = true; + this.abort(new Error('max redirects')); + return + } + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)); + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); + const path = search ? `${pathname}${search}` : pathname; + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); + this.opts.path = path; + this.opts.origin = origin; + this.opts.maxRedirections = 0; + this.opts.query = null; + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET'; + this.opts.body = null; + } + } + + onData (chunk) { + if (this.location) ; else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed information. + */ + + this.location = null; + this.abort = null; + + this.dispatch(this.opts, this); + } else { + this.handler.onComplete(trailers); + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk); + } + } + } + + function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') { + return headers[i + 1] + } + } + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header); + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false + } + + // https://tools.ietf.org/html/rfc7231#section-6.4 + function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = []; + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]); + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]); + } + } + } else { + assert(headers == null, 'headers must be an object or an array'); + } + return ret + } + + redirectHandler = RedirectHandler; + return redirectHandler; +} + +var redirectInterceptor; +var hasRequiredRedirectInterceptor; + +function requireRedirectInterceptor () { + if (hasRequiredRedirectInterceptor) return redirectInterceptor; + hasRequiredRedirectInterceptor = 1; + + const RedirectHandler = requireRedirectHandler(); + + function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts; + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler); + opts = { ...opts, maxRedirections: 0 }; // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } + } + + redirectInterceptor = createRedirectInterceptor; + return redirectInterceptor; +} + +var client; +var hasRequiredClient; + +function requireClient () { + if (hasRequiredClient) return client; + hasRequiredClient = 1; + + const assert = require$$0$4; + const net = require$$0$6; + const http = require$$2$1; + const util = requireUtil$9(); + const { channels } = requireDiagnostics(); + const Request = requireRequest$1(); + const DispatcherBase = requireDispatcherBase(); + const { + InvalidArgumentError, + InformationalError, + ClientDestroyedError + } = requireErrors(); + const buildConnector = requireConnect(); + const { + kUrl, + kServerName, + kClient, + kBusy, + kConnect, + kResuming, + kRunning, + kPending, + kSize, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kOnError, + kHTTPContext, + kMaxConcurrentStreams, + kResume + } = requireSymbols$4(); + const connectH1 = requireClientH1(); + const connectH2 = requireClientH2(); + let deprecatedInterceptorWarned = false; + + const kClosedResolve = Symbol('kClosedResolve'); + + const noop = () => {}; + + function getPipelining (client) { + return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 + } + + /** + * @type {import('../../types/client.js').default} + */ + class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../../types/client.js').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + maxConcurrentStreams, + allowH2, + webSocket + } = {}) { + super({ webSocket }); + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }); + } + + if (interceptors?.Client && Array.isArray(interceptors.Client)) { + this[kInterceptors] = interceptors.Client; + if (!deprecatedInterceptorWarned) { + deprecatedInterceptorWarned = true; + process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { + code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED' + }); + } + } else { + this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })]; + } + + this[kUrl] = util.parseOrigin(url); + this[kConnector] = connect; + this[kPipelining] = pipelining != null ? pipelining : 1; + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize; + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout; + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout; + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold; + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]; + this[kServerName] = null; + this[kLocalAddress] = localAddress != null ? localAddress : null; + this[kResuming] = 0; // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0; // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`; + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3; + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3; + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength; + this[kMaxRedirections] = maxRedirections; + this[kMaxRequests] = maxRequestsPerClient; + this[kClosedResolve] = null; + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1; + this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100; // Max peerConcurrentStreams for a Node h2 server + this[kHTTPContext] = null; + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = []; + this[kRunningIdx] = 0; + this[kPendingIdx] = 0; + + this[kResume] = (sync) => resume(this, sync); + this[kOnError] = (err) => onError(this, err); + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value; + this[kResume](true); + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed + } + + get [kBusy] () { + return Boolean( + this[kHTTPContext]?.busy(null) || + (this[kSize] >= (getPipelining(this) || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this); + this.once('connect', cb); + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin; + const request = new Request(origin, opts, handler); + + this[kQueue].push(request); + if (this[kResuming]) ; else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1; + queueMicrotask(() => resume(this)); + } else { + this[kResume](true); + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2; + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (this[kSize]) { + this[kClosedResolve] = resolve; + } else { + resolve(null); + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + util.errorRequest(this, request, err); + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve](); + this[kClosedResolve] = null; + } + resolve(null); + }; + + if (this[kHTTPContext]) { + this[kHTTPContext].destroy(err, callback); + this[kHTTPContext] = null; + } else { + queueMicrotask(callback); + } + + this[kResume](); + }) + } + } + + const createRedirectInterceptor = requireRedirectInterceptor(); + + function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]); + + const requests = client[kQueue].splice(client[kRunningIdx]); + + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + util.errorRequest(client, request, err); + } + assert(client[kSize] === 0); + } + } + + /** + * @param {Client} client + * @returns + */ + async function connect (client) { + assert(!client[kConnecting]); + assert(!client[kHTTPContext]); + + let { host, hostname, protocol, port } = client[kUrl]; + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']'); + + assert(idx !== -1); + const ip = hostname.substring(1, idx); + + assert(net.isIP(ip)); + hostname = ip; + } + + client[kConnecting] = true; + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }); + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err); + } else { + resolve(socket); + } + }); + }); + + if (client.destroyed) { + util.destroy(socket.on('error', noop), new ClientDestroyedError()); + return + } + + assert(socket); + + try { + client[kHTTPContext] = socket.alpnProtocol === 'h2' + ? await connectH2(client, socket) + : await connectH1(client, socket); + } catch (err) { + socket.destroy().on('error', noop); + throw err + } + + client[kConnecting] = false; + + socket[kCounter] = 0; + socket[kMaxRequests] = client[kMaxRequests]; + socket[kClient] = client; + socket[kError] = null; + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }); + } + client.emit('connect', client[kUrl], [client]); + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false; + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }); + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0); + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++]; + util.errorRequest(client, request, err); + } + } else { + onError(client, err); + } + + client.emit('connectionError', client[kUrl], [client], err); + } + + client[kResume](); + } + + function emitDrain (client) { + client[kNeedDrain] = 0; + client.emit('drain', client[kUrl], [client]); + } + + function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2; + + _resume(client, sync); + client[kResuming] = 0; + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]); + client[kPendingIdx] -= client[kRunningIdx]; + client[kRunningIdx] = 0; + } + } + + function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0); + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve](); + client[kClosedResolve] = null; + return + } + + if (client[kHTTPContext]) { + client[kHTTPContext].resume(); + } + + if (client[kBusy]) { + client[kNeedDrain] = 2; + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1; + queueMicrotask(() => emitDrain(client)); + } else { + emitDrain(client); + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (getPipelining(client) || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]]; + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername; + client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { + client[kHTTPContext] = null; + resume(client); + }); + } + + if (client[kConnecting]) { + return + } + + if (!client[kHTTPContext]) { + connect(client); + return + } + + if (client[kHTTPContext].destroyed) { + return + } + + if (client[kHTTPContext].busy(request)) { + return + } + + if (!request.aborted && client[kHTTPContext].write(request)) { + client[kPendingIdx]++; + } else { + client[kQueue].splice(client[kPendingIdx], 1); + } + } + } + + client = Client; + return client; +} + +/* eslint-disable */ + +var fixedQueue; +var hasRequiredFixedQueue; + +function requireFixedQueue () { + if (hasRequiredFixedQueue) return fixedQueue; + hasRequiredFixedQueue = 1; + + // Extracted from node/lib/internal/fixed_queue.js + + // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. + const kSize = 2048; + const kMask = kSize - 1; + + // The FixedQueue is implemented as a singly-linked list of fixed-size + // circular buffers. It looks something like this: + // + // head tail + // | | + // v v + // +-----------+ <-----\ +-----------+ <------\ +-----------+ + // | [null] | \----- | next | \------- | next | + // +-----------+ +-----------+ +-----------+ + // | item | <-- bottom | item | <-- bottom | [empty] | + // | item | | item | | [empty] | + // | item | | item | | [empty] | + // | item | | item | | [empty] | + // | item | | item | bottom --> | item | + // | item | | item | | item | + // | ... | | ... | | ... | + // | item | | item | | item | + // | item | | item | | item | + // | [empty] | <-- top | item | | item | + // | [empty] | | item | | item | + // | [empty] | | [empty] | <-- top top --> | [empty] | + // +-----------+ +-----------+ +-----------+ + // + // Or, if there is only one circular buffer, it looks something + // like either of these: + // + // head tail head tail + // | | | | + // v v v v + // +-----------+ +-----------+ + // | [null] | | [null] | + // +-----------+ +-----------+ + // | [empty] | | item | + // | [empty] | | item | + // | item | <-- bottom top --> | [empty] | + // | item | | [empty] | + // | [empty] | <-- top bottom --> | item | + // | [empty] | | item | + // +-----------+ +-----------+ + // + // Adding a value means moving `top` forward by one, removing means + // moving `bottom` forward by one. After reaching the end, the queue + // wraps around. + // + // When `top === bottom` the current queue is empty and when + // `top + 1 === bottom` it's full. This wastes a single space of storage + // but allows much quicker checks. + + class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } + } + + fixedQueue = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } + }; + return fixedQueue; +} + +var poolStats; +var hasRequiredPoolStats; + +function requirePoolStats () { + if (hasRequiredPoolStats) return poolStats; + hasRequiredPoolStats = 1; + const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = requireSymbols$4(); + const kPool = Symbol('pool'); + + class PoolStats { + constructor (pool) { + this[kPool] = pool; + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } + } + + poolStats = PoolStats; + return poolStats; +} + +var poolBase; +var hasRequiredPoolBase; + +function requirePoolBase () { + if (hasRequiredPoolBase) return poolBase; + hasRequiredPoolBase = 1; + + const DispatcherBase = requireDispatcherBase(); + const FixedQueue = requireFixedQueue(); + const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = requireSymbols$4(); + const PoolStats = requirePoolStats(); + + const kClients = Symbol('clients'); + const kNeedDrain = Symbol('needDrain'); + const kQueue = Symbol('queue'); + const kClosedResolve = Symbol('closed resolve'); + const kOnDrain = Symbol('onDrain'); + const kOnConnect = Symbol('onConnect'); + const kOnDisconnect = Symbol('onDisconnect'); + const kOnConnectionError = Symbol('onConnectionError'); + const kGetDispatcher = Symbol('get dispatcher'); + const kAddClient = Symbol('add client'); + const kRemoveClient = Symbol('remove client'); + const kStats = Symbol('stats'); + + class PoolBase extends DispatcherBase { + constructor (opts) { + super(opts); + + this[kQueue] = new FixedQueue(); + this[kClients] = []; + this[kQueued] = 0; + + const pool = this; + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue]; + + let needDrain = false; + + while (!needDrain) { + const item = queue.shift(); + if (!item) { + break + } + pool[kQueued]--; + needDrain = !this.dispatch(item.opts, item.handler); + } + + this[kNeedDrain] = needDrain; + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false; + pool.emit('drain', origin, [pool, ...targets]); + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]); + } + }; + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]); + }; + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err); + }; + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err); + }; + + this[kStats] = new PoolStats(this); + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued]; + for (const { [kPending]: pending } of this[kClients]) { + ret += pending; + } + return ret + } + + get [kRunning] () { + let ret = 0; + for (const { [kRunning]: running } of this[kClients]) { + ret += running; + } + return ret + } + + get [kSize] () { + let ret = this[kQueued]; + for (const { [kSize]: size } of this[kClients]) { + ret += size; + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + await Promise.all(this[kClients].map(c => c.close())); + } else { + await new Promise((resolve) => { + this[kClosedResolve] = resolve; + }); + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift(); + if (!item) { + break + } + item.handler.onError(err); + } + + await Promise.all(this[kClients].map(c => c.destroy(err))); + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher](); + + if (!dispatcher) { + this[kNeedDrain] = true; + this[kQueue].push({ opts, handler }); + this[kQueued]++; + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true; + this[kNeedDrain] = !this[kGetDispatcher](); + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]); + + this[kClients].push(client); + + if (this[kNeedDrain]) { + queueMicrotask(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]); + } + }); + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client); + if (idx !== -1) { + this[kClients].splice(idx, 1); + } + }); + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )); + } + } + + poolBase = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher + }; + return poolBase; +} + +var pool; +var hasRequiredPool; + +function requirePool () { + if (hasRequiredPool) return pool; + hasRequiredPool = 1; + + const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher + } = requirePoolBase(); + const Client = requireClient(); + const { + InvalidArgumentError + } = requireErrors(); + const util = requireUtil$9(); + const { kUrl, kInterceptors } = requireSymbols$4(); + const buildConnector = requireConnect(); + + const kOptions = Symbol('options'); + const kConnections = Symbol('connections'); + const kFactory = Symbol('factory'); + + function defaultFactory (origin, opts) { + return new Client(origin, opts) + } + + class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }); + } + + super(options); + + this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : []; + this[kConnections] = connections || null; + this[kUrl] = util.parseOrigin(origin); + this[kOptions] = { ...util.deepClone(options), connect, allowH2 }; + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined; + this[kFactory] = factory; + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target); + if (idx !== -1) { + this[kClients].splice(idx, 1); + } + } + }); + } + + [kGetDispatcher] () { + for (const client of this[kClients]) { + if (!client[kNeedDrain]) { + return client + } + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + const dispatcher = this[kFactory](this[kUrl], this[kOptions]); + this[kAddClient](dispatcher); + return dispatcher + } + } + } + + pool = Pool; + return pool; +} + +var balancedPool; +var hasRequiredBalancedPool; + +function requireBalancedPool () { + if (hasRequiredBalancedPool) return balancedPool; + hasRequiredBalancedPool = 1; + + const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError + } = requireErrors(); + const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher + } = requirePoolBase(); + const Pool = requirePool(); + const { kUrl, kInterceptors } = requireSymbols$4(); + const { parseOrigin } = requireUtil$9(); + const kFactory = Symbol('factory'); + + const kOptions = Symbol('options'); + const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor'); + const kCurrentWeight = Symbol('kCurrentWeight'); + const kIndex = Symbol('kIndex'); + const kWeight = Symbol('kWeight'); + const kMaxWeightPerServer = Symbol('kMaxWeightPerServer'); + const kErrorPenalty = Symbol('kErrorPenalty'); + + /** + * Calculate the greatest common divisor of two numbers by + * using the Euclidean algorithm. + * + * @param {number} a + * @param {number} b + * @returns {number} + */ + function getGreatestCommonDivisor (a, b) { + if (a === 0) return b + + while (b !== 0) { + const t = b; + b = a % b; + a = t; + } + return a + } + + function defaultFactory (origin, opts) { + return new Pool(origin, opts) + } + + class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super(); + + this[kOptions] = opts; + this[kIndex] = -1; + this[kCurrentWeight] = 0; + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100; + this[kErrorPenalty] = this[kOptions].errorPenalty || 15; + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams]; + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : []; + this[kFactory] = factory; + + for (const upstream of upstreams) { + this.addUpstream(upstream); + } + this._updateBalancedPoolStats(); + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin; + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])); + + this[kAddClient](pool); + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]); + }); + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]); + this._updateBalancedPoolStats(); + }); + + pool.on('disconnect', (...args) => { + const err = args[2]; + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]); + this._updateBalancedPoolStats(); + } + }); + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer]; + } + + this._updateBalancedPoolStats(); + + return this + } + + _updateBalancedPoolStats () { + let result = 0; + for (let i = 0; i < this[kClients].length; i++) { + result = getGreatestCommonDivisor(this[kClients][i][kWeight], result); + } + + this[kGreatestCommonDivisor] = result; + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin; + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )); + + if (pool) { + this[kRemoveClient](pool); + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )); + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true); + + if (allClientsBusy) { + return + } + + let counter = 0; + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]); + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length; + const pool = this[kClients][this[kIndex]]; + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex]; + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]; + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer]; + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]; + this[kIndex] = maxWeightIndex; + return this[kClients][maxWeightIndex] + } + } + + balancedPool = BalancedPool; + return balancedPool; +} + +var agent; +var hasRequiredAgent; + +function requireAgent () { + if (hasRequiredAgent) return agent; + hasRequiredAgent = 1; + + const { InvalidArgumentError } = requireErrors(); + const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = requireSymbols$4(); + const DispatcherBase = requireDispatcherBase(); + const Pool = requirePool(); + const Client = requireClient(); + const util = requireUtil$9(); + const createRedirectInterceptor = requireRedirectInterceptor(); + + const kOnConnect = Symbol('onConnect'); + const kOnDisconnect = Symbol('onDisconnect'); + const kOnConnectionError = Symbol('onConnectionError'); + const kMaxRedirections = Symbol('maxRedirections'); + const kOnDrain = Symbol('onDrain'); + const kFactory = Symbol('factory'); + const kOptions = Symbol('options'); + + function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) + } + + class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + super(options); + + if (connect && typeof connect !== 'function') { + connect = { ...connect }; + } + + this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })]; + + this[kOptions] = { ...util.deepClone(options), connect }; + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined; + this[kMaxRedirections] = maxRedirections; + this[kFactory] = factory; + this[kClients] = new Map(); + + this[kOnDrain] = (origin, targets) => { + this.emit('drain', origin, [this, ...targets]); + }; + + this[kOnConnect] = (origin, targets) => { + this.emit('connect', origin, [this, ...targets]); + }; + + this[kOnDisconnect] = (origin, targets, err) => { + this.emit('disconnect', origin, [this, ...targets], err); + }; + + this[kOnConnectionError] = (origin, targets, err) => { + this.emit('connectionError', origin, [this, ...targets], err); + }; + } + + get [kRunning] () { + let ret = 0; + for (const client of this[kClients].values()) { + ret += client[kRunning]; + } + return ret + } + + [kDispatch] (opts, handler) { + let key; + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin); + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + let dispatcher = this[kClients].get(key); + + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]); + + // This introduces a tiny memory leak, as dispatchers are never removed from the map. + // TODO(mcollina): remove te timer when the client/pool do not have any more + // active connections. + this[kClients].set(key, dispatcher); + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = []; + for (const client of this[kClients].values()) { + closePromises.push(client.close()); + } + this[kClients].clear(); + + await Promise.all(closePromises); + } + + async [kDestroy] (err) { + const destroyPromises = []; + for (const client of this[kClients].values()) { + destroyPromises.push(client.destroy(err)); + } + this[kClients].clear(); + + await Promise.all(destroyPromises); + } + } + + agent = Agent; + return agent; +} + +var proxyAgent; +var hasRequiredProxyAgent; + +function requireProxyAgent () { + if (hasRequiredProxyAgent) return proxyAgent; + hasRequiredProxyAgent = 1; + + const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = requireSymbols$4(); + const { URL } = require$$1$6; + const Agent = requireAgent(); + const Pool = requirePool(); + const DispatcherBase = requireDispatcherBase(); + const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = requireErrors(); + const buildConnector = requireConnect(); + const Client = requireClient(); + + const kAgent = Symbol('proxy agent'); + const kClient = Symbol('proxy client'); + const kProxyHeaders = Symbol('proxy headers'); + const kRequestTls = Symbol('request tls settings'); + const kProxyTls = Symbol('proxy tls settings'); + const kConnectEndpoint = Symbol('connect endpoint function'); + const kTunnelProxy = Symbol('tunnel proxy'); + + function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 + } + + function defaultFactory (origin, opts) { + return new Pool(origin, opts) + } + + const noop = () => {}; + + function defaultAgentFactory (origin, opts) { + if (opts.connections === 1) { + return new Client(origin, opts) + } + return new Pool(origin, opts) + } + + class Http1ProxyWrapper extends DispatcherBase { + #client + + constructor (proxyUrl, { headers = {}, connect, factory }) { + super(); + if (!proxyUrl) { + throw new InvalidArgumentError('Proxy URL is mandatory') + } + + this[kProxyHeaders] = headers; + if (factory) { + this.#client = factory(proxyUrl, { connect }); + } else { + this.#client = new Client(proxyUrl, { connect }); + } + } + + [kDispatch] (opts, handler) { + const onHeaders = handler.onHeaders; + handler.onHeaders = function (statusCode, data, resume) { + if (statusCode === 407) { + if (typeof handler.onError === 'function') { + handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')); + } + return + } + if (onHeaders) onHeaders.call(this, statusCode, data, resume); + }; + + // Rewrite request as an HTTP1 Proxy request, without tunneling. + const { + origin, + path = '/', + headers = {} + } = opts; + + opts.path = origin + path; + + if (!('host' in headers) && !('Host' in headers)) { + const { host } = new URL(origin); + headers.host = host; + } + opts.headers = { ...this[kProxyHeaders], ...headers }; + + return this.#client[kDispatch](opts, handler) + } + + async [kClose] () { + return this.#client.close() + } + + async [kDestroy] (err) { + return this.#client.destroy(err) + } + } + + class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(); + + if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { + throw new InvalidArgumentError('Proxy uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts; + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + const { proxyTunnel = true } = opts; + + const url = this.#getUrl(opts); + const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url; + + this[kProxy] = { uri: href, protocol }; + this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : []; + this[kRequestTls] = opts.requestTls; + this[kProxyTls] = opts.proxyTls; + this[kProxyHeaders] = opts.headers || {}; + this[kTunnelProxy] = proxyTunnel; + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`; + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token; + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`; + } + + const connect = buildConnector({ ...opts.proxyTls }); + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }); + + const agentFactory = opts.factory || defaultAgentFactory; + const factory = (origin, options) => { + const { protocol } = new URL(origin); + if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { + return new Http1ProxyWrapper(this[kProxy].uri, { + headers: this[kProxyHeaders], + connect, + factory: agentFactory + }) + } + return agentFactory(origin, options) + }; + this[kClient] = clientFactory(url, { connect }); + this[kAgent] = new Agent({ + ...opts, + factory, + connect: async (opts, callback) => { + let requestedPath = opts.host; + if (!opts.port) { + requestedPath += `:${defaultProtocolPort(opts.protocol)}`; + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedPath, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host: opts.host + }, + servername: this[kProxyTls]?.servername || proxyHostname + }); + if (statusCode !== 200) { + socket.on('error', noop).destroy(); + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)); + } + if (opts.protocol !== 'https:') { + callback(null, socket); + return + } + let servername; + if (this[kRequestTls]) { + servername = this[kRequestTls].servername; + } else { + servername = opts.servername; + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback); + } catch (err) { + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + // Throw a custom error to avoid loop in client.js#connect + callback(new SecureProxyConnectionError(err)); + } else { + callback(err); + } + } + } + }); + } + + dispatch (opts, handler) { + const headers = buildHeaders(opts.headers); + throwIfProxyAuthIsSent(headers); + + if (headers && !('host' in headers) && !('Host' in headers)) { + const { host } = new URL(opts.origin); + headers.host = host; + } + + return this[kAgent].dispatch( + { + ...opts, + headers + }, + handler + ) + } + + /** + * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts + * @returns {URL} + */ + #getUrl (opts) { + if (typeof opts === 'string') { + return new URL(opts) + } else if (opts instanceof URL) { + return opts + } else { + return new URL(opts.uri) + } + } + + async [kClose] () { + await this[kAgent].close(); + await this[kClient].close(); + } + + async [kDestroy] () { + await this[kAgent].destroy(); + await this[kClient].destroy(); + } + } + + /** + * @param {string[] | Record} headers + * @returns {Record} + */ + function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {}; + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1]; + } + + return headersPair + } + + return headers + } + + /** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ + function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization'); + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } + } + + proxyAgent = ProxyAgent; + return proxyAgent; +} + +var envHttpProxyAgent; +var hasRequiredEnvHttpProxyAgent; + +function requireEnvHttpProxyAgent () { + if (hasRequiredEnvHttpProxyAgent) return envHttpProxyAgent; + hasRequiredEnvHttpProxyAgent = 1; + + const DispatcherBase = requireDispatcherBase(); + const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = requireSymbols$4(); + const ProxyAgent = requireProxyAgent(); + const Agent = requireAgent(); + + const DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443 + }; + + let experimentalWarned = false; + + class EnvHttpProxyAgent extends DispatcherBase { + #noProxyValue = null + #noProxyEntries = null + #opts = null + + constructor (opts = {}) { + super(); + this.#opts = opts; + + if (!experimentalWarned) { + experimentalWarned = true; + process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { + code: 'UNDICI-EHPA' + }); + } + + const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts; + + this[kNoProxyAgent] = new Agent(agentOpts); + + const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY; + if (HTTP_PROXY) { + this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }); + } else { + this[kHttpProxyAgent] = this[kNoProxyAgent]; + } + + const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY; + if (HTTPS_PROXY) { + this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }); + } else { + this[kHttpsProxyAgent] = this[kHttpProxyAgent]; + } + + this.#parseNoProxy(); + } + + [kDispatch] (opts, handler) { + const url = new URL(opts.origin); + const agent = this.#getProxyAgentForUrl(url); + return agent.dispatch(opts, handler) + } + + async [kClose] () { + await this[kNoProxyAgent].close(); + if (!this[kHttpProxyAgent][kClosed]) { + await this[kHttpProxyAgent].close(); + } + if (!this[kHttpsProxyAgent][kClosed]) { + await this[kHttpsProxyAgent].close(); + } + } + + async [kDestroy] (err) { + await this[kNoProxyAgent].destroy(err); + if (!this[kHttpProxyAgent][kDestroyed]) { + await this[kHttpProxyAgent].destroy(err); + } + if (!this[kHttpsProxyAgent][kDestroyed]) { + await this[kHttpsProxyAgent].destroy(err); + } + } + + #getProxyAgentForUrl (url) { + let { protocol, host: hostname, port } = url; + + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, '').toLowerCase(); + port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0; + if (!this.#shouldProxy(hostname, port)) { + return this[kNoProxyAgent] + } + if (protocol === 'https:') { + return this[kHttpsProxyAgent] + } + return this[kHttpProxyAgent] + } + + #shouldProxy (hostname, port) { + if (this.#noProxyChanged) { + this.#parseNoProxy(); + } + + if (this.#noProxyEntries.length === 0) { + return true // Always proxy if NO_PROXY is not set or empty. + } + if (this.#noProxyValue === '*') { + return false // Never proxy if wildcard is set. + } + + for (let i = 0; i < this.#noProxyEntries.length; i++) { + const entry = this.#noProxyEntries[i]; + if (entry.port && entry.port !== port) { + continue // Skip if ports don't match. + } + if (!/^[.*]/.test(entry.hostname)) { + // No wildcards, so don't proxy only if there is not an exact match. + if (hostname === entry.hostname) { + return false + } + } else { + // Don't proxy if the hostname ends with the no_proxy host. + if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { + return false + } + } + } + + return true + } + + #parseNoProxy () { + const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv; + const noProxySplit = noProxyValue.split(/[,\s]/); + const noProxyEntries = []; + + for (let i = 0; i < noProxySplit.length; i++) { + const entry = noProxySplit[i]; + if (!entry) { + continue + } + const parsed = entry.match(/^(.+):(\d+)$/); + noProxyEntries.push({ + hostname: (parsed ? parsed[1] : entry).toLowerCase(), + port: parsed ? Number.parseInt(parsed[2], 10) : 0 + }); + } + + this.#noProxyValue = noProxyValue; + this.#noProxyEntries = noProxyEntries; + } + + get #noProxyChanged () { + if (this.#opts.noProxy !== undefined) { + return false + } + return this.#noProxyValue !== this.#noProxyEnv + } + + get #noProxyEnv () { + return process.env.no_proxy ?? process.env.NO_PROXY ?? '' + } + } + + envHttpProxyAgent = EnvHttpProxyAgent; + return envHttpProxyAgent; +} + +var retryHandler; +var hasRequiredRetryHandler; + +function requireRetryHandler () { + if (hasRequiredRetryHandler) return retryHandler; + hasRequiredRetryHandler = 1; + const assert = require$$0$4; + + const { kRetryHandlerDefaultRetry } = requireSymbols$4(); + const { RequestRetryError } = requireErrors(); + const { + isDisturbed, + parseHeaders, + parseRangeHeader, + wrapRequestBody + } = requireUtil$9(); + + function calculateRetryAfterHeader (retryAfter) { + const current = Date.now(); + return new Date(retryAfter).getTime() - current + } + + class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts; + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {}; + + this.dispatch = handlers.dispatch; + this.handler = handlers.handler; + this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }; + this.abort = null; + this.aborted = false; + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + minTimeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE', + 'UND_ERR_SOCKET' + ] + }; + + this.retryCount = 0; + this.retryCountCheckpoint = 0; + this.start = 0; + this.end = null; + this.etag = null; + this.resume = null; + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true; + if (this.abort) { + this.abort(reason); + } else { + this.reason = reason; + } + }); + } + + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent(); + } + } + + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket); + } + } + + onConnect (abort) { + if (this.aborted) { + abort(this.reason); + } else { + this.abort = abort; + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err; + const { method, retryOptions } = opts; + const { + maxRetries, + minTimeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions; + const { counter } = state; + + // Any code that is not a Undici's originated and allowed to retry + if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { + cb(err); + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err); + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err); + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err); + return + } + + let retryAfterHeader = headers?.['retry-after']; + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader); + retryAfterHeader = Number.isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3; // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout); + + setTimeout(() => cb(null), retryTimeout); + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders); + + this.retryCount += 1; + + if (statusCode >= 300) { + if (this.retryOpts.statusCodes.includes(statusCode) === false) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } else { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + data: { + count: this.retryCount + } + }) + ); + return false + } + } + + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null; + + // Only Partial Content 206 supposed to provide Content-Range, + // any other status code that partially consumed the payload + // should not be retry because it would result in downstream + // wrongly concatanete multiple responses. + if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { + this.abort( + new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { + headers, + data: { count: this.retryCount } + }) + ); + return false + } + + const contentRange = parseRangeHeader(headers['content-range']); + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + ); + return false + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + data: { count: this.retryCount } + }) + ); + return false + } + + const { start, size, end = size - 1 } = contentRange; + + assert(this.start === start, 'content-range mismatch'); + assert(this.end == null || this.end === end, 'content-range mismatch'); + + this.resume = resume; + return true + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']); + + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const { start, size, end = size - 1 } = range; + assert( + start != null && Number.isFinite(start), + 'content-range mismatch' + ); + assert(end != null && Number.isFinite(end), 'invalid content-length'); + + this.start = start; + this.end = end; + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length']; + this.end = contentLength != null ? Number(contentLength) - 1 : null; + } + + assert(Number.isFinite(this.start)); + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ); + + this.resume = resume; + this.etag = headers.etag != null ? headers.etag : null; + + // Weak etags are not useful for comparison nor cache + // for instance not safe to assume if the response is byte-per-byte + // equal + if (this.etag != null && this.etag.startsWith('W/')) { + this.etag = null; + } + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const err = new RequestRetryError('Request failed', statusCode, { + headers, + data: { count: this.retryCount } + }); + + this.abort(err); + + return false + } + + onData (chunk) { + this.start += chunk.length; + + return this.handler.onData(chunk) + } + + onComplete (rawTrailers) { + this.retryCount = 0; + return this.handler.onComplete(rawTrailers) + } + + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + // We reconcile in case of a mix between network errors + // and server error response + if (this.retryCount - this.retryCountCheckpoint > 0) { + // We count the difference between the last checkpoint and the current retry count + this.retryCount = + this.retryCountCheckpoint + + (this.retryCount - this.retryCountCheckpoint); + } else { + this.retryCount += 1; + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ); + + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + if (this.start !== 0) { + const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }; + + // Weak etag check - weak etags will make comparison algorithms never match + if (this.etag != null) { + headers['if-match'] = this.etag; + } + + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + ...headers + } + }; + } + + try { + this.retryCountCheckpoint = this.retryCount; + this.dispatch(this.opts, this); + } catch (err) { + this.handler.onError(err); + } + } + } + } + + retryHandler = RetryHandler; + return retryHandler; +} + +var retryAgent; +var hasRequiredRetryAgent; + +function requireRetryAgent () { + if (hasRequiredRetryAgent) return retryAgent; + hasRequiredRetryAgent = 1; + + const Dispatcher = requireDispatcher(); + const RetryHandler = requireRetryHandler(); + + class RetryAgent extends Dispatcher { + #agent = null + #options = null + constructor (agent, options = {}) { + super(options); + this.#agent = agent; + this.#options = options; + } + + dispatch (opts, handler) { + const retry = new RetryHandler({ + ...opts, + retryOptions: this.#options + }, { + dispatch: this.#agent.dispatch.bind(this.#agent), + handler + }); + return this.#agent.dispatch(opts, retry) + } + + close () { + return this.#agent.close() + } + + destroy () { + return this.#agent.destroy() + } + } + + retryAgent = RetryAgent; + return retryAgent; +} + +var api = {}; + +var apiRequest = {exports: {}}; + +var readable; +var hasRequiredReadable; + +function requireReadable () { + if (hasRequiredReadable) return readable; + hasRequiredReadable = 1; + + const assert = require$$0$4; + const { Readable } = require$$0$5; + const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = requireErrors(); + const util = requireUtil$9(); + const { ReadableStreamFrom } = requireUtil$9(); + + const kConsume = Symbol('kConsume'); + const kReading = Symbol('kReading'); + const kBody = Symbol('kBody'); + const kAbort = Symbol('kAbort'); + const kContentType = Symbol('kContentType'); + const kContentLength = Symbol('kContentLength'); + + const noop = () => {}; + + class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + contentLength, + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }); + + this._readableState.dataEmitted = false; + + this[kAbort] = abort; + this[kConsume] = null; + this[kBody] = null; + this[kContentType] = contentType; + this[kContentLength] = contentLength; + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false; + } + + destroy (err) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError(); + } + + if (err) { + this[kAbort](); + } + + return super.destroy(err) + } + + _destroy (err, callback) { + // Workaround for Node "bug". If the stream is destroyed in same + // tick as it is created, then a user who is waiting for a + // promise (i.e micro tick) for installing a 'error' listener will + // never get a chance and will always encounter an unhandled exception. + if (!this[kReading]) { + setImmediate(() => { + callback(err); + }); + } else { + callback(err); + } + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true; + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args); + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ); + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null) { + consumePush(this[kConsume], chunk); + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-bytes + async bytes () { + return consume(this, 'bytes') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this); + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader(); // Ensure stream is locked. + assert(this[kBody].locked); + } + } + return this[kBody] + } + + async dump (opts) { + let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024; + const signal = opts?.signal; + + if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + + signal?.throwIfAborted(); + + if (this._readableState.closeEmitted) { + return null + } + + return await new Promise((resolve, reject) => { + if (this[kContentLength] > limit) { + this.destroy(new AbortError()); + } + + const onAbort = () => { + this.destroy(signal.reason ?? new AbortError()); + }; + signal?.addEventListener('abort', onAbort); + + this + .on('close', function () { + signal?.removeEventListener('abort', onAbort); + if (signal?.aborted) { + reject(signal.reason ?? new AbortError()); + } else { + resolve(null); + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length; + if (limit <= 0) { + this.destroy(); + } + }) + .resume(); + }) + } + } + + // https://streams.spec.whatwg.org/#readablestream-locked + function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] + } + + // https://fetch.spec.whatwg.org/#body-unusable + function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) + } + + async function consume (stream, type) { + assert(!stream[kConsume]); + + return new Promise((resolve, reject) => { + if (isUnusable(stream)) { + const rState = stream._readableState; + if (rState.destroyed && rState.closeEmitted === false) { + stream + .on('error', err => { + reject(err); + }) + .on('close', () => { + reject(new TypeError('unusable')); + }); + } else { + reject(rState.errored ?? new TypeError('unusable')); + } + } else { + queueMicrotask(() => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + }; + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err); + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()); + } + }); + + consumeStart(stream[kConsume]); + }); + } + }) + } + + function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream; + + if (state.bufferIndex) { + const start = state.bufferIndex; + const end = state.buffer.length; + for (let n = start; n < end; n++) { + consumePush(consume, state.buffer[n]); + } + } else { + for (const chunk of state.buffer) { + consumePush(consume, chunk); + } + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]); + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]); + }); + } + + consume.stream.resume(); + + while (consume.stream.read() != null) { + // Loop + } + } + + /** + * @param {Buffer[]} chunks + * @param {number} length + */ + function chunksDecode (chunks, length) { + if (chunks.length === 0 || length === 0) { + return '' + } + const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length); + const bufferLength = buffer.length; + + // Skip BOM. + const start = + bufferLength > 2 && + buffer[0] === 0xef && + buffer[1] === 0xbb && + buffer[2] === 0xbf + ? 3 + : 0; + return buffer.utf8Slice(start, bufferLength) + } + + /** + * @param {Buffer[]} chunks + * @param {number} length + * @returns {Uint8Array} + */ + function chunksConcat (chunks, length) { + if (chunks.length === 0 || length === 0) { + return new Uint8Array(0) + } + if (chunks.length === 1) { + // fast-path + return new Uint8Array(chunks[0]) + } + const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer); + + let offset = 0; + for (let i = 0; i < chunks.length; ++i) { + const chunk = chunks[i]; + buffer.set(chunk, offset); + offset += chunk.length; + } + + return buffer + } + + function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume; + + try { + if (type === 'text') { + resolve(chunksDecode(body, length)); + } else if (type === 'json') { + resolve(JSON.parse(chunksDecode(body, length))); + } else if (type === 'arrayBuffer') { + resolve(chunksConcat(body, length).buffer); + } else if (type === 'blob') { + resolve(new Blob(body, { type: stream[kContentType] })); + } else if (type === 'bytes') { + resolve(chunksConcat(body, length)); + } + + consumeFinish(consume); + } catch (err) { + stream.destroy(err); + } + } + + function consumePush (consume, chunk) { + consume.length += chunk.length; + consume.body.push(chunk); + } + + function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err); + } else { + consume.resolve(); + } + + consume.type = null; + consume.stream = null; + consume.resolve = null; + consume.reject = null; + consume.length = 0; + consume.body = null; + } + + readable = { Readable: BodyReadable, chunksDecode }; + return readable; +} + +var util$7; +var hasRequiredUtil$7; + +function requireUtil$7 () { + if (hasRequiredUtil$7) return util$7; + hasRequiredUtil$7 = 1; + const assert = require$$0$4; + const { + ResponseStatusCodeError + } = requireErrors(); + + const { chunksDecode } = requireReadable(); + const CHUNK_LIMIT = 128 * 1024; + + async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body); + + let chunks = []; + let length = 0; + + try { + for await (const chunk of body) { + chunks.push(chunk); + length += chunk.length; + if (length > CHUNK_LIMIT) { + chunks = []; + length = 0; + break + } + } + } catch { + chunks = []; + length = 0; + // Do nothing.... + } + + const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`; + + if (statusCode === 204 || !contentType || !length) { + queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers))); + return + } + + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + let payload; + + try { + if (isContentTypeApplicationJson(contentType)) { + payload = JSON.parse(chunksDecode(chunks, length)); + } else if (isContentTypeText(contentType)) { + payload = chunksDecode(chunks, length); + } + } catch { + // process in a callback to avoid throwing in the microtask queue + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload))); + } + + const isContentTypeApplicationJson = (contentType) => { + return ( + contentType.length > 15 && + contentType[11] === '/' && + contentType[0] === 'a' && + contentType[1] === 'p' && + contentType[2] === 'p' && + contentType[3] === 'l' && + contentType[4] === 'i' && + contentType[5] === 'c' && + contentType[6] === 'a' && + contentType[7] === 't' && + contentType[8] === 'i' && + contentType[9] === 'o' && + contentType[10] === 'n' && + contentType[12] === 'j' && + contentType[13] === 's' && + contentType[14] === 'o' && + contentType[15] === 'n' + ) + }; + + const isContentTypeText = (contentType) => { + return ( + contentType.length > 4 && + contentType[4] === '/' && + contentType[0] === 't' && + contentType[1] === 'e' && + contentType[2] === 'x' && + contentType[3] === 't' + ) + }; + + util$7 = { + getResolveErrorBodyCallback, + isContentTypeApplicationJson, + isContentTypeText + }; + return util$7; +} + +var hasRequiredApiRequest; + +function requireApiRequest () { + if (hasRequiredApiRequest) return apiRequest.exports; + hasRequiredApiRequest = 1; + + const assert = require$$0$4; + const { Readable } = requireReadable(); + const { InvalidArgumentError, RequestAbortedError } = requireErrors(); + const util = requireUtil$9(); + const { getResolveErrorBodyCallback } = requireUtil$7(); + const { AsyncResource } = require$$5$3; + + class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts; + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST'); + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err); + } + throw err + } + + this.method = method; + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.callback = callback; + this.res = null; + this.abort = null; + this.body = body; + this.trailers = {}; + this.context = null; + this.onInfo = onInfo || null; + this.throwOnError = throwOnError; + this.highWaterMark = highWaterMark; + this.signal = signal; + this.reason = null; + this.removeAbortListener = null; + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err); + }); + } + + if (this.signal) { + if (this.signal.aborted) { + this.reason = this.signal.reason ?? new RequestAbortedError(); + } else { + this.removeAbortListener = util.addAbortListener(this.signal, () => { + this.reason = this.signal.reason ?? new RequestAbortedError(); + if (this.res) { + util.destroy(this.res.on('error', util.nop), this.reason); + } else if (this.abort) { + this.abort(this.reason); + } + + if (this.removeAbortListener) { + this.res?.off('close', this.removeAbortListener); + this.removeAbortListener(); + this.removeAbortListener = null; + } + }); + } + } + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason); + return + } + + assert(this.callback); + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this; + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }); + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers; + const contentType = parsedHeaders['content-type']; + const contentLength = parsedHeaders['content-length']; + const res = new Readable({ + resume, + abort, + contentType, + contentLength: this.method !== 'HEAD' && contentLength + ? Number(contentLength) + : null, + highWaterMark + }); + + if (this.removeAbortListener) { + res.on('close', this.removeAbortListener); + } + + this.callback = null; + this.res = res; + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ); + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body: res, + context + }); + } + } + } + + onData (chunk) { + return this.res.push(chunk) + } + + onComplete (trailers) { + util.parseHeaders(trailers, this.trailers); + this.res.push(null); + } + + onError (err) { + const { res, callback, body, opaque } = this; + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + + if (res) { + this.res = null; + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err); + }); + } + + if (body) { + this.body = null; + util.destroy(body, err); + } + + if (this.removeAbortListener) { + res?.off('close', this.removeAbortListener); + this.removeAbortListener(); + this.removeAbortListener = null; + } + } + } + + function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + apiRequest.exports = request; + apiRequest.exports.RequestHandler = RequestHandler; + return apiRequest.exports; +} + +var abortSignal; +var hasRequiredAbortSignal; + +function requireAbortSignal () { + if (hasRequiredAbortSignal) return abortSignal; + hasRequiredAbortSignal = 1; + const { addAbortListener } = requireUtil$9(); + const { RequestAbortedError } = requireErrors(); + + const kListener = Symbol('kListener'); + const kSignal = Symbol('kSignal'); + + function abort (self) { + if (self.abort) { + self.abort(self[kSignal]?.reason); + } else { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError(); + } + removeSignal(self); + } + + function addSignal (self, signal) { + self.reason = null; + + self[kSignal] = null; + self[kListener] = null; + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self); + return + } + + self[kSignal] = signal; + self[kListener] = () => { + abort(self); + }; + + addAbortListener(self[kSignal], self[kListener]); + } + + function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]); + } else { + self[kSignal].removeListener('abort', self[kListener]); + } + + self[kSignal] = null; + self[kListener] = null; + } + + abortSignal = { + addSignal, + removeSignal + }; + return abortSignal; +} + +var apiStream; +var hasRequiredApiStream; + +function requireApiStream () { + if (hasRequiredApiStream) return apiStream; + hasRequiredApiStream = 1; + + const assert = require$$0$4; + const { finished, PassThrough } = require$$0$5; + const { InvalidArgumentError, InvalidReturnValueError } = requireErrors(); + const util = requireUtil$9(); + const { getResolveErrorBodyCallback } = requireUtil$7(); + const { AsyncResource } = require$$5$3; + const { addSignal, removeSignal } = requireAbortSignal(); + + class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts; + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM'); + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err); + } + throw err + } + + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.factory = factory; + this.callback = callback; + this.res = null; + this.abort = null; + this.context = null; + this.trailers = null; + this.body = body; + this.onInfo = onInfo || null; + this.throwOnError = throwOnError || false; + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err); + }); + } + + addSignal(this, signal); + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason); + return + } + + assert(this.callback); + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this; + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }); + } + return + } + + this.factory = null; + + let res; + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers; + const contentType = parsedHeaders['content-type']; + res = new PassThrough(); + + this.callback = null; + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ); + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }); + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this; + + this.res = null; + if (err || !res.readable) { + util.destroy(res, err); + } + + this.callback = null; + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }); + + if (err) { + abort(); + } + }); + } + + res.on('drain', resume); + + this.res = res; + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState?.needDrain; + + return needDrain !== true + } + + onData (chunk) { + const { res } = this; + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this; + + removeSignal(this); + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers); + + res.end(); + } + + onError (err) { + const { res, callback, opaque, body } = this; + + removeSignal(this); + + this.factory = null; + + if (res) { + this.res = null; + util.destroy(res, err); + } else if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + + if (body) { + this.body = null; + util.destroy(body, err); + } + } + } + + function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + apiStream = stream; + return apiStream; +} + +var apiPipeline; +var hasRequiredApiPipeline; + +function requireApiPipeline () { + if (hasRequiredApiPipeline) return apiPipeline; + hasRequiredApiPipeline = 1; + + const { + Readable, + Duplex, + PassThrough + } = require$$0$5; + const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError + } = requireErrors(); + const util = requireUtil$9(); + const { AsyncResource } = require$$5$3; + const { addSignal, removeSignal } = requireAbortSignal(); + const assert = require$$0$4; + + const kResume = Symbol('resume'); + + class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }); + + this[kResume] = null; + } + + _read () { + const { [kResume]: resume } = this; + + if (resume) { + this[kResume] = null; + resume(); + } + } + + _destroy (err, callback) { + this._read(); + + callback(err); + } + } + + class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }); + this[kResume] = resume; + } + + _read () { + this[kResume](); + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError(); + } + + callback(err); + } + } + + class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE'); + + this.opaque = opaque || null; + this.responseHeaders = responseHeaders || null; + this.handler = handler; + this.abort = null; + this.context = null; + this.onInfo = onInfo || null; + + this.req = new PipelineRequest().on('error', util.nop); + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this; + + if (body?.resume) { + body.resume(); + } + }, + write: (chunk, encoding, callback) => { + const { req } = this; + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback(); + } else { + req[kResume] = callback; + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this; + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError(); + } + + if (abort && err) { + abort(); + } + + util.destroy(body, err); + util.destroy(req, err); + util.destroy(res, err); + + removeSignal(this); + + callback(err); + } + }).on('prefinish', () => { + const { req } = this; + + // Node < 15 does not call _final in same tick. + req.push(null); + }); + + this.res = null; + + addSignal(this, signal); + } + + onConnect (abort, context) { + const { ret, res } = this; + + if (this.reason) { + abort(this.reason); + return + } + + assert(!res, 'pipeline cannot be retried'); + assert(!ret.destroyed); + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this; + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + this.onInfo({ statusCode, headers }); + } + return + } + + this.res = new PipelineResponse(resume); + + let body; + try { + this.handler = null; + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }); + } catch (err) { + this.res.on('error', util.nop); + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this; + + if (!ret.push(chunk) && body.pause) { + body.pause(); + } + }) + .on('error', (err) => { + const { ret } = this; + + util.destroy(ret, err); + }) + .on('end', () => { + const { ret } = this; + + ret.push(null); + }) + .on('close', () => { + const { ret } = this; + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()); + } + }); + + this.body = body; + } + + onData (chunk) { + const { res } = this; + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this; + res.push(null); + } + + onError (err) { + const { ret } = this; + this.handler = null; + util.destroy(ret, err); + } + } + + function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler); + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler); + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } + } + + apiPipeline = pipeline; + return apiPipeline; +} + +var apiUpgrade; +var hasRequiredApiUpgrade; + +function requireApiUpgrade () { + if (hasRequiredApiUpgrade) return apiUpgrade; + hasRequiredApiUpgrade = 1; + + const { InvalidArgumentError, SocketError } = requireErrors(); + const { AsyncResource } = require$$5$3; + const util = requireUtil$9(); + const { addSignal, removeSignal } = requireAbortSignal(); + const assert = require$$0$4; + + class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE'); + + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.callback = callback; + this.abort = null; + this.context = null; + + addSignal(this, signal); + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason); + return + } + + assert(this.callback); + + this.abort = abort; + this.context = null; + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + assert(statusCode === 101); + + const { callback, opaque, context } = this; + + removeSignal(this); + + this.callback = null; + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }); + } + + onError (err) { + const { callback, opaque } = this; + + removeSignal(this); + + if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + } + } + + function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback); + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + apiUpgrade = upgrade; + return apiUpgrade; +} + +var apiConnect; +var hasRequiredApiConnect; + +function requireApiConnect () { + if (hasRequiredApiConnect) return apiConnect; + hasRequiredApiConnect = 1; + + const assert = require$$0$4; + const { AsyncResource } = require$$5$3; + const { InvalidArgumentError, SocketError } = requireErrors(); + const util = requireUtil$9(); + const { addSignal, removeSignal } = requireAbortSignal(); + + class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT'); + + this.opaque = opaque || null; + this.responseHeaders = responseHeaders || null; + this.callback = callback; + this.abort = null; + + addSignal(this, signal); + } + + onConnect (abort, context) { + if (this.reason) { + abort(this.reason); + return + } + + assert(this.callback); + + this.abort = abort; + this.context = context; + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this; + + removeSignal(this); + + this.callback = null; + + let headers = rawHeaders; + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders); + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }); + } + + onError (err) { + const { callback, opaque } = this; + + removeSignal(this); + + if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + } + } + + function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback); + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts?.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + apiConnect = connect; + return apiConnect; +} + +var hasRequiredApi; + +function requireApi () { + if (hasRequiredApi) return api; + hasRequiredApi = 1; + + api.request = requireApiRequest(); + api.stream = requireApiStream(); + api.pipeline = requireApiPipeline(); + api.upgrade = requireApiUpgrade(); + api.connect = requireApiConnect(); + return api; +} + +var mockErrors; +var hasRequiredMockErrors; + +function requireMockErrors () { + if (hasRequiredMockErrors) return mockErrors; + hasRequiredMockErrors = 1; + + const { UndiciError } = requireErrors(); + + const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED'); + + /** + * The request does not match any registered mock dispatches. + */ + class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message); + Error.captureStackTrace(this, MockNotMatchedError); + this.name = 'MockNotMatchedError'; + this.message = message || 'The request does not match any registered mock dispatches'; + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } + + static [Symbol.hasInstance] (instance) { + return instance && instance[kMockNotMatchedError] === true + } + + [kMockNotMatchedError] = true + } + + mockErrors = { + MockNotMatchedError + }; + return mockErrors; +} + +var mockSymbols; +var hasRequiredMockSymbols; + +function requireMockSymbols () { + if (hasRequiredMockSymbols) return mockSymbols; + hasRequiredMockSymbols = 1; + + mockSymbols = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') + }; + return mockSymbols; +} + +var mockUtils; +var hasRequiredMockUtils; + +function requireMockUtils () { + if (hasRequiredMockUtils) return mockUtils; + hasRequiredMockUtils = 1; + + const { MockNotMatchedError } = requireMockErrors(); + const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect + } = requireMockSymbols(); + const { buildURL } = requireUtil$9(); + const { STATUS_CODES } = require$$2$1; + const { + types: { + isPromise + } + } = require$$0$7; + + function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false + } + + function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) + } + + /** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ + function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } + } + + /** @param {string[]} headers */ + function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice(); + const entries = []; + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]); + } + return Object.fromEntries(entries) + } + + function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers); + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName); + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true + } + + function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?'); + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()); + qp.sort(); + return [...pathSegments, qp.toString()].join('?') + } + + function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path); + const methodMatch = matchValue(mockDispatch.method, method); + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true; + const headersMatch = matchHeaders(mockDispatch, headers); + return pathMatch && methodMatch && bodyMatch && headersMatch + } + + function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (data instanceof Uint8Array) { + return data + } else if (data instanceof ArrayBuffer) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } + } + + function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path; + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath; + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)); + if (matchedMockDispatches.length === 0) { + const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers; + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) + } + + return matchedMockDispatches[0] + } + + function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }; + const replyData = typeof data === 'function' ? { callback: data } : { ...data }; + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }; + mockDispatches.push(newMockDispatch); + return newMockDispatch + } + + function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }); + if (index !== -1) { + mockDispatches.splice(index, 1); + } + } + + function buildKey (opts) { + const { path, method, body, headers, query } = opts; + return { + path, + method, + body, + headers, + query + } + } + + function generateKeyValues (data) { + const keys = Object.keys(data); + const result = []; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + const value = data[key]; + const name = Buffer.from(`${key}`); + if (Array.isArray(value)) { + for (let j = 0; j < value.length; ++j) { + result.push(name, Buffer.from(`${value[j]}`)); + } + } else { + result.push(name, Buffer.from(`${value}`)); + } + } + return result + } + + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ + function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' + } + + async function getResponse (body) { + const buffers = []; + for await (const data of body) { + buffers.push(data); + } + return Buffer.concat(buffers).toString('utf8') + } + + /** + * Mock dispatch function used to simulate undici dispatches + */ + function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts); + const mockDispatch = getMockDispatch(this[kDispatches], key); + + mockDispatch.timesInvoked++; + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }; + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch; + const { timesInvoked, times } = mockDispatch; + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times; + mockDispatch.pending = timesInvoked < times; + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key); + handler.onError(error); + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]); + }, delay); + } else { + handleReply(this[kDispatches]); + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers; + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data; + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)); + return + } + + const responseData = getResponseData(body); + const responseHeaders = generateKeyValues(headers); + const responseTrailers = generateKeyValues(trailers); + + handler.onConnect?.(err => handler.onError(err), null); + handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)); + handler.onData?.(Buffer.from(responseData)); + handler.onComplete?.(responseTrailers); + deleteMockDispatch(mockDispatches, key); + } + + function resume () {} + + return true + } + + function buildMockDispatch () { + const agent = this[kMockAgent]; + const origin = this[kOrigin]; + const originalDispatch = this[kOriginalDispatch]; + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler); + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect](); + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler); + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler); + } + } + } + + function checkNetConnect (netConnect, origin) { + const url = new URL(origin); + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false + } + + function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts; + return mockOptions + } + } + + mockUtils = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName, + buildHeadersFromArray + }; + return mockUtils; +} + +var mockInterceptor = {}; + +var hasRequiredMockInterceptor; + +function requireMockInterceptor () { + if (hasRequiredMockInterceptor) return mockInterceptor; + hasRequiredMockInterceptor = 1; + + const { getResponseData, buildKey, addMockDispatch } = requireMockUtils(); + const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch + } = requireMockSymbols(); + const { InvalidArgumentError } = requireErrors(); + const { buildURL } = requireUtil$9(); + + /** + * Defines the scope API for an interceptor reply + */ + class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch; + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs; + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true; + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes; + return this + } + } + + /** + * Defines an interceptor for a Mock + */ + class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET'; + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query); + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://'); + opts.path = parsedURL.pathname + parsedURL.search; + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase(); + } + + this[kDispatchKey] = buildKey(opts); + this[kDispatches] = mockDispatches; + this[kDefaultHeaders] = {}; + this[kDefaultTrailers] = {}; + this[kContentLength] = false; + } + + createMockScopeDispatchData ({ statusCode, data, responseOptions }) { + const responseData = getResponseData(data); + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}; + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }; + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }; + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (replyParameters) { + if (typeof replyParameters.statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyOptionsCallbackOrStatusCode) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyOptionsCallbackOrStatusCode === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyOptionsCallbackOrStatusCode(opts); + + // Check if it is in the right format + if (typeof resolvedData !== 'object' || resolvedData === null) { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const replyParameters = { data: '', responseOptions: {}, ...resolvedData }; + this.validateReplyParameters(replyParameters); + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(replyParameters) + } + }; + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback); + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const replyParameters = { + statusCode: replyOptionsCallbackOrStatusCode, + data: arguments[1] === undefined ? '' : arguments[1], + responseOptions: arguments[2] === undefined ? {} : arguments[2] + }; + this.validateReplyParameters(replyParameters); + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(replyParameters); + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData); + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }); + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers; + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers; + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true; + return this + } + } + + mockInterceptor.MockInterceptor = MockInterceptor; + mockInterceptor.MockScope = MockScope; + return mockInterceptor; +} + +var mockClient; +var hasRequiredMockClient; + +function requireMockClient () { + if (hasRequiredMockClient) return mockClient; + hasRequiredMockClient = 1; + + const { promisify } = require$$0$7; + const Client = requireClient(); + const { buildMockDispatch } = requireMockUtils(); + const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected + } = requireMockSymbols(); + const { MockInterceptor } = requireMockInterceptor(); + const Symbols = requireSymbols$4(); + const { InvalidArgumentError } = requireErrors(); + + /** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ + class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts); + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent; + this[kOrigin] = origin; + this[kDispatches] = []; + this[kConnected] = 1; + this[kOriginalDispatch] = this.dispatch; + this[kOriginalClose] = this.close.bind(this); + + this.dispatch = buildMockDispatch.call(this); + this.close = this[kClose]; + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])(); + this[kConnected] = 0; + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]); + } + } + + mockClient = MockClient; + return mockClient; +} + +var mockPool; +var hasRequiredMockPool; + +function requireMockPool () { + if (hasRequiredMockPool) return mockPool; + hasRequiredMockPool = 1; + + const { promisify } = require$$0$7; + const Pool = requirePool(); + const { buildMockDispatch } = requireMockUtils(); + const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected + } = requireMockSymbols(); + const { MockInterceptor } = requireMockInterceptor(); + const Symbols = requireSymbols$4(); + const { InvalidArgumentError } = requireErrors(); + + /** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ + class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts); + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent; + this[kOrigin] = origin; + this[kDispatches] = []; + this[kConnected] = 1; + this[kOriginalDispatch] = this.dispatch; + this[kOriginalClose] = this.close.bind(this); + + this.dispatch = buildMockDispatch.call(this); + this.close = this[kClose]; + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])(); + this[kConnected] = 0; + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]); + } + } + + mockPool = MockPool; + return mockPool; +} + +var pluralizer; +var hasRequiredPluralizer; + +function requirePluralizer () { + if (hasRequiredPluralizer) return pluralizer; + hasRequiredPluralizer = 1; + + const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' + }; + + const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' + }; + + pluralizer = class Pluralizer { + constructor (singular, plural) { + this.singular = singular; + this.plural = plural; + } + + pluralize (count) { + const one = count === 1; + const keys = one ? singulars : plurals; + const noun = one ? this.singular : this.plural; + return { ...keys, count, noun } + } + }; + return pluralizer; +} + +var pendingInterceptorsFormatter; +var hasRequiredPendingInterceptorsFormatter; + +function requirePendingInterceptorsFormatter () { + if (hasRequiredPendingInterceptorsFormatter) return pendingInterceptorsFormatter; + hasRequiredPendingInterceptorsFormatter = 1; + + const { Transform } = require$$0$5; + const { Console } = require$$1$7; + + const PERSISTENT = process.versions.icu ? '✅' : 'Y '; + const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N '; + + /** + * Gets the output of `console.table(…)` as a string. + */ + pendingInterceptorsFormatter = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk); + } + }); + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }); + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? PERSISTENT : NOT_PERSISTENT, + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })); + + this.logger.table(withPrettyHeaders); + return this.transform.read().toString() + } + }; + return pendingInterceptorsFormatter; +} + +var mockAgent; +var hasRequiredMockAgent; + +function requireMockAgent () { + if (hasRequiredMockAgent) return mockAgent; + hasRequiredMockAgent = 1; + + const { kClients } = requireSymbols$4(); + const Agent = requireAgent(); + const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory + } = requireMockSymbols(); + const MockClient = requireMockClient(); + const MockPool = requireMockPool(); + const { matchValue, buildMockOptions } = requireMockUtils(); + const { InvalidArgumentError, UndiciError } = requireErrors(); + const Dispatcher = requireDispatcher(); + const Pluralizer = requirePluralizer(); + const PendingInterceptorsFormatter = requirePendingInterceptorsFormatter(); + + class MockAgent extends Dispatcher { + constructor (opts) { + super(opts); + + this[kNetConnect] = true; + this[kIsMockActive] = true; + + // Instantiate Agent and encapsulate + if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts?.agent ? opts.agent : new Agent(opts); + this[kAgent] = agent; + + this[kClients] = agent[kClients]; + this[kOptions] = buildMockOptions(opts); + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin); + + if (!dispatcher) { + dispatcher = this[kFactory](origin); + this[kMockAgentSet](origin, dispatcher); + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin); + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close(); + this[kClients].clear(); + } + + deactivate () { + this[kIsMockActive] = false; + } + + activate () { + this[kIsMockActive] = true; + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher); + } else { + this[kNetConnect] = [matcher]; + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true; + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false; + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, dispatcher); + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]); + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const client = this[kClients].get(origin); + if (client) { + return client + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999'); + this[kMockAgentSet](origin, dispatcher); + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) { + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin); + this[kMockAgentSet](origin, dispatcher); + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]; + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients]; + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors(); + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length); + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } + } + + mockAgent = MockAgent; + return mockAgent; +} + +var global$1; +var hasRequiredGlobal; + +function requireGlobal () { + if (hasRequiredGlobal) return global$1; + hasRequiredGlobal = 1; + + // We include a version number for the Dispatcher API. In case of breaking changes, + // this version number must be increased to avoid conflicts. + const globalDispatcher = Symbol.for('undici.globalDispatcher.1'); + const { InvalidArgumentError } = requireErrors(); + const Agent = requireAgent(); + + if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()); + } + + function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }); + } + + function getGlobalDispatcher () { + return globalThis[globalDispatcher] + } + + global$1 = { + setGlobalDispatcher, + getGlobalDispatcher + }; + return global$1; +} + +var decoratorHandler; +var hasRequiredDecoratorHandler; + +function requireDecoratorHandler () { + if (hasRequiredDecoratorHandler) return decoratorHandler; + hasRequiredDecoratorHandler = 1; + + decoratorHandler = class DecoratorHandler { + #handler + + constructor (handler) { + if (typeof handler !== 'object' || handler === null) { + throw new TypeError('handler must be an object') + } + this.#handler = handler; + } + + onConnect (...args) { + return this.#handler.onConnect?.(...args) + } + + onError (...args) { + return this.#handler.onError?.(...args) + } + + onUpgrade (...args) { + return this.#handler.onUpgrade?.(...args) + } + + onResponseStarted (...args) { + return this.#handler.onResponseStarted?.(...args) + } + + onHeaders (...args) { + return this.#handler.onHeaders?.(...args) + } + + onData (...args) { + return this.#handler.onData?.(...args) + } + + onComplete (...args) { + return this.#handler.onComplete?.(...args) + } + + onBodySent (...args) { + return this.#handler.onBodySent?.(...args) + } + }; + return decoratorHandler; +} + +var redirect; +var hasRequiredRedirect; + +function requireRedirect () { + if (hasRequiredRedirect) return redirect; + hasRequiredRedirect = 1; + const RedirectHandler = requireRedirectHandler(); + + redirect = opts => { + const globalMaxRedirections = opts?.maxRedirections; + return dispatch => { + return function redirectInterceptor (opts, handler) { + const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts; + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler( + dispatch, + maxRedirections, + opts, + handler + ); + + return dispatch(baseOpts, redirectHandler) + } + } + }; + return redirect; +} + +var retry; +var hasRequiredRetry; + +function requireRetry () { + if (hasRequiredRetry) return retry; + hasRequiredRetry = 1; + const RetryHandler = requireRetryHandler(); + + retry = globalOpts => { + return dispatch => { + return function retryInterceptor (opts, handler) { + return dispatch( + opts, + new RetryHandler( + { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, + { + handler, + dispatch + } + ) + ) + } + } + }; + return retry; +} + +var dump; +var hasRequiredDump; + +function requireDump () { + if (hasRequiredDump) return dump; + hasRequiredDump = 1; + + const util = requireUtil$9(); + const { InvalidArgumentError, RequestAbortedError } = requireErrors(); + const DecoratorHandler = requireDecoratorHandler(); + + class DumpHandler extends DecoratorHandler { + #maxSize = 1024 * 1024 + #abort = null + #dumped = false + #aborted = false + #size = 0 + #reason = null + #handler = null + + constructor ({ maxSize }, handler) { + super(handler); + + if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { + throw new InvalidArgumentError('maxSize must be a number greater than 0') + } + + this.#maxSize = maxSize ?? this.#maxSize; + this.#handler = handler; + } + + onConnect (abort) { + this.#abort = abort; + + this.#handler.onConnect(this.#customAbort.bind(this)); + } + + #customAbort (reason) { + this.#aborted = true; + this.#reason = reason; + } + + // TODO: will require adjustment after new hooks are out + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = util.parseHeaders(rawHeaders); + const contentLength = headers['content-length']; + + if (contentLength != null && contentLength > this.#maxSize) { + throw new RequestAbortedError( + `Response size (${contentLength}) larger than maxSize (${ + this.#maxSize + })` + ) + } + + if (this.#aborted) { + return true + } + + return this.#handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + onError (err) { + if (this.#dumped) { + return + } + + err = this.#reason ?? err; + + this.#handler.onError(err); + } + + onData (chunk) { + this.#size = this.#size + chunk.length; + + if (this.#size >= this.#maxSize) { + this.#dumped = true; + + if (this.#aborted) { + this.#handler.onError(this.#reason); + } else { + this.#handler.onComplete([]); + } + } + + return true + } + + onComplete (trailers) { + if (this.#dumped) { + return + } + + if (this.#aborted) { + this.#handler.onError(this.reason); + return + } + + this.#handler.onComplete(trailers); + } + } + + function createDumpInterceptor ( + { maxSize: defaultMaxSize } = { + maxSize: 1024 * 1024 + } + ) { + return dispatch => { + return function Intercept (opts, handler) { + const { dumpMaxSize = defaultMaxSize } = + opts; + + const dumpHandler = new DumpHandler( + { maxSize: dumpMaxSize }, + handler + ); + + return dispatch(opts, dumpHandler) + } + } + } + + dump = createDumpInterceptor; + return dump; +} + +var dns; +var hasRequiredDns; + +function requireDns () { + if (hasRequiredDns) return dns; + hasRequiredDns = 1; + const { isIP } = require$$0$6; + const { lookup } = require$$1$8; + const DecoratorHandler = requireDecoratorHandler(); + const { InvalidArgumentError, InformationalError } = requireErrors(); + const maxInt = Math.pow(2, 31) - 1; + + class DNSInstance { + #maxTTL = 0 + #maxItems = 0 + #records = new Map() + dualStack = true + affinity = null + lookup = null + pick = null + + constructor (opts) { + this.#maxTTL = opts.maxTTL; + this.#maxItems = opts.maxItems; + this.dualStack = opts.dualStack; + this.affinity = opts.affinity; + this.lookup = opts.lookup ?? this.#defaultLookup; + this.pick = opts.pick ?? this.#defaultPick; + } + + get full () { + return this.#records.size === this.#maxItems + } + + runLookup (origin, opts, cb) { + const ips = this.#records.get(origin.hostname); + + // If full, we just return the origin + if (ips == null && this.full) { + cb(null, origin.origin); + return + } + + const newOpts = { + affinity: this.affinity, + dualStack: this.dualStack, + lookup: this.lookup, + pick: this.pick, + ...opts.dns, + maxTTL: this.#maxTTL, + maxItems: this.#maxItems + }; + + // If no IPs we lookup + if (ips == null) { + this.lookup(origin, newOpts, (err, addresses) => { + if (err || addresses == null || addresses.length === 0) { + cb(err ?? new InformationalError('No DNS entries found')); + return + } + + this.setRecords(origin, addresses); + const records = this.#records.get(origin.hostname); + + const ip = this.pick( + origin, + records, + newOpts.affinity + ); + + let port; + if (typeof ip.port === 'number') { + port = `:${ip.port}`; + } else if (origin.port !== '') { + port = `:${origin.port}`; + } else { + port = ''; + } + + cb( + null, + `${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + ); + }); + } else { + // If there's IPs we pick + const ip = this.pick( + origin, + ips, + newOpts.affinity + ); + + // If no IPs we lookup - deleting old records + if (ip == null) { + this.#records.delete(origin.hostname); + this.runLookup(origin, opts, cb); + return + } + + let port; + if (typeof ip.port === 'number') { + port = `:${ip.port}`; + } else if (origin.port !== '') { + port = `:${origin.port}`; + } else { + port = ''; + } + + cb( + null, + `${origin.protocol}//${ + ip.family === 6 ? `[${ip.address}]` : ip.address + }${port}` + ); + } + } + + #defaultLookup (origin, opts, cb) { + lookup( + origin.hostname, + { + all: true, + family: this.dualStack === false ? this.affinity : 0, + order: 'ipv4first' + }, + (err, addresses) => { + if (err) { + return cb(err) + } + + const results = new Map(); + + for (const addr of addresses) { + // On linux we found duplicates, we attempt to remove them with + // the latest record + results.set(`${addr.address}:${addr.family}`, addr); + } + + cb(null, results.values()); + } + ); + } + + #defaultPick (origin, hostnameRecords, affinity) { + let ip = null; + const { records, offset } = hostnameRecords; + + let family; + if (this.dualStack) { + if (affinity == null) { + // Balance between ip families + if (offset == null || offset === maxInt) { + hostnameRecords.offset = 0; + affinity = 4; + } else { + hostnameRecords.offset++; + affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4; + } + } + + if (records[affinity] != null && records[affinity].ips.length > 0) { + family = records[affinity]; + } else { + family = records[affinity === 4 ? 6 : 4]; + } + } else { + family = records[affinity]; + } + + // If no IPs we return null + if (family == null || family.ips.length === 0) { + return ip + } + + if (family.offset == null || family.offset === maxInt) { + family.offset = 0; + } else { + family.offset++; + } + + const position = family.offset % family.ips.length; + ip = family.ips[position] ?? null; + + if (ip == null) { + return ip + } + + if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms + // We delete expired records + // It is possible that they have different TTL, so we manage them individually + family.ips.splice(position, 1); + return this.pick(origin, hostnameRecords, affinity) + } + + return ip + } + + setRecords (origin, addresses) { + const timestamp = Date.now(); + const records = { records: { 4: null, 6: null } }; + for (const record of addresses) { + record.timestamp = timestamp; + if (typeof record.ttl === 'number') { + // The record TTL is expected to be in ms + record.ttl = Math.min(record.ttl, this.#maxTTL); + } else { + record.ttl = this.#maxTTL; + } + + const familyRecords = records.records[record.family] ?? { ips: [] }; + + familyRecords.ips.push(record); + records.records[record.family] = familyRecords; + } + + this.#records.set(origin.hostname, records); + } + + getHandler (meta, opts) { + return new DNSDispatchHandler(this, meta, opts) + } + } + + class DNSDispatchHandler extends DecoratorHandler { + #state = null + #opts = null + #dispatch = null + #handler = null + #origin = null + + constructor (state, { origin, handler, dispatch }, opts) { + super(handler); + this.#origin = origin; + this.#handler = handler; + this.#opts = { ...opts }; + this.#state = state; + this.#dispatch = dispatch; + } + + onError (err) { + switch (err.code) { + case 'ETIMEDOUT': + case 'ECONNREFUSED': { + if (this.#state.dualStack) { + // We delete the record and retry + this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => { + if (err) { + return this.#handler.onError(err) + } + + const dispatchOpts = { + ...this.#opts, + origin: newOrigin + }; + + this.#dispatch(dispatchOpts, this); + }); + + // if dual-stack disabled, we error out + return + } + + this.#handler.onError(err); + return + } + case 'ENOTFOUND': + this.#state.deleteRecord(this.#origin); + // eslint-disable-next-line no-fallthrough + default: + this.#handler.onError(err); + break + } + } + } + + dns = interceptorOpts => { + if ( + interceptorOpts?.maxTTL != null && + (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) + ) { + throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') + } + + if ( + interceptorOpts?.maxItems != null && + (typeof interceptorOpts?.maxItems !== 'number' || + interceptorOpts?.maxItems < 1) + ) { + throw new InvalidArgumentError( + 'Invalid maxItems. Must be a positive number and greater than zero' + ) + } + + if ( + interceptorOpts?.affinity != null && + interceptorOpts?.affinity !== 4 && + interceptorOpts?.affinity !== 6 + ) { + throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') + } + + if ( + interceptorOpts?.dualStack != null && + typeof interceptorOpts?.dualStack !== 'boolean' + ) { + throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') + } + + if ( + interceptorOpts?.lookup != null && + typeof interceptorOpts?.lookup !== 'function' + ) { + throw new InvalidArgumentError('Invalid lookup. Must be a function') + } + + if ( + interceptorOpts?.pick != null && + typeof interceptorOpts?.pick !== 'function' + ) { + throw new InvalidArgumentError('Invalid pick. Must be a function') + } + + const dualStack = interceptorOpts?.dualStack ?? true; + let affinity; + if (dualStack) { + affinity = interceptorOpts?.affinity ?? null; + } else { + affinity = interceptorOpts?.affinity ?? 4; + } + + const opts = { + maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms + lookup: interceptorOpts?.lookup ?? null, + pick: interceptorOpts?.pick ?? null, + dualStack, + affinity, + maxItems: interceptorOpts?.maxItems ?? Infinity + }; + + const instance = new DNSInstance(opts); + + return dispatch => { + return function dnsInterceptor (origDispatchOpts, handler) { + const origin = + origDispatchOpts.origin.constructor === URL + ? origDispatchOpts.origin + : new URL(origDispatchOpts.origin); + + if (isIP(origin.hostname) !== 0) { + return dispatch(origDispatchOpts, handler) + } + + instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { + if (err) { + return handler.onError(err) + } + + let dispatchOpts = null; + dispatchOpts = { + ...origDispatchOpts, + servername: origin.hostname, // For SNI on TLS + origin: newOrigin, + headers: { + host: origin.hostname, + ...origDispatchOpts.headers + } + }; + + dispatch( + dispatchOpts, + instance.getHandler({ origin, dispatch, handler }, origDispatchOpts) + ); + }); + + return true + } + } + }; + return dns; +} + +var headers; +var hasRequiredHeaders; + +function requireHeaders () { + if (hasRequiredHeaders) return headers; + hasRequiredHeaders = 1; + + const { kConstruct } = requireSymbols$4(); + const { kEnumerableProperty } = requireUtil$9(); + const { + iteratorMixin, + isValidHeaderName, + isValidHeaderValue + } = requireUtil$8(); + const { webidl } = requireWebidl(); + const assert = require$$0$4; + const util = require$$0$7; + + const kHeadersMap = Symbol('headers map'); + const kHeadersSortedMap = Symbol('headers map sorted'); + + /** + * @param {number} code + */ + function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ + function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length; + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j; + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i; + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) + } + + function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i]; + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]); + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object); + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]); + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ + function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value); + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + // Note: undici does not implement forbidden header names + if (getHeadersGuard(headers) === 'immutable') { + throw new TypeError('immutable') + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return getHeadersList(headers).append(name, value, false) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers + } + + function compareHeaderName (a, b) { + return a[0] < b[0] ? -1 : 1 + } + + class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]); + this[kHeadersSortedMap] = init[kHeadersSortedMap]; + this.cookies = init.cookies === null ? null : [...init.cookies]; + } else { + this[kHeadersMap] = new Map(init); + this[kHeadersSortedMap] = null; + } + } + + /** + * @see https://fetch.spec.whatwg.org/#header-list-contains + * @param {string} name + * @param {boolean} isLowerCase + */ + contains (name, isLowerCase) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + + return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase()) + } + + clear () { + this[kHeadersMap].clear(); + this[kHeadersSortedMap] = null; + this.cookies = null; + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-append + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + append (name, value, isLowerCase) { + this[kHeadersSortedMap] = null; + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = isLowerCase ? name : name.toLowerCase(); + const exists = this[kHeadersMap].get(lowercaseName); + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', '; + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }); + } else { + this[kHeadersMap].set(lowercaseName, { name, value }); + } + + if (lowercaseName === 'set-cookie') { + (this.cookies ??= []).push(value); + } + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-set + * @param {string} name + * @param {string} value + * @param {boolean} isLowerCase + */ + set (name, value, isLowerCase) { + this[kHeadersSortedMap] = null; + const lowercaseName = isLowerCase ? name : name.toLowerCase(); + + if (lowercaseName === 'set-cookie') { + this.cookies = [value]; + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }); + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-delete + * @param {string} name + * @param {boolean} isLowerCase + */ + delete (name, isLowerCase) { + this[kHeadersSortedMap] = null; + if (!isLowerCase) name = name.toLowerCase(); + + if (name === 'set-cookie') { + this.cookies = null; + } + + this[kHeadersMap].delete(name); + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-list-get + * @param {string} name + * @param {boolean} isLowerCase + * @returns {string | null} + */ + get (name, isLowerCase) { + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const { 0: name, 1: { value } } of this[kHeadersMap]) { + yield [name, value]; + } + } + + get entries () { + const headers = {}; + + if (this[kHeadersMap].size !== 0) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value; + } + } + + return headers + } + + rawValues () { + return this[kHeadersMap].values() + } + + get entriesList () { + const headers = []; + + if (this[kHeadersMap].size !== 0) { + for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) { + if (lowerName === 'set-cookie') { + for (const cookie of this.cookies) { + headers.push([name, cookie]); + } + } else { + headers.push([name, value]); + } + } + } + + return headers + } + + // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set + toSortedArray () { + const size = this[kHeadersMap].size; + const array = new Array(size); + // In most cases, you will use the fast-path. + // fast-path: Use binary insertion sort for small arrays. + if (size <= 32) { + if (size === 0) { + // If empty, it is an empty array. To avoid the first index assignment. + return array + } + // Improve performance by unrolling loop and avoiding double-loop. + // Double-loop-less version of the binary insertion sort. + const iterator = this[kHeadersMap][Symbol.iterator](); + const firstValue = iterator.next().value; + // set [name, value] to first index. + array[0] = [firstValue[0], firstValue[1].value]; + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(firstValue[1].value !== null); + for ( + let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; + i < size; + ++i + ) { + // get next value + value = iterator.next().value; + // set [name, value] to current index. + x = array[i] = [value[0], value[1].value]; + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(x[1] !== null); + left = 0; + right = i; + // binary search + while (left < right) { + // middle index + pivot = left + ((right - left) >> 1); + // compare header name + if (array[pivot][0] <= x[0]) { + left = pivot + 1; + } else { + right = pivot; + } + } + if (i !== pivot) { + j = i; + while (j > left) { + array[j] = array[--j]; + } + array[left] = x; + } + } + /* c8 ignore next 4 */ + if (!iterator.next().done) { + // This is for debugging and will never be called. + throw new TypeError('Unreachable') + } + return array + } else { + // This case would be a rare occurrence. + // slow-path: fallback + let i = 0; + for (const { 0: name, 1: { value } } of this[kHeadersMap]) { + array[i++] = [name, value]; + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + // 3.2.2. Assert: value is non-null. + assert(value !== null); + } + return array.sort(compareHeaderName) + } + } + } + + // https://fetch.spec.whatwg.org/#headers-class + class Headers { + #guard + #headersList + + constructor (init = undefined) { + webidl.util.markAsUncloneable(this); + + if (init === kConstruct) { + return + } + + this.#headersList = new HeadersList(); + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this.#guard = 'none'; + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init'); + fill(this, init); + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 2, 'Headers.append'); + + const prefix = 'Headers.append'; + name = webidl.converters.ByteString(name, prefix, 'name'); + value = webidl.converters.ByteString(value, prefix, 'value'); + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, 'Headers.delete'); + + const prefix = 'Headers.delete'; + name = webidl.converters.ByteString(name, prefix, 'name'); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this.#headersList.contains(name, false)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this.#headersList.delete(name, false); + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, 'Headers.get'); + + const prefix = 'Headers.get'; + name = webidl.converters.ByteString(name, prefix, 'name'); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this.#headersList.get(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, 'Headers.has'); + + const prefix = 'Headers.has'; + name = webidl.converters.ByteString(name, prefix, 'name'); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this.#headersList.contains(name, false) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 2, 'Headers.set'); + + const prefix = 'Headers.set'; + name = webidl.converters.ByteString(name, prefix, 'name'); + value = webidl.converters.ByteString(value, prefix, 'value'); + + // 1. Normalize value. + value = headerValueNormalize(value); + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix, + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix, + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this.#guard === 'immutable') { + throw new TypeError('immutable') + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this.#headersList.set(name, value, false); + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers); + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this.#headersList.cookies; + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this.#headersList[kHeadersSortedMap]) { + return this.#headersList[kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = []; + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = this.#headersList.toSortedArray(); + + const cookies = this.#headersList.cookies; + + // fast-path + if (cookies === null || cookies.length === 1) { + // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` + return (this.#headersList[kHeadersSortedMap] = names) + } + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const { 0: name, 1: value } = names[i]; + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]); + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + // Note: This operation was done by `HeadersList#toSortedArray`. + + // 3. Append (name, value) to headers. + headers.push([name, value]); + } + } + + // 4. Return headers. + return (this.#headersList[kHeadersSortedMap] = headers) + } + + [util.inspect.custom] (depth, options) { + options.depth ??= depth; + + return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` + } + + static getHeadersGuard (o) { + return o.#guard + } + + static setHeadersGuard (o, guard) { + o.#guard = guard; + } + + static getHeadersList (o) { + return o.#headersList + } + + static setHeadersList (o, list) { + o.#headersList = list; + } + } + + const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers; + Reflect.deleteProperty(Headers, 'getHeadersGuard'); + Reflect.deleteProperty(Headers, 'setHeadersGuard'); + Reflect.deleteProperty(Headers, 'getHeadersList'); + Reflect.deleteProperty(Headers, 'setHeadersList'); + + iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1); + + Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } + }); + + webidl.converters.HeadersInit = function (V, prefix, argument) { + if (webidl.util.Type(V) === 'Object') { + const iterator = Reflect.get(V, Symbol.iterator); + + // A work-around to ensure we send the properly-cased Headers when V is a Headers object. + // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. + if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object + try { + return getHeadersList(V).entriesList + } catch { + // fall-through + } + } + + if (typeof iterator === 'function') { + return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) + } + + return webidl.converters['record'](V, prefix, argument) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + }; + + headers = { + fill, + // for test. + compareHeaderName, + Headers, + HeadersList, + getHeadersGuard, + setHeadersGuard, + setHeadersList, + getHeadersList + }; + return headers; +} + +var response; +var hasRequiredResponse; + +function requireResponse () { + if (hasRequiredResponse) return response; + hasRequiredResponse = 1; + + const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = requireHeaders(); + const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = requireBody(); + const util = requireUtil$9(); + const nodeUtil = require$$0$7; + const { kEnumerableProperty } = util; + const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode, + environmentSettingsObject: relevantRealm + } = requireUtil$8(); + const { + redirectStatusSet, + nullBodyStatus + } = requireConstants$2(); + const { kState, kHeaders } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { FormData } = requireFormdata(); + const { URLSerializer } = requireDataUrl(); + const { kConstruct } = requireSymbols$4(); + const assert = require$$0$4; + const { types } = require$$0$7; + + const textEncoder = new TextEncoder('utf-8'); + + // https://fetch.spec.whatwg.org/#response-class + class Response { + // Creates network error Response. + static error () { + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = fromInnerResponse(makeNetworkError(), 'immutable'); + + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, 'Response.json'); + + if (init !== null) { + init = webidl.converters.ResponseInit(init); + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ); + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes); + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'response'); + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }); + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + webidl.argumentLengthCheck(arguments, 1, 'Response.redirect'); + + url = webidl.converters.USVString(url); + status = webidl.converters['unsigned short'](status); + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL; + try { + parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl); + } catch (err) { + throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError(`Invalid status code ${status}`) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = fromInnerResponse(makeResponse({}), 'immutable'); + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status; + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)); + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value, true); + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + webidl.util.markAsUncloneable(this); + if (body === kConstruct) { + return + } + + if (body !== null) { + body = webidl.converters.BodyInit(body); + } + + init = webidl.converters.ResponseInit(init); + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}); + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct); + setHeadersGuard(this[kHeaders], 'response'); + setHeadersList(this[kHeaders], this[kState].headersList); + + // 3. Let bodyWithType be null. + let bodyWithType = null; + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body); + bodyWithType = { body: extractedBody, type }; + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType); + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response); + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response); + + const urlList = this[kState].urlList; + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null; + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response); + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response); + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response); + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response); + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response); + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response); + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response); + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response); + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]); + + // Note: To re-register because of a new stream. + if (hasFinalizationRegistry && this[kState].body?.stream) { + streamRegistry.register(this, new WeakRef(this[kState].body.stream)); + } + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders])) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2; + } + + options.colors ??= true; + + const properties = { + status: this.status, + statusText: this.statusText, + headers: this.headers, + body: this.body, + bodyUsed: this.bodyUsed, + ok: this.ok, + redirected: this.redirected, + type: this.type, + url: this.url + }; + + return `Response ${nodeUtil.formatWithOptions(options, properties)}` + } + } + + mixinBody(Response); + + Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } + }); + + Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty + }); + + // https://fetch.spec.whatwg.org/#concept-response-clone + function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }); + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(newResponse, response.body); + } + + // 4. Return newResponse. + return newResponse + } + + function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init?.headersList + ? new HeadersList(init?.headersList) + : new HeadersList(), + urlList: init?.urlList ? [...init.urlList] : [] + } + } + + function makeNetworkError (reason) { + const isError = isErrorLike(reason); + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) + } + + // @see https://fetch.spec.whatwg.org/#concept-network-error + function isNetworkError (response) { + return ( + // A network error is a response whose type is "error", + response.type === 'error' && + // status is 0 + response.status === 0 + ) + } + + function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + }; + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)); + target[p] = value; + return true + } + }) + } + + // https://fetch.spec.whatwg.org/#concept-filtered-response + function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false); + } + } + + // https://fetch.spec.whatwg.org/#appropriate-network-error + function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)); + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) + } + + // https://whatpr.org/fetch/1392.html#initialize-a-response + function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status; + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText; + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers); + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: `Invalid response status code ${response.status}` + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body; + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('content-type', true)) { + response[kState].headersList.append('content-type', body.type, true); + } + } + } + + /** + * @see https://fetch.spec.whatwg.org/#response-create + * @param {any} innerResponse + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Response} + */ + function fromInnerResponse (innerResponse, guard) { + const response = new Response(kConstruct); + response[kState] = innerResponse; + response[kHeaders] = new Headers(kConstruct); + setHeadersList(response[kHeaders], innerResponse.headersList); + setHeadersGuard(response[kHeaders], guard); + + if (hasFinalizationRegistry && innerResponse.body?.stream) { + // If the target (response) is reclaimed, the cleanup callback may be called at some point with + // the held value provided for it (innerResponse.body.stream). The held value can be any value: + // a primitive or an object, even undefined. If the held value is an object, the registry keeps + // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + streamRegistry.register(response, new WeakRef(innerResponse.body.stream)); + } + + return response + } + + webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream + ); + + webidl.converters.FormData = webidl.interfaceConverter( + FormData + ); + + webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams + ); + + // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit + webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, name) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, prefix, name, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { + return webidl.converters.BufferSource(V, prefix, name) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, prefix, name, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V, prefix, name) + } + + return webidl.converters.DOMString(V, prefix, name) + }; + + // https://fetch.spec.whatwg.org/#bodyinit + webidl.converters.BodyInit = function (V, prefix, argument) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V, prefix, argument) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) + }; + + webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: () => 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: () => '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } + ]); + + response = { + isNetworkError, + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse, + fromInnerResponse + }; + return response; +} + +var dispatcherWeakref; +var hasRequiredDispatcherWeakref; + +function requireDispatcherWeakref () { + if (hasRequiredDispatcherWeakref) return dispatcherWeakref; + hasRequiredDispatcherWeakref = 1; + + const { kConnected, kSize } = requireSymbols$4(); + + class CompatWeakRef { + constructor (value) { + this.value = value; + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } + } + + class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer; + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key); + } + }); + } + } + + unregister (key) {} + } + + dispatcherWeakref = function () { + // FIXME: remove workaround when the Node bug is backported to v18 + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) { + process._rawDebug('Using compatibility WeakRef and FinalizationRegistry'); + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { WeakRef, FinalizationRegistry } + }; + return dispatcherWeakref; +} + +/* globals AbortController */ + +var request$1; +var hasRequiredRequest; + +function requireRequest () { + if (hasRequiredRequest) return request$1; + hasRequiredRequest = 1; + + const { extractBody, mixinBody, cloneBody, bodyUnusable } = requireBody(); + const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = requireHeaders(); + const { FinalizationRegistry } = requireDispatcherWeakref()(); + const util = requireUtil$9(); + const nodeUtil = require$$0$7; + const { + isValidHTTPToken, + sameOrigin, + environmentSettingsObject + } = requireUtil$8(); + const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex + } = requireConstants$2(); + const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util; + const { kHeaders, kSignal, kState, kDispatcher } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { URLSerializer } = requireDataUrl(); + const { kConstruct } = requireSymbols$4(); + const assert = require$$0$4; + const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require$$8; + + const kAbortController = Symbol('abortController'); + + const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort); + }); + + const dependentControllerMap = new WeakMap(); + + function buildAbort (acRef) { + return abort + + function abort () { + const ac = acRef.deref(); + if (ac !== undefined) { + // Currently, there is a problem with FinalizationRegistry. + // https://github.com/nodejs/node/issues/49344 + // https://github.com/nodejs/node/issues/47748 + // In the case of abort, the first step is to unregister from it. + // If the controller can refer to it, it is still registered. + // It will be removed in the future. + requestFinalizer.unregister(abort); + + // Unsubscribe a listener. + // FinalizationRegistry will no longer be called, so this must be done. + this.removeEventListener('abort', abort); + + ac.abort(this.reason); + + const controllerList = dependentControllerMap.get(ac.signal); + + if (controllerList !== undefined) { + if (controllerList.size !== 0) { + for (const ref of controllerList) { + const ctrl = ref.deref(); + if (ctrl !== undefined) { + ctrl.abort(this.reason); + } + } + controllerList.clear(); + } + dependentControllerMap.delete(ac.signal); + } + } + } + } + + let patchMethodWarning = false; + + // https://fetch.spec.whatwg.org/#request-class + class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + webidl.util.markAsUncloneable(this); + if (input === kConstruct) { + return + } + + const prefix = 'Request constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + input = webidl.converters.RequestInfo(input, prefix, 'input'); + init = webidl.converters.RequestInit(init, prefix, 'init'); + + // 1. Let request be null. + let request = null; + + // 2. Let fallbackMode be null. + let fallbackMode = null; + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = environmentSettingsObject.settingsObject.baseUrl; + + // 4. Let signal be null. + let signal = null; + + // 5. If input is a string, then: + if (typeof input === 'string') { + this[kDispatcher] = init.dispatcher; + + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL; + try { + parsedURL = new URL(input, baseUrl); + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }); + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors'; + } else { + this[kDispatcher] = init.dispatcher || input[kDispatcher]; + + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request); + + // 8. Set request to input’s request. + request = input[kState]; + + // 9. Set signal to input’s signal. + signal = input[kSignal]; + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = environmentSettingsObject.settingsObject.origin; + + // 8. Let window be "client". + let window = 'client'; + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window; + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window'; + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: environmentSettingsObject.settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }); + + const initHasKey = Object.keys(init).length !== 0; + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin'; + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false; + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false; + + // 4. Set request’s origin to "client". + request.origin = 'client'; + + // 5. Set request’s referrer to "client" + request.referrer = 'client'; + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = ''; + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1]; + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url]; + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer; + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer'; + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer; + try { + parsedReferrer = new URL(referrer, baseUrl); + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) + ) { + request.referrer = 'client'; + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer; + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy; + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode; + if (init.mode !== undefined) { + mode = init.mode; + } else { + mode = fallbackMode; + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode; + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials; + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache; + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect; + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity); + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive); + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method; + + const mayBeNormalized = normalizedMethodRecords[method]; + + if (mayBeNormalized !== undefined) { + // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones + request.method = mayBeNormalized; + } else { + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + const upperCase = method.toUpperCase(); + + if (forbiddenMethodsSet.has(upperCase)) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + // https://fetch.spec.whatwg.org/#concept-method-normalize + // Note: must be in uppercase + method = normalizedMethodRecordsBase[upperCase] ?? method; + + // 4. Set request’s method to method. + request.method = method; + } + + if (!patchMethodWarning && request.method === 'patch') { + process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { + code: 'UNDICI-FETCH-patch' + }); + + patchMethodWarning = true; + } + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal; + } + + // 27. Set this’s request to request. + this[kState] = request; + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController(); + this[kSignal] = ac.signal; + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason); + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac; + + const acRef = new WeakRef(ac); + const abort = buildAbort(acRef); + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(1500, signal); + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(1500, signal); + } + } catch {} + + util.addAbortListener(signal, abort); + // The third argument must be a registry key to be unregistered. + // Without it, you cannot unregister. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + // abort is used as the unregister key. (because it is unique) + requestFinalizer.register(ac, { signal, abort }, abort); + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct); + setHeadersList(this[kHeaders], request.headersList); + setHeadersGuard(this[kHeaders], 'request'); + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + setHeadersGuard(this[kHeaders], 'request-no-cors'); + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = getHeadersList(this[kHeaders]); + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList); + + // 3. Empty this’s headers’s header list. + headersList.clear(); + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const { name, value } of headers.rawValues()) { + headersList.append(name, value, false); + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies; + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers); + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null; + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null; + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ); + initBody = extractedBody; + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) { + this[kHeaders].append('content-type', contentType); + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody; + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true; + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody; + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (bodyUnusable(input)) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream(); + inputBody.stream.pipeThrough(identityTransform); + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + }; + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody; + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request); + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request); + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request); + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request); + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request); + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request); + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request); + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request); + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request); + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request); + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request); + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request); + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-forward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request); + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request); + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request); + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request); + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request); + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request); + + // 1. If this is unusable, then throw a TypeError. + if (bodyUnusable(this)) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]); + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController(); + if (this.signal.aborted) { + ac.abort(this.signal.reason); + } else { + let list = dependentControllerMap.get(this.signal); + if (list === undefined) { + list = new Set(); + dependentControllerMap.set(this.signal, list); + } + const acRef = new WeakRef(ac); + list.add(acRef); + util.addAbortListener( + ac.signal, + buildAbort(acRef) + ); + } + + // 4. Return clonedRequestObject. + return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders])) + } + + [nodeUtil.inspect.custom] (depth, options) { + if (options.depth === null) { + options.depth = 2; + } + + options.colors ??= true; + + const properties = { + method: this.method, + url: this.url, + headers: this.headers, + destination: this.destination, + referrer: this.referrer, + referrerPolicy: this.referrerPolicy, + mode: this.mode, + credentials: this.credentials, + cache: this.cache, + redirect: this.redirect, + integrity: this.integrity, + keepalive: this.keepalive, + isReloadNavigation: this.isReloadNavigation, + isHistoryNavigation: this.isHistoryNavigation, + signal: this.signal + }; + + return `Request ${nodeUtil.formatWithOptions(options, properties)}` + } + } + + mixinBody(Request); + + // https://fetch.spec.whatwg.org/#requests + function makeRequest (init) { + return { + method: init.method ?? 'GET', + localURLsOnly: init.localURLsOnly ?? false, + unsafeRequest: init.unsafeRequest ?? false, + body: init.body ?? null, + client: init.client ?? null, + reservedClient: init.reservedClient ?? null, + replacesClientId: init.replacesClientId ?? '', + window: init.window ?? 'client', + keepalive: init.keepalive ?? false, + serviceWorkers: init.serviceWorkers ?? 'all', + initiator: init.initiator ?? '', + destination: init.destination ?? '', + priority: init.priority ?? null, + origin: init.origin ?? 'client', + policyContainer: init.policyContainer ?? 'client', + referrer: init.referrer ?? 'client', + referrerPolicy: init.referrerPolicy ?? '', + mode: init.mode ?? 'no-cors', + useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, + credentials: init.credentials ?? 'same-origin', + useCredentials: init.useCredentials ?? false, + cache: init.cache ?? 'default', + redirect: init.redirect ?? 'follow', + integrity: init.integrity ?? '', + cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', + parserMetadata: init.parserMetadata ?? '', + reloadNavigation: init.reloadNavigation ?? false, + historyNavigation: init.historyNavigation ?? false, + userActivation: init.userActivation ?? false, + taintedOrigin: init.taintedOrigin ?? false, + redirectCount: init.redirectCount ?? 0, + responseTainting: init.responseTainting ?? 'basic', + preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, + done: init.done ?? false, + timingAllowFailed: init.timingAllowFailed ?? false, + urlList: init.urlList, + url: init.urlList[0], + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + } + + // https://fetch.spec.whatwg.org/#concept-request-clone + function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }); + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(newRequest, request.body); + } + + // 3. Return newRequest. + return newRequest + } + + /** + * @see https://fetch.spec.whatwg.org/#request-create + * @param {any} innerRequest + * @param {AbortSignal} signal + * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard + * @returns {Request} + */ + function fromInnerRequest (innerRequest, signal, guard) { + const request = new Request(kConstruct); + request[kState] = innerRequest; + request[kSignal] = signal; + request[kHeaders] = new Headers(kConstruct); + setHeadersList(request[kHeaders], innerRequest.headersList); + setHeadersGuard(request[kHeaders], guard); + return request + } + + Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } + }); + + webidl.converters.Request = webidl.interfaceConverter( + Request + ); + + // https://fetch.spec.whatwg.org/#requestinfo + webidl.converters.RequestInfo = function (V, prefix, argument) { + if (typeof V === 'string') { + return webidl.converters.USVString(V, prefix, argument) + } + + if (V instanceof Request) { + return webidl.converters.Request(V, prefix, argument) + } + + return webidl.converters.USVString(V, prefix, argument) + }; + + webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal + ); + + // https://fetch.spec.whatwg.org/#requestinit + webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + 'RequestInit', + 'signal', + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + }, + { + key: 'dispatcher', // undici specific option + converter: webidl.converters.any + } + ]); + + request$1 = { Request, makeRequest, fromInnerRequest, cloneRequest }; + return request$1; +} + +var fetch_1; +var hasRequiredFetch; + +function requireFetch () { + if (hasRequiredFetch) return fetch_1; + hasRequiredFetch = 1; + + const { + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse, + fromInnerResponse + } = requireResponse(); + const { HeadersList } = requireHeaders(); + const { Request, cloneRequest } = requireRequest(); + const zlib = require$$1$5; + const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme, + clampAndCoarsenConnectionTimingInfo, + simpleRangeHeaderValue, + buildContentRange, + createInflate, + extractMimeType + } = requireUtil$8(); + const { kState, kDispatcher } = requireSymbols$3(); + const assert = require$$0$4; + const { safelyExtractBody, extractBody } = requireBody(); + const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet + } = requireConstants$2(); + const EE = require$$8; + const { Readable, pipeline, finished } = require$$0$5; + const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = requireUtil$9(); + const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = requireDataUrl(); + const { getGlobalDispatcher } = requireGlobal(); + const { webidl } = requireWebidl(); + const { STATUS_CODES } = require$$2$1; + const GET_OR_HEAD = ['GET', 'HEAD']; + + const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici'; + + /** @type {import('buffer').resolveObjectURL} */ + let resolveObjectURL; + + class Fetch extends EE { + constructor (dispatcher) { + super(); + + this.dispatcher = dispatcher; + this.connection = null; + this.dump = false; + this.state = 'ongoing'; + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated'; + this.connection?.destroy(reason); + this.emit('terminated', reason); + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted'; + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError'); + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error; + + this.connection?.destroy(error); + this.emit('terminated', error); + } + } + + function handleFetchDone (response) { + finalizeAndReportTiming(response, 'fetch'); + } + + // https://fetch.spec.whatwg.org/#fetch-method + function fetch (input, init = undefined) { + webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch'); + + // 1. Let p be a new promise. + let p = createDeferredPromise(); + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject; + + try { + requestObject = new Request(input, init); + } catch (e) { + p.reject(e); + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState]; + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason); + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject; + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none'; + } + + // 7. Let responseObject be null. + let responseObject = null; + + // 8. Let relevantRealm be this’s relevant Realm. + + // 9. Let locallyAborted be false. + let locallyAborted = false; + + // 10. Let controller be null. + let controller = null; + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true; + + // 2. Assert: controller is non-null. + assert(controller != null); + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason); + + const realResponse = responseObject?.deref(); + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, realResponse, requestObject.signal.reason); + } + ); + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + // see function handleFetchDone + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason); + return + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject(new TypeError('fetch failed', { cause: response.error })); + return + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new WeakRef(fromInnerResponse(response, 'immutable')); + + // 5. Resolve p with responseObject. + p.resolve(responseObject.deref()); + p = null; + }; + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: requestObject[kDispatcher] // undici + }); + + // 14. Return p. + return p.promise + } + + // https://fetch.spec.whatwg.org/#finalize-and-report-timing + function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0]; + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo; + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState; + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }); + + // 2. Set cacheState to the empty string. + cacheState = ''; + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime(); + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo; + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL.href, + initiatorType, + globalThis, + cacheState + ); + } + + // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing + const markResourceTiming = performance.markResourceTiming; + + // https://fetch.spec.whatwg.org/#abort-fetch + function abortFetch (p, request, responseObject, error) { + // 1. Reject promise with error. + if (p) { + // We might have already resolved the promise at this stage + p.reject(error); + } + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }); + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState]; + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }); + } + } + + // https://fetch.spec.whatwg.org/#fetching + function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher = getGlobalDispatcher() // undici + }) { + // Ensure that the dispatcher is set accordingly + assert(dispatcher); + + // 1. Let taskDestination be null. + let taskDestination = null; + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false; + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject; + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability; + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability); + const timingInfo = createOpaqueTimingInfo({ + startTime: currentTime + }); + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + }; + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream); + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window'; + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + request.origin = request.client.origin; + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ); + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer(); + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept', true)) { + // 1. Let value be `*/*`. + const value = '*/*'; + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value, true); + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language', true)) { + request.headersList.append('accept-language', '*', true); + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) ; + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) ; + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err); + }); + + // 17. Return fetchParam's controller + return fetchParams.controller + } + + // https://fetch.spec.whatwg.org/#concept-main-fetch + async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only'); + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request); + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port'); + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy; + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request); + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request); + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic'; + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque'; + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors'; + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })(); + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') ; + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic'); + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors'); + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque'); + } else { + assert(false); + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse; + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList); + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true; + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range', true) + ) { + response = internalResponse = makeNetworkError(); + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null; + fetchParams.controller.dump = true; + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)); + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error); + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch'); + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0]; + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response); + }; + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError); + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response); + } + } + + // https://fetch.spec.whatwg.org/#concept-scheme-fetch + // given a fetch params fetchParams + function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams; + + const { protocol: scheme } = requestCurrentURL(request); + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require$$0$3.resolveObjectURL; + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request); + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blob = resolveObjectURL(blobURLEntry.toString()); + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blob)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let blob be blobURLEntry’s object. + // Note: done above + + // 4. Let response be a new response. + const response = makeResponse(); + + // 5. Let fullLength be blob’s size. + const fullLength = blob.size; + + // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. + const serializedFullLength = isomorphicEncode(`${fullLength}`); + + // 7. Let type be blob’s type. + const type = blob.type; + + // 8. If request’s header list does not contain `Range`: + // 9. Otherwise: + if (!request.headersList.contains('range', true)) { + // 1. Let bodyWithType be the result of safely extracting blob. + // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. + // In node, this can only ever be a Blob. Therefore we can safely + // use extractBody directly. + const bodyWithType = extractBody(blob); + + // 2. Set response’s status message to `OK`. + response.statusText = 'OK'; + + // 3. Set response’s body to bodyWithType’s body. + response.body = bodyWithType[0]; + + // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». + response.headersList.set('content-length', serializedFullLength, true); + response.headersList.set('content-type', type, true); + } else { + // 1. Set response’s range-requested flag. + response.rangeRequested = true; + + // 2. Let rangeHeader be the result of getting `Range` from request’s header list. + const rangeHeader = request.headersList.get('range', true); + + // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. + const rangeValue = simpleRangeHeaderValue(rangeHeader, true); + + // 4. If rangeValue is failure, then return a network error. + if (rangeValue === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 5. Let (rangeStart, rangeEnd) be rangeValue. + let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue; + + // 6. If rangeStart is null: + // 7. Otherwise: + if (rangeStart === null) { + // 1. Set rangeStart to fullLength − rangeEnd. + rangeStart = fullLength - rangeEnd; + + // 2. Set rangeEnd to rangeStart + rangeEnd − 1. + rangeEnd = rangeStart + rangeEnd - 1; + } else { + // 1. If rangeStart is greater than or equal to fullLength, then return a network error. + if (rangeStart >= fullLength) { + return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) + } + + // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set + // rangeEnd to fullLength − 1. + if (rangeEnd === null || rangeEnd >= fullLength) { + rangeEnd = fullLength - 1; + } + } + + // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, + // rangeEnd + 1, and type. + const slicedBlob = blob.slice(rangeStart, rangeEnd, type); + + // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. + // Note: same reason as mentioned above as to why we use extractBody + const slicedBodyWithType = extractBody(slicedBlob); + + // 10. Set response’s body to slicedBodyWithType’s body. + response.body = slicedBodyWithType[0]; + + // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. + const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`); + + // 12. Let contentRange be the result of invoking build a content range given rangeStart, + // rangeEnd, and fullLength. + const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength); + + // 13. Set response’s status to 206. + response.status = 206; + + // 14. Set response’s status message to `Partial Content`. + response.statusText = 'Partial Content'; + + // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), + // (`Content-Type`, type), (`Content-Range`, contentRange) ». + response.headersList.set('content-length', serializedSlicedLength, true); + response.headersList.set('content-type', type, true); + response.headersList.set('content-range', contentRange, true); + } + + // 10. Return response. + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request); + const dataURLStruct = dataURLProcessor(currentURL); + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType); + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } + } + + // https://fetch.spec.whatwg.org/#finalize-response + function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true; + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)); + } + } + + // https://fetch.spec.whatwg.org/#fetch-finale + function fetchFinale (fetchParams, response) { + // 1. Let timingInfo be fetchParams’s timing info. + let timingInfo = fetchParams.timingInfo; + + // 2. If response is not a network error and fetchParams’s request’s client is a secure context, + // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting + // `Server-Timing` from response’s internal response’s header list. + // TODO + + // 3. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Let unsafeEndTime be the unsafe shared current time. + const unsafeEndTime = Date.now(); // ? + + // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s + // full timing info to fetchParams’s timing info. + if (fetchParams.request.destination === 'document') { + fetchParams.controller.fullTimingInfo = timingInfo; + } + + // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: + fetchParams.controller.reportTimingSteps = () => { + // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. + if (fetchParams.request.url.protocol !== 'https:') { + return + } + + // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. + timingInfo.endTime = unsafeEndTime; + + // 3. Let cacheState be response’s cache state. + let cacheState = response.cacheState; + + // 4. Let bodyInfo be response’s body info. + const bodyInfo = response.bodyInfo; + + // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an + // opaque timing info for timingInfo and set cacheState to the empty string. + if (!response.timingAllowPassed) { + timingInfo = createOpaqueTimingInfo(timingInfo); + + cacheState = ''; + } + + // 6. Let responseStatus be 0. + let responseStatus = 0; + + // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: + if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { + // 1. Set responseStatus to response’s status. + responseStatus = response.status; + + // 2. Let mimeType be the result of extracting a MIME type from response’s header list. + const mimeType = extractMimeType(response.headersList); + + // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. + if (mimeType !== 'failure') { + bodyInfo.contentType = minimizeSupportedMimeType(mimeType); + } + } + + // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, + // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, + // and responseStatus. + if (fetchParams.request.initiatorType != null) { + // TODO: update markresourcetiming + markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus); + } + }; + + // 4. Let processResponseEndOfBodyTask be the following steps: + const processResponseEndOfBodyTask = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true; + + // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process + // response end-of-body given response. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)); + } + + // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s + // global object is fetchParams’s task destination, then run fetchParams’s controller’s report + // timing steps given fetchParams’s request’s client’s global object. + if (fetchParams.request.initiatorType != null) { + fetchParams.controller.reportTimingSteps(); + } + }; + + // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination + queueMicrotask(() => processResponseEndOfBodyTask()); + }; + + // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s + // process response given response, with fetchParams’s task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => { + fetchParams.processResponse(response); + fetchParams.processResponse = null; + }); + } + + // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. + const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response); + + // 6. If internalResponse’s body is null, then run processResponseEndOfBody. + // 7. Otherwise: + if (internalResponse.body == null) { + processResponseEndOfBody(); + } else { + // mcollina: all the following steps of the specs are skipped. + // The internal transform stream is not needed. + // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 + + // 1. Let transformStream be a new TransformStream. + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm + // set to processResponseEndOfBody. + // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. + + finished(internalResponse.body.stream, () => { + processResponseEndOfBody(); + }); + } + } + + // https://fetch.spec.whatwg.org/#http-fetch + async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. Let actualResponse be null. + let actualResponse = null; + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') ; + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none'; + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams); + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true; + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy(undefined, false); + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect'); + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse; + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response); + } else { + assert(false); + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo; + + // 10. Return response. + return response + } + + // https://fetch.spec.whatwg.org/#http-redirect-fetch + function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response; + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL; + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ); + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1; + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET'; + request.body = null; + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName); + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization', true); + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true); + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie', true); + request.headersList.delete('host', true); + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null); + request.body = safelyExtractBody(request.body.source)[0]; + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime; + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL); + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse); + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) + } + + // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch + async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false + ) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let httpFetchParams be null. + let httpFetchParams = null; + + // 3. Let httpRequest be null. + let httpRequest = null; + + // 4. Let response be null. + let response = null; + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams; + httpRequest = request; + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = cloneRequest(request); + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams }; + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest; + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic'); + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null; + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null; + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0'; + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`); + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue, true); + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) ; + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true); + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest); + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest); + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent', true)) { + httpRequest.headersList.append('user-agent', defaultUserAgent); + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since', true) || + httpRequest.headersList.contains('if-none-match', true) || + httpRequest.headersList.contains('if-unmodified-since', true) || + httpRequest.headersList.contains('if-match', true) || + httpRequest.headersList.contains('if-range', true)) + ) { + httpRequest.cache = 'no-store'; + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control', true) + ) { + httpRequest.headersList.append('cache-control', 'max-age=0', true); + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma', true)) { + httpRequest.headersList.append('pragma', 'no-cache', true); + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control', true)) { + httpRequest.headersList.append('cache-control', 'no-cache', true); + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range', true)) { + httpRequest.headersList.append('accept-encoding', 'identity', true); + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding', true)) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true); + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true); + } + } + + httpRequest.headersList.delete('host', true); + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + { + httpRequest.cache = 'no-store'; + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') ; + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.cache === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ); + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) ; + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse; + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList]; + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range', true)) { + response.rangeRequested = true; + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials; + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy(); + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ); + } + + // 18. Return response. + return response + } + + // https://fetch.spec.whatwg.org/#http-network-fetch + async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false + ) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed); + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err, abort = true) { + if (!this.destroyed) { + this.destroyed = true; + if (abort) { + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')); + } + } + } + }; + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + { + request.cache = 'no-store'; + } + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') ; + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null; + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()); + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes; + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength); + }; + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody(); + } + }; + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort(); + } else { + fetchParams.controller.terminate(e); + } + }; + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes); + } + processEndOfBody(); + } catch (err) { + processBodyError(err); + } + })(); + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }); + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }); + } else { + const iterator = body[Symbol.asyncIterator](); + fetchParams.controller.next = () => iterator.next(); + + response = makeResponse({ status, statusText, headersList }); + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy(); + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = async () => { + await fetchParams.controller.resume(); + }; + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + // If the aborted fetch was already terminated, then we do not + // need to do anything. + if (!isCancelled(fetchParams)) { + fetchParams.controller.abort(reason); + } + }; + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm. + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller; + }, + async pull (controller) { + await pullAlgorithm(); + }, + async cancel (reason) { + await cancelAlgorithm(reason); + }, + type: 'bytes' + } + ); + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream, source: null, length: null }; + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.onAborted = onAborted; + fetchParams.controller.on('terminated', onAborted); + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes; + let isFailure; + try { + const { done, value } = await fetchParams.controller.next(); + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value; + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined; + } else { + bytes = err; + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true; + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller); + + finalizeResponse(fetchParams, response); + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0; + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes); + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + const buffer = new Uint8Array(bytes); + if (buffer.byteLength) { + fetchParams.controller.controller.enqueue(buffer); + } + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate(); + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (fetchParams.controller.controller.desiredSize <= 0) { + return + } + } + }; + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true; + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ); + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })); + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy(); + } + + // 20. Return response. + return response + + function dispatch ({ body }) { + const url = requestCurrentURL(request); + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher; + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller; + + // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen + // connection timing info with connection’s timing info, timingInfo’s post-redirect start + // time, and fetchParams’s cross-origin isolated capability. + // TODO: implement connection timing + timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability); + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')); + } else { + fetchParams.controller.on('terminated', abort); + this.abort = connection.abort = abort; + } + + // Set timingInfo’s final network-request start time to the coarsened shared current time given + // fetchParams’s cross-origin isolated capability. + timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + }, + + onResponseStarted () { + // Set timingInfo’s final network-response start time to the coarsened shared current + // time given fetchParams’s cross-origin isolated capability, immediately after the + // user agent’s HTTP parser receives the first byte of the response (e.g., frame header + // bytes for HTTP/2 or response status line for HTTP/1.x). + timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + }, + + onHeaders (status, rawHeaders, resume, statusText) { + if (status < 200) { + return + } + + let location = ''; + + const headersList = new HeadersList(); + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true); + } + location = headersList.get('location', true); + + this.body = new Readable({ read: resume }); + + const decoders = []; + + const willFollow = location && request.redirect === 'follow' && + redirectStatusSet.has(status); + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + const contentEncoding = headersList.get('content-encoding', true); + // "All content-coding values are case-insensitive..." + /** @type {string[]} */ + const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []; + + // Limit the number of content-encodings to prevent resource exhaustion. + // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). + const maxContentEncodings = 5; + if (codings.length > maxContentEncodings) { + reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`)); + return true + } + + for (let i = codings.length - 1; i >= 0; --i) { + const coding = codings[i].trim(); + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })); + } else if (coding === 'deflate') { + decoders.push(createInflate({ + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })); + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress({ + flush: zlib.constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH + })); + } else { + decoders.length = 0; + break + } + } + } + + const onError = this.onError.bind(this); + + resolve({ + status, + statusText, + headersList, + body: decoders.length + ? pipeline(this.body, ...decoders, (err) => { + if (err) { + this.onError(err); + } + }).on('error', onError) + : this.body.on('error', onError) + }); + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk; + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength; + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort); + } + + if (fetchParams.controller.onAborted) { + fetchParams.controller.off('terminated', fetchParams.controller.onAborted); + } + + fetchParams.controller.ended = true; + + this.body.push(null); + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort); + } + + this.body?.destroy(error); + + fetchParams.controller.terminate(error); + + reject(error); + }, + + onUpgrade (status, rawHeaders, socket) { + if (status !== 101) { + return + } + + const headersList = new HeadersList(); + + for (let i = 0; i < rawHeaders.length; i += 2) { + headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true); + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList, + socket + }); + + return true + } + } + )) + } + } + + fetch_1 = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming + }; + return fetch_1; +} + +var symbols$2; +var hasRequiredSymbols$2; + +function requireSymbols$2 () { + if (hasRequiredSymbols$2) return symbols$2; + hasRequiredSymbols$2 = 1; + + symbols$2 = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') + }; + return symbols$2; +} + +var progressevent; +var hasRequiredProgressevent; + +function requireProgressevent () { + if (hasRequiredProgressevent) return progressevent; + hasRequiredProgressevent = 1; + + const { webidl } = requireWebidl(); + + const kState = Symbol('ProgressEvent state'); + + /** + * @see https://xhr.spec.whatwg.org/#progressevent + */ + class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type'); + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}); + + super(type, eventInitDict); + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + }; + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].total + } + } + + webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: () => 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: () => 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } + ]); + + progressevent = { + ProgressEvent + }; + return progressevent; +} + +var encoding; +var hasRequiredEncoding; + +function requireEncoding () { + if (hasRequiredEncoding) return encoding; + hasRequiredEncoding = 1; + + /** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ + function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } + } + + encoding = { + getEncoding + }; + return encoding; +} + +var util$6; +var hasRequiredUtil$6; + +function requireUtil$6 () { + if (hasRequiredUtil$6) return util$6; + hasRequiredUtil$6 = 1; + + const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired + } = requireSymbols$2(); + const { ProgressEvent } = requireProgressevent(); + const { getEncoding } = requireEncoding(); + const { serializeAMimeType, parseMIMEType } = requireDataUrl(); + const { types } = require$$0$7; + const { StringDecoder } = require$$5$4; + const { btoa } = require$$0$3; + + /** @type {PropertyDescriptor} */ + const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false + }; + + /** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ + function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading'; + + // 3. Set fr’s result to null. + fr[kResult] = null; + + // 4. Set fr’s error to null. + fr[kError] = null; + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream(); + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader(); + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = []; + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read(); + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise; + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr); + }); + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false; + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value); + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now(); + queueMicrotask(() => { + fireAProgressEvent('progress', fr); + }); + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read(); + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done'; + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName); + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result; + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr); + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error; + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr); + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr); + } + }); + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done'; + + // 2. Set fr’s error to error. + fr[kError] = error; + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr); + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr); + } + }); + + break + } + } + })(); + } + + /** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ + function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }); + + reader.dispatchEvent(event); + } + + /** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ + function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:'; + + const parsed = parseMIMEType(mimeType || 'application/octet-stream'); + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed); + } + + dataURL += ';base64,'; + + const decoder = new StringDecoder('latin1'); + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)); + } + + dataURL += btoa(decoder.end()); + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure'; + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName); + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType); + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')); + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8'; + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes); + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = ''; + + const decoder = new StringDecoder('latin1'); + + for (const chunk of bytes) { + binaryString += decoder.write(chunk); + } + + binaryString += decoder.end(); + + return binaryString + } + } + } + + /** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ + function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue); + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes); + + let slice = 0; + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding; + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2; + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice); + return new TextDecoder(encoding).decode(sliced) + } + + /** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ + function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue; + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null + } + + /** + * @param {Uint8Array[]} sequences + */ + function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0); + + let offset = 0; + + return sequences.reduce((a, b) => { + a.set(b, offset); + offset += b.byteLength; + return a + }, new Uint8Array(size)) + } + + util$6 = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent + }; + return util$6; +} + +var filereader; +var hasRequiredFilereader; + +function requireFilereader () { + if (hasRequiredFilereader) return filereader; + hasRequiredFilereader = 1; + + const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent + } = requireUtil$6(); + const { + kState, + kError, + kResult, + kEvents, + kAborted + } = requireSymbols$2(); + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = requireUtil$9(); + + class FileReader extends EventTarget { + constructor () { + super(); + + this[kState] = 'empty'; + this[kResult] = null; + this[kError] = null; + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + }; + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer'); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer'); + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString'); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString'); + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText'); + + blob = webidl.converters.Blob(blob, { strict: false }); + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding'); + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding); + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL'); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL'); + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null; + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done'; + this[kResult] = null; + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true; + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this); + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this); + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader); + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader); + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader); + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend); + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn; + this.addEventListener('loadend', fn); + } else { + this[kEvents].loadend = null; + } + } + + get onerror () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error); + } + + if (typeof fn === 'function') { + this[kEvents].error = fn; + this.addEventListener('error', fn); + } else { + this[kEvents].error = null; + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart); + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn; + this.addEventListener('loadstart', fn); + } else { + this[kEvents].loadstart = null; + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress); + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn; + this.addEventListener('progress', fn); + } else { + this[kEvents].progress = null; + } + } + + get onload () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load); + } + + if (typeof fn === 'function') { + this[kEvents].load = fn; + this.addEventListener('load', fn); + } else { + this[kEvents].load = null; + } + } + + get onabort () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort); + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn; + this.addEventListener('abort', fn); + } else { + this[kEvents].abort = null; + } + } + } + + // https://w3c.github.io/FileAPI/#dom-filereader-empty + FileReader.EMPTY = FileReader.prototype.EMPTY = 0; + // https://w3c.github.io/FileAPI/#dom-filereader-loading + FileReader.LOADING = FileReader.prototype.LOADING = 1; + // https://w3c.github.io/FileAPI/#dom-filereader-done + FileReader.DONE = FileReader.prototype.DONE = 2; + + Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } + }); + + Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors + }); + + filereader = { + FileReader + }; + return filereader; +} + +var symbols$1; +var hasRequiredSymbols$1; + +function requireSymbols$1 () { + if (hasRequiredSymbols$1) return symbols$1; + hasRequiredSymbols$1 = 1; + + symbols$1 = { + kConstruct: requireSymbols$4().kConstruct + }; + return symbols$1; +} + +var util$5; +var hasRequiredUtil$5; + +function requireUtil$5 () { + if (hasRequiredUtil$5) return util$5; + hasRequiredUtil$5 = 1; + + const assert = require$$0$4; + const { URLSerializer } = requireDataUrl(); + const { isValidHeaderName } = requireUtil$8(); + + /** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ + function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment); + + const serializedB = URLSerializer(B, excludeFragment); + + return serializedA === serializedB + } + + /** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ + function getFieldValues (header) { + assert(header !== null); + + const values = []; + + for (let value of header.split(',')) { + value = value.trim(); + + if (isValidHeaderName(value)) { + values.push(value); + } + } + + return values + } + + util$5 = { + urlEquals, + getFieldValues + }; + return util$5; +} + +var cache; +var hasRequiredCache; + +function requireCache () { + if (hasRequiredCache) return cache; + hasRequiredCache = 1; + + const { kConstruct } = requireSymbols$1(); + const { urlEquals, getFieldValues } = requireUtil$5(); + const { kEnumerableProperty, isDisturbed } = requireUtil$9(); + const { webidl } = requireWebidl(); + const { Response, cloneResponse, fromInnerResponse } = requireResponse(); + const { Request, fromInnerRequest } = requireRequest(); + const { kState } = requireSymbols$3(); + const { fetching } = requireFetch(); + const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = requireUtil$8(); + const assert = require$$0$4; + + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + + class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor(); + } + + webidl.util.markAsUncloneable(this); + this.#relevantRequestResponseList = arguments[1]; + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.match'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + request = webidl.converters.RequestInfo(request, prefix, 'request'); + options = webidl.converters.CacheQueryOptions(options, prefix, 'options'); + + const p = this.#internalMatchAll(request, options, 1); + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.matchAll'; + if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request'); + options = webidl.converters.CacheQueryOptions(options, prefix, 'options'); + + return this.#internalMatchAll(request, options) + } + + async add (request) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.add'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + request = webidl.converters.RequestInfo(request, prefix, 'request'); + + // 1. + const requests = [request]; + + // 2. + const responseArrayPromise = this.addAll(requests); + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.addAll'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + // 1. + const responsePromises = []; + + // 2. + const requestList = []; + + // 3. + for (let request of requests) { + if (request === undefined) { + throw webidl.errors.conversionFailed({ + prefix, + argument: 'Argument 1', + types: ['undefined is not allowed'] + }) + } + + request = webidl.converters.RequestInfo(request); + + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState]; + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = []; + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState]; + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch'; + r.destination = 'subresource'; + + // 5.5 + requestList.push(r); + + // 5.6 + const responsePromise = createDeferredPromise(); + + // 5.7 + fetchControllers.push(fetching({ + request: r, + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })); + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')); + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })); + + for (const controller of fetchControllers) { + controller.abort(); + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')); + return + } + + // 2. + responsePromise.resolve(response); + } + })); + + // 5.8 + responsePromises.push(responsePromise.promise); + } + + // 6. + const p = Promise.all(responsePromises); + + // 7. + const responses = await p; + + // 7.1 + const operations = []; + + // 7.2 + let index = 0; + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + }; + + operations.push(operation); // 7.3.5 + + index++; // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise(); + + // 7.6.1 + let errorData = null; + + // 7.6.2 + try { + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined); + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData); + } + }); + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.put'; + webidl.argumentLengthCheck(arguments, 2, prefix); + + request = webidl.converters.RequestInfo(request, prefix, 'request'); + response = webidl.converters.Response(response, prefix, 'response'); + + // 1. + let innerRequest = null; + + // 2. + if (request instanceof Request) { + innerRequest = request[kState]; + } else { // 3. + innerRequest = new Request(request)[kState]; + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: prefix, + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState]; + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: prefix, + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')); + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: prefix, + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: prefix, + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse); + + // 10. + const bodyReadPromise = createDeferredPromise(); + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream; + + // 11.2 + const reader = stream.getReader(); + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject); + } else { + bodyReadPromise.resolve(undefined); + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = []; + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + }; + + // 17. + operations.push(operation); + + // 19. + const bytes = await bodyReadPromise.promise; + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes; + } + + // 19.1 + const cacheJobPromise = createDeferredPromise(); + + // 19.2.1 + let errorData = null; + + // 19.2.2 + try { + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve(); + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData); + } + }); + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.delete'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + request = webidl.converters.RequestInfo(request, prefix, 'request'); + options = webidl.converters.CacheQueryOptions(options, prefix, 'options'); + + /** + * @type {Request} + */ + let r = null; + + if (request instanceof Request) { + r = request[kState]; + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string'); + + r = new Request(request)[kState]; + } + + /** @type {CacheBatchOperation[]} */ + const operations = []; + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + }; + + operations.push(operation); + + const cacheJobPromise = createDeferredPromise(); + + let errorData = null; + let requestResponses; + + try { + requestResponses = this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length); + } else { + cacheJobPromise.reject(errorData); + } + }); + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {Promise} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache); + + const prefix = 'Cache.keys'; + + if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request'); + options = webidl.converters.CacheQueryOptions(options, prefix, 'options'); + + // 1. + let r = null; + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState]; + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState]; + } + } + + // 4. + const promise = createDeferredPromise(); + + // 5. + // 5.1 + const requests = []; + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]); + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options); + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]); + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = []; + + // 5.4.2 + for (const request of requests) { + const requestObject = fromInnerRequest( + request, + new AbortController().signal, + 'immutable' + ); + // 5.4.2.1 + requestList.push(requestObject); + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)); + }); + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList; + + // 2. + const backupCache = [...cache]; + + // 3. + const addedItems = []; + + // 4.1 + const resultList = []; + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses; + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options); + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + + // 4.2.5.2.1 + cache.splice(idx, 1); + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request; + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request); + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + + // 4.2.6.7.1 + cache.splice(idx, 1); + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]); + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]); + } + + // 4.2.7 + resultList.push([operation.request, operation.response]); + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0; + + // 5.2 + this.#relevantRequestResponseList = backupCache; + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = []; + + const storage = targetStorage ?? this.#relevantRequestResponseList; + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse; + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse); + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url); + + const cachedURL = new URL(request.url); + + if (options?.ignoreSearch) { + cachedURL.search = ''; + + queryURL.search = ''; + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')); + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue); + const queryValue = requestQuery.headersList.get(fieldValue); + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } + + #internalMatchAll (request, options, maxResponses = Infinity) { + // 1. + let r = null; + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState]; + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState]; + } + } + + // 5. + // 5.1 + const responses = []; + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]); + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options); + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]); + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = []; + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = fromInnerResponse(response, 'immutable'); + + responseList.push(responseObject.clone()); + + if (responseList.length >= maxResponses) { + break + } + } + + // 6. + return Object.freeze(responseList) + } + } + + Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty + }); + + const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: () => false + } + ]; + + webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters); + + webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } + ]); + + webidl.converters.Response = webidl.interfaceConverter(Response); + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo + ); + + cache = { + Cache + }; + return cache; +} + +var cachestorage; +var hasRequiredCachestorage; + +function requireCachestorage () { + if (hasRequiredCachestorage) return cachestorage; + hasRequiredCachestorage = 1; + + const { kConstruct } = requireSymbols$1(); + const { Cache } = requireCache(); + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = requireUtil$9(); + + class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage); + + const prefix = 'CacheStorage.has'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName'); + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage); + + const prefix = 'CacheStorage.open'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName'); + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName); + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = []; + + // 2.3 + this.#caches.set(cacheName, cache); + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage); + + const prefix = 'CacheStorage.delete'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName'); + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {Promise} + */ + async keys () { + webidl.brandCheck(this, CacheStorage); + + // 2.1 + const keys = this.#caches.keys(); + + // 2.2 + return [...keys] + } + } + + Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty + }); + + cachestorage = { + CacheStorage + }; + return cachestorage; +} + +var constants$1; +var hasRequiredConstants$1; + +function requireConstants$1 () { + if (hasRequiredConstants$1) return constants$1; + hasRequiredConstants$1 = 1; + + // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size + const maxAttributeValueSize = 1024; + + // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size + const maxNameValuePairSize = 4096; + + constants$1 = { + maxAttributeValueSize, + maxNameValuePairSize + }; + return constants$1; +} + +var util$4; +var hasRequiredUtil$4; + +function requireUtil$4 () { + if (hasRequiredUtil$4) return util$4; + hasRequiredUtil$4 = 1; + + /** + * @param {string} value + * @returns {boolean} + */ + function isCTLExcludingHtab (value) { + for (let i = 0; i < value.length; ++i) { + const code = value.charCodeAt(i); + + if ( + (code >= 0x00 && code <= 0x08) || + (code >= 0x0A && code <= 0x1F) || + code === 0x7F + ) { + return true + } + } + return false + } + + /** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ + function validateCookieName (name) { + for (let i = 0; i < name.length; ++i) { + const code = name.charCodeAt(i); + + if ( + code < 0x21 || // exclude CTLs (0-31), SP and HT + code > 0x7E || // exclude non-ascii and DEL + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x3C || // < + code === 0x3E || // > + code === 0x40 || // @ + code === 0x2C || // , + code === 0x3B || // ; + code === 0x3A || // : + code === 0x5C || // \ + code === 0x2F || // / + code === 0x5B || // [ + code === 0x5D || // ] + code === 0x3F || // ? + code === 0x3D || // = + code === 0x7B || // { + code === 0x7D // } + ) { + throw new Error('Invalid cookie name') + } + } + } + + /** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ + function validateCookieValue (value) { + let len = value.length; + let i = 0; + + // if the value is wrapped in DQUOTE + if (value[0] === '"') { + if (len === 1 || value[len - 1] !== '"') { + throw new Error('Invalid cookie value') + } + --len; + ++i; + } + + while (i < len) { + const code = value.charCodeAt(i++); + + if ( + code < 0x21 || // exclude CTLs (0-31) + code > 0x7E || // non-ascii and DEL (127) + code === 0x22 || // " + code === 0x2C || // , + code === 0x3B || // ; + code === 0x5C // \ + ) { + throw new Error('Invalid cookie value') + } + } + } + + /** + * path-value = + * @param {string} path + */ + function validateCookiePath (path) { + for (let i = 0; i < path.length; ++i) { + const code = path.charCodeAt(i); + + if ( + code < 0x20 || // exclude CTLs (0-31) + code === 0x7F || // DEL + code === 0x3B // ; + ) { + throw new Error('Invalid cookie path') + } + } + } + + /** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ + function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } + } + + const IMFDays = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ]; + + const IMFMonths = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ]; + + const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')); + + /** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ + function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date); + } + + return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` + } + + /** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ + function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } + } + + /** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ + function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name); + validateCookieValue(cookie.value); + + const out = [`${cookie.name}=${cookie.value}`]; + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true; + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true; + cookie.domain = null; + cookie.path = '/'; + } + + if (cookie.secure) { + out.push('Secure'); + } + + if (cookie.httpOnly) { + out.push('HttpOnly'); + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge); + out.push(`Max-Age=${cookie.maxAge}`); + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain); + out.push(`Domain=${cookie.domain}`); + } + + if (cookie.path) { + validateCookiePath(cookie.path); + out.push(`Path=${cookie.path}`); + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`); + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`); + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('='); + + out.push(`${key.trim()}=${value.join('=')}`); + } + + return out.join('; ') + } + + util$4 = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify + }; + return util$4; +} + +var parse$2; +var hasRequiredParse; + +function requireParse () { + if (hasRequiredParse) return parse$2; + hasRequiredParse = 1; + + const { maxNameValuePairSize, maxAttributeValueSize } = requireConstants$1(); + const { isCTLExcludingHtab } = requireUtil$4(); + const { collectASequenceOfCodePointsFast } = requireDataUrl(); + const assert = require$$0$4; + + /** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ + function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = ''; + let unparsedAttributes = ''; + let name = ''; + let value = ''; + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 }; + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position); + unparsedAttributes = header.slice(position.position); + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header; + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair; + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 }; + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ); + value = nameValuePair.slice(position.position + 1); + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim(); + value = value.trim(); + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } + } + + /** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ + function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';'); + unparsedAttributes = unparsedAttributes.slice(1); + + let cookieAv = ''; + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ); + unparsedAttributes = unparsedAttributes.slice(cookieAv.length); + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes; + unparsedAttributes = ''; + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = ''; + let attributeValue = ''; + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 }; + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ); + attributeValue = cookieAv.slice(position.position + 1); + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv; + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim(); + attributeValue = attributeValue.trim(); + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase(); + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue); + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime; + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0); + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue); + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds; + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue; + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1); + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase(); + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain; + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = ''; + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/'; + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue; + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath; + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true; + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true; + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + const attributeValueLowercase = attributeValue.toLowerCase(); + + // 1. If cookie-av's attribute-value is a case-insensitive match for + // "None", append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of "None". + if (attributeValueLowercase === 'none') { + cookieAttributeList.sameSite = 'None'; + } else if (attributeValueLowercase === 'strict') { + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", append an attribute to the cookie-attribute-list with + // an attribute-name of "SameSite" and an attribute-value of + // "Strict". + cookieAttributeList.sameSite = 'Strict'; + } else if (attributeValueLowercase === 'lax') { + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of "Lax". + cookieAttributeList.sameSite = 'Lax'; + } + } else { + cookieAttributeList.unparsed ??= []; + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + parse$2 = { + parseSetCookie, + parseUnparsedAttributes + }; + return parse$2; +} + +var cookies; +var hasRequiredCookies; + +function requireCookies () { + if (hasRequiredCookies) return cookies; + hasRequiredCookies = 1; + + const { parseSetCookie } = requireParse(); + const { stringify } = requireUtil$4(); + const { webidl } = requireWebidl(); + const { Headers } = requireHeaders(); + + /** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + + /** + * @param {Headers} headers + * @returns {Record} + */ + function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getCookies'); + + webidl.brandCheck(headers, Headers, { strict: false }); + + const cookie = headers.get('cookie'); + const out = {}; + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('='); + + out[name.trim()] = value.join('='); + } + + return out + } + + /** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ + function deleteCookie (headers, name, attributes) { + webidl.brandCheck(headers, Headers, { strict: false }); + + const prefix = 'deleteCookie'; + webidl.argumentLengthCheck(arguments, 2, prefix); + + name = webidl.converters.DOMString(name, prefix, 'name'); + attributes = webidl.converters.DeleteCookieAttributes(attributes); + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }); + } + + /** + * @param {Headers} headers + * @returns {Cookie[]} + */ + function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, 'getSetCookies'); + + webidl.brandCheck(headers, Headers, { strict: false }); + + const cookies = headers.getSetCookie(); + + if (!cookies) { + return [] + } + + return cookies.map((pair) => parseSetCookie(pair)) + } + + /** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ + function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, 'setCookie'); + + webidl.brandCheck(headers, Headers, { strict: false }); + + cookie = webidl.converters.Cookie(cookie); + + const str = stringify(cookie); + + if (str) { + headers.append('Set-Cookie', str); + } + } + + webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + } + ]); + + webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: () => null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: () => null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: () => new Array(0) + } + ]); + + cookies = { + getCookies, + deleteCookie, + getSetCookies, + setCookie + }; + return cookies; +} + +var events; +var hasRequiredEvents; + +function requireEvents () { + if (hasRequiredEvents) return events; + hasRequiredEvents = 1; + + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = requireUtil$9(); + const { kConstruct } = requireSymbols$4(); + const { MessagePort } = require$$1$4; + + /** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ + class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + if (type === kConstruct) { + super(arguments[1], arguments[2]); + webidl.util.markAsUncloneable(this); + return + } + + const prefix = 'MessageEvent constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + type = webidl.converters.DOMString(type, prefix, 'type'); + eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict'); + + super(type, eventInitDict); + + this.#eventInit = eventInitDict; + webidl.util.markAsUncloneable(this); + } + + get data () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent); + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports); + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent); + + webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent'); + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } + + static createFastMessageEvent (type, init) { + const messageEvent = new MessageEvent(kConstruct, type, init); + messageEvent.#eventInit = init; + messageEvent.#eventInit.data ??= null; + messageEvent.#eventInit.origin ??= ''; + messageEvent.#eventInit.lastEventId ??= ''; + messageEvent.#eventInit.source ??= null; + messageEvent.#eventInit.ports ??= []; + return messageEvent + } + } + + const { createFastMessageEvent } = MessageEvent; + delete MessageEvent.createFastMessageEvent; + + /** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ + class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + const prefix = 'CloseEvent constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + type = webidl.converters.DOMString(type, prefix, 'type'); + eventInitDict = webidl.converters.CloseEventInit(eventInitDict); + + super(type, eventInitDict); + + this.#eventInit = eventInitDict; + webidl.util.markAsUncloneable(this); + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.reason + } + } + + // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface + class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + const prefix = 'ErrorEvent constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + super(type, eventInitDict); + webidl.util.markAsUncloneable(this); + + type = webidl.converters.DOMString(type, prefix, 'type'); + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}); + + this.#eventInit = eventInitDict; + } + + get message () { + webidl.brandCheck(this, ErrorEvent); + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent); + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent); + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent); + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent); + + return this.#eventInit.error + } + } + + Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty + }); + + Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty + }); + + Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty + }); + + webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort); + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort + ); + + const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: () => false + } + ]; + + webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: () => null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: () => null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + defaultValue: () => new Array(0) + } + ]); + + webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: () => 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: () => '' + } + ]); + + webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: () => '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: () => '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: () => 0 + }, + { + key: 'error', + converter: webidl.converters.any + } + ]); + + events = { + MessageEvent, + CloseEvent, + ErrorEvent, + createFastMessageEvent + }; + return events; +} + +var constants; +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + // This is a Globally Unique Identifier unique used + // to validate that the endpoint accepts websocket + // connections. + // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 + const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + + /** @type {PropertyDescriptor} */ + const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false + }; + + const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 + }; + + const sentCloseFrameState = { + NOT_SENT: 0, + PROCESSING: 1, + SENT: 2 + }; + + const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA + }; + + const maxUnsigned16Bit = 2 ** 16 - 1; // 65535 + + const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 + }; + + const emptyBuffer = Buffer.allocUnsafe(0); + + const sendHints = { + string: 1, + typedArray: 2, + arrayBuffer: 3, + blob: 4 + }; + + constants = { + uid, + sentCloseFrameState, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer, + sendHints + }; + return constants; +} + +var symbols; +var hasRequiredSymbols; + +function requireSymbols () { + if (hasRequiredSymbols) return symbols; + hasRequiredSymbols = 1; + + symbols = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') + }; + return symbols; +} + +var util$3; +var hasRequiredUtil$3; + +function requireUtil$3 () { + if (hasRequiredUtil$3) return util$3; + hasRequiredUtil$3 = 1; + + const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = requireSymbols(); + const { states, opcodes } = requireConstants(); + const { ErrorEvent, createFastMessageEvent } = requireEvents(); + const { isUtf8 } = require$$0$3; + const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = requireDataUrl(); + + /* globals Blob */ + + /** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ + function isConnecting (ws) { + // If the WebSocket connection is not yet established, and the connection + // is not yet closed, then the WebSocket connection is in the CONNECTING state. + return ws[kReadyState] === states.CONNECTING + } + + /** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ + function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN + } + + /** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ + function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING + } + + /** + * @param {import('./websocket').WebSocket} ws + * @returns {boolean} + */ + function isClosed (ws) { + return ws[kReadyState] === states.CLOSED + } + + /** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {(...args: ConstructorParameters) => Event} eventFactory + * @param {EventInit | undefined} eventInitDict + */ + function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = eventFactory(e, eventInitDict); + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event); + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ + function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent; + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = utf8Decode(data); + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.'); + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]); + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = toArrayBuffer(data); + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, createFastMessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }); + } + + function toArrayBuffer (buffer) { + if (buffer.byteLength === buffer.buffer.byteLength) { + return buffer.buffer + } + return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ + function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (let i = 0; i < protocol.length; ++i) { + const code = protocol.charCodeAt(i); + + if ( + code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) + code > 0x7E || + code === 0x22 || // " + code === 0x28 || // ( + code === 0x29 || // ) + code === 0x2C || // , + code === 0x2F || // / + code === 0x3A || // : + code === 0x3B || // ; + code === 0x3C || // < + code === 0x3D || // = + code === 0x3E || // > + code === 0x3F || // ? + code === 0x40 || // @ + code === 0x5B || // [ + code === 0x5C || // \ + code === 0x5D || // ] + code === 0x7B || // { + code === 0x7D // } + ) { + return false + } + } + + return true + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ + function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 + } + + /** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ + function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws; + + controller.abort(); + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy(); + } + + if (reason) { + // TODO: process.nextTick + fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), { + error: new Error(reason), + message: reason + }); + } + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 + * @param {number} opcode + */ + function isControlFrame (opcode) { + return ( + opcode === opcodes.CLOSE || + opcode === opcodes.PING || + opcode === opcodes.PONG + ) + } + + function isContinuationFrame (opcode) { + return opcode === opcodes.CONTINUATION + } + + function isTextBinaryFrame (opcode) { + return opcode === opcodes.TEXT || opcode === opcodes.BINARY + } + + function isValidOpcode (opcode) { + return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) + } + + /** + * Parses a Sec-WebSocket-Extensions header value. + * @param {string} extensions + * @returns {Map} + */ + // TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + function parseExtensions (extensions) { + const position = { position: 0 }; + const extensionList = new Map(); + + while (position.position < extensions.length) { + const pair = collectASequenceOfCodePointsFast(';', extensions, position); + const [name, value = ''] = pair.split('='); + + extensionList.set( + removeHTTPWhitespace(name, true, false), + removeHTTPWhitespace(value, false, true) + ); + + position.position++; + } + + return extensionList + } + + /** + * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 + * @description "client-max-window-bits = 1*DIGIT" + * @param {string} value + */ + function isValidClientWindowBits (value) { + // Must have at least one character + if (value.length === 0) { + return false + } + + // Check all characters are ASCII digits + for (let i = 0; i < value.length; i++) { + const byte = value.charCodeAt(i); + + if (byte < 0x30 || byte > 0x39) { + return false + } + } + + // Check numeric range: zlib requires windowBits in range 8-15 + const num = Number.parseInt(value, 10); + return num >= 8 && num <= 15 + } + + // https://nodejs.org/api/intl.html#detecting-internationalization-support + const hasIntl = typeof process.versions.icu === 'string'; + const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined; + + /** + * Converts a Buffer to utf-8, even on platforms without icu. + * @param {Buffer} buffer + */ + const utf8Decode = hasIntl + ? fatalDecoder.decode.bind(fatalDecoder) + : function (buffer) { + if (isUtf8(buffer)) { + return buffer.toString('utf-8') + } + throw new TypeError('Invalid utf-8 received.') + }; + + util$3 = { + isConnecting, + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isContinuationFrame, + isTextBinaryFrame, + isValidOpcode, + parseExtensions, + isValidClientWindowBits + }; + return util$3; +} + +var frame; +var hasRequiredFrame; + +function requireFrame () { + if (hasRequiredFrame) return frame; + hasRequiredFrame = 1; + + const { maxUnsigned16Bit } = requireConstants(); + + const BUFFER_SIZE = 16386; + + /** @type {import('crypto')} */ + let crypto; + let buffer = null; + let bufIdx = BUFFER_SIZE; + + try { + crypto = require('node:crypto'); + /* c8 ignore next 3 */ + } catch { + crypto = { + // not full compatibility, but minimum. + randomFillSync: function randomFillSync (buffer, _offset, _size) { + for (let i = 0; i < buffer.length; ++i) { + buffer[i] = Math.random() * 255 | 0; + } + return buffer + } + }; + } + + function generateMask () { + if (bufIdx === BUFFER_SIZE) { + bufIdx = 0; + crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE); + } + return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] + } + + class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data; + } + + createFrame (opcode) { + const frameData = this.frameData; + const maskKey = generateMask(); + const bodyLength = frameData?.byteLength ?? 0; + + /** @type {number} */ + let payloadLength = bodyLength; // 0-125 + let offset = 6; + + if (bodyLength > maxUnsigned16Bit) { + offset += 8; // payload length is next 8 bytes + payloadLength = 127; + } else if (bodyLength > 125) { + offset += 2; // payload length is next 2 bytes + payloadLength = 126; + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset); + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0; + buffer[0] |= 0x80; // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode; // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = maskKey[0]; + buffer[offset - 3] = maskKey[1]; + buffer[offset - 2] = maskKey[2]; + buffer[offset - 1] = maskKey[3]; + + buffer[1] = payloadLength; + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2); + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0; + buffer.writeUIntBE(bodyLength, 4, 6); + } + + buffer[1] |= 0x80; // MASK + + // mask body + for (let i = 0; i < bodyLength; ++i) { + buffer[offset + i] = frameData[i] ^ maskKey[i & 3]; + } + + return buffer + } + } + + frame = { + WebsocketFrameSend + }; + return frame; +} + +var connection; +var hasRequiredConnection; + +function requireConnection () { + if (hasRequiredConnection) return connection; + hasRequiredConnection = 1; + + const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = requireConstants(); + const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose, + kResponse + } = requireSymbols(); + const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = requireUtil$3(); + const { channels } = requireDiagnostics(); + const { CloseEvent } = requireEvents(); + const { makeRequest } = requireRequest(); + const { fetching } = requireFetch(); + const { Headers, getHeadersList } = requireHeaders(); + const { getDecodeSplit } = requireUtil$8(); + const { WebsocketFrameSend } = requireFrame(); + + /** @type {import('crypto')} */ + let crypto; + try { + crypto = require('node:crypto'); + /* c8 ignore next 3 */ + } catch { + + } + + /** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any, extensions: string[] | undefined) => void} onEstablish + * @param {Partial} options + */ + function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url; + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'; + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + client, + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }); + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = getHeadersList(new Headers(options.headers)); + + request.headersList = headersList; + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64'); + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue); + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13'); + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol); + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + const permessageDeflate = 'permessage-deflate; client_max_window_bits'; + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + request.headersList.append('sec-websocket-extensions', permessageDeflate); + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher, + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.'); + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.'); + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".'); + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".'); + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept'); + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64'); + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.'); + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions'); + let extensions; + + if (secExtension !== null) { + extensions = parseExtensions(secExtension); + + if (!extensions.has('permessage-deflate')) { + failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.'); + return + } + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol'); + + if (secProtocol !== null) { + const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList); + + // The client can request that the server use a specific subprotocol by + // including the |Sec-WebSocket-Protocol| field in its handshake. If it + // is specified, the server needs to include the same field and one of + // the selected subprotocol values in its response for the connection to + // be established. + if (!requestProtocols.includes(secProtocol)) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.'); + return + } + } + + response.socket.on('data', onSocketData); + response.socket.on('close', onSocketClose); + response.socket.on('error', onSocketError); + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }); + } + + onEstablish(response, extensions); + } + }); + + return controller + } + + function closeWebSocketConnection (ws, code, reason, reasonByteLength) { + if (isClosing(ws) || isClosed(ws)) ; else if (!isEstablished(ws)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(ws, 'Connection was closed before it was established.'); + ws[kReadyState] = states.CLOSING; + } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + ws[kSentClose] = sentCloseFrameState.PROCESSING; + + const frame = new WebsocketFrameSend(); + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2); + frame.frameData.writeUInt16BE(code, 0); + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength); + frame.frameData.writeUInt16BE(code, 0); + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8'); + } else { + frame.frameData = emptyBuffer; + } + + /** @type {import('stream').Duplex} */ + const socket = ws[kResponse].socket; + + socket.write(frame.createFrame(opcodes.CLOSE)); + + ws[kSentClose] = sentCloseFrameState.SENT; + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + ws[kReadyState] = states.CLOSING; + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + ws[kReadyState] = states.CLOSING; + } + } + + /** + * @param {Buffer} chunk + */ + function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause(); + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ + function onSocketClose () { + const { ws } = this; + const { [kResponse]: response } = ws; + + response.socket.off('data', onSocketData); + response.socket.off('close', onSocketClose); + response.socket.off('error', onSocketError); + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]; + + let code = 1005; + let reason = ''; + + const result = ws[kByteParser].closingInfo; + + if (result && !result.error) { + code = result.code ?? 1005; + reason = result.reason; + } else if (!ws[kReceivedClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006; + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED; + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + // TODO: process.nextTick + fireEvent('close', ws, (type, init) => new CloseEvent(type, init), { + wasClean, code, reason + }); + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }); + } + } + + function onSocketError (error) { + const { ws } = this; + + ws[kReadyState] = states.CLOSING; + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error); + } + + this.destroy(); + } + + connection = { + establishWebSocketConnection, + closeWebSocketConnection + }; + return connection; +} + +var permessageDeflate; +var hasRequiredPermessageDeflate; + +function requirePermessageDeflate () { + if (hasRequiredPermessageDeflate) return permessageDeflate; + hasRequiredPermessageDeflate = 1; + + const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require$$1$5; + const { isValidClientWindowBits } = requireUtil$3(); + const { MessageSizeExceededError } = requireErrors(); + + const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]); + const kBuffer = Symbol('kBuffer'); + const kLength = Symbol('kLength'); + + class PerMessageDeflate { + /** @type {import('node:zlib').InflateRaw} */ + #inflate + + #options = {} + + #maxPayloadSize = 0 + + /** + * @param {Map} extensions + */ + constructor (extensions, options) { + this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover'); + this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits'); + + this.#maxPayloadSize = options.maxPayloadSize; + } + + /** + * Decompress a compressed payload. + * @param {Buffer} chunk Compressed data + * @param {boolean} fin Final fragment flag + * @param {Function} callback Callback function + */ + decompress (chunk, fin, callback) { + // An endpoint uses the following algorithm to decompress a message. + // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the + // payload of the message. + // 2. Decompress the resulting data using DEFLATE. + if (!this.#inflate) { + let windowBits = Z_DEFAULT_WINDOWBITS; + + if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS + if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { + callback(new Error('Invalid server_max_window_bits')); + return + } + + windowBits = Number.parseInt(this.#options.serverMaxWindowBits); + } + + try { + this.#inflate = createInflateRaw({ windowBits }); + } catch (err) { + callback(err); + return + } + this.#inflate[kBuffer] = []; + this.#inflate[kLength] = 0; + + this.#inflate.on('data', (data) => { + this.#inflate[kLength] += data.length; + + if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { + callback(new MessageSizeExceededError()); + this.#inflate.removeAllListeners(); + this.#inflate = null; + return + } + + this.#inflate[kBuffer].push(data); + }); + + this.#inflate.on('error', (err) => { + this.#inflate = null; + callback(err); + }); + } + + this.#inflate.write(chunk); + if (fin) { + this.#inflate.write(tail); + } + + this.#inflate.flush(() => { + if (!this.#inflate) { + return + } + + const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]); + + this.#inflate[kBuffer].length = 0; + this.#inflate[kLength] = 0; + + callback(null, full); + }); + } + } + + permessageDeflate = { PerMessageDeflate }; + return permessageDeflate; +} + +var receiver; +var hasRequiredReceiver; + +function requireReceiver () { + if (hasRequiredReceiver) return receiver; + hasRequiredReceiver = 1; + + const { Writable } = require$$0$5; + const assert = require$$0$4; + const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = requireConstants(); + const { kReadyState, kSentClose, kResponse, kReceivedClose } = requireSymbols(); + const { channels } = requireDiagnostics(); + const { + isValidStatusCode, + isValidOpcode, + failWebsocketConnection, + websocketMessageReceived, + utf8Decode, + isControlFrame, + isTextBinaryFrame, + isContinuationFrame + } = requireUtil$3(); + const { WebsocketFrameSend } = requireFrame(); + const { closeWebSocketConnection } = requireConnection(); + const { PerMessageDeflate } = requirePermessageDeflate(); + const { MessageSizeExceededError } = requireErrors(); + + function failWebsocketConnectionWithCode (ws, code, reason) { + closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)); + failWebsocketConnection(ws, reason); + } + + // This code was influenced by ws released under the MIT license. + // Copyright (c) 2011 Einar Otto Stangvik + // Copyright (c) 2013 Arnout Kazemier and contributors + // Copyright (c) 2016 Luigi Pinca and contributors + + class ByteParser extends Writable { + #buffers = [] + #fragmentsBytes = 0 + #byteOffset = 0 + #loop = false + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + /** @type {Map} */ + #extensions + + /** @type {number} */ + #maxFragments + + /** @type {number} */ + #maxPayloadSize + + /** + * @param {import('./websocket').WebSocket} ws + * @param {Map|null} extensions + * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] + */ + constructor (ws, extensions, options = {}) { + super(); + + this.ws = ws; + this.#extensions = extensions == null ? new Map() : extensions; + this.#maxFragments = options.maxFragments ?? 0; + this.#maxPayloadSize = options.maxPayloadSize ?? 0; + + if (this.#extensions.has('permessage-deflate')) { + this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options)); + } + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk); + this.#byteOffset += chunk.length; + this.#loop = true; + + this.run(callback); + } + + #validatePayloadLength () { + if ( + this.#maxPayloadSize > 0 && + !isControlFrame(this.#info.opcode) && + this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize + ) { + failWebsocketConnectionWithCode(this.ws, 1009, 'Payload size exceeds maximum allowed size'); + return false + } + + return true + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (this.#loop) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2); + const fin = (buffer[0] & 0x80) !== 0; + const opcode = buffer[0] & 0x0F; + const masked = (buffer[1] & 0x80) === 0x80; + + const fragmented = !fin && opcode !== opcodes.CONTINUATION; + const payloadLength = buffer[1] & 0x7F; + + const rsv1 = buffer[0] & 0x40; + const rsv2 = buffer[0] & 0x20; + const rsv3 = buffer[0] & 0x10; + + if (!isValidOpcode(opcode)) { + failWebsocketConnection(this.ws, 'Invalid opcode received'); + return callback() + } + + if (masked) { + failWebsocketConnection(this.ws, 'Frame cannot be masked'); + return callback() + } + + // MUST be 0 unless an extension is negotiated that defines meanings + // for non-zero values. If a nonzero value is received and none of + // the negotiated extensions defines the meaning of such a nonzero + // value, the receiving endpoint MUST _Fail the WebSocket + // Connection_. + // This document allocates the RSV1 bit of the WebSocket header for + // PMCEs and calls the bit the "Per-Message Compressed" bit. On a + // WebSocket connection where a PMCE is in use, this bit indicates + // whether a message is compressed or not. + if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { + failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.'); + return + } + + if (rsv2 !== 0 || rsv3 !== 0) { + failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear'); + return + } + + if (fragmented && !isTextBinaryFrame(opcode)) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.'); + return + } + + // If we are already parsing a text/binary frame and do not receive either + // a continuation frame or close frame, fail the connection. + if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { + failWebsocketConnection(this.ws, 'Expected continuation frame'); + return + } + + if (this.#info.fragmented && fragmented) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.'); + return + } + + // "All control frames MUST have a payload length of 125 bytes or less + // and MUST NOT be fragmented." + if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { + failWebsocketConnection(this.ws, 'Control frame either too large or fragmented'); + return + } + + if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { + failWebsocketConnection(this.ws, 'Unexpected continuation frame'); + return + } + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength; + this.#state = parserStates.READ_DATA; + + if (!this.#validatePayloadLength()) { + return + } + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16; + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64; + } + + if (isTextBinaryFrame(opcode)) { + this.#info.binaryType = opcode; + this.#info.compressed = rsv1 !== 0; + } + + this.#info.opcode = opcode; + this.#info.masked = masked; + this.#info.fin = fin; + this.#info.fragmented = fragmented; + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2); + + this.#info.payloadLength = buffer.readUInt16BE(0); + this.#state = parserStates.READ_DATA; + + if (!this.#validatePayloadLength()) { + return + } + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8); + const upper = buffer.readUInt32BE(0); + const lower = buffer.readUInt32BE(4); + + // 2^31 is the maximum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper !== 0 || lower > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.'); + return + } + + this.#info.payloadLength = lower; + this.#state = parserStates.READ_DATA; + + if (!this.#validatePayloadLength()) { + return + } + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + return callback() + } + + const body = this.consume(this.#info.payloadLength); + + if (isControlFrame(this.#info.opcode)) { + this.#loop = this.parseControlFrame(body); + this.#state = parserStates.INFO; + } else { + if (!this.#info.compressed) { + if (!this.writeFragments(body)) { + return + } + + if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); + return + } + + // If the frame is not fragmented, a message has been received. + // If the frame is fragmented, it will terminate with a fin bit set + // and an opcode of 0 (continuation), therefore we handle that when + // parsing continuation frames, not here. + if (!this.#info.fragmented && this.#info.fin) { + websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + } + + this.#state = parserStates.INFO; + } else { + this.#extensions.get('permessage-deflate').decompress( + body, + this.#info.fin, + (error, data) => { + if (error) { + const code = error instanceof MessageSizeExceededError ? 1009 : 1007; + failWebsocketConnectionWithCode(this.ws, code, error.message); + return + } + + if (!this.writeFragments(data)) { + return + } + + if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { + failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message); + return + } + + if (!this.#info.fin) { + this.#state = parserStates.INFO; + this.#loop = true; + this.run(callback); + return + } + + websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()); + + this.#loop = true; + this.#state = parserStates.INFO; + this.run(callback); + } + ); + + this.#loop = false; + break + } + } + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer} + */ + consume (n) { + if (n > this.#byteOffset) { + throw new Error('Called consume() before buffers satiated.') + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length; + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n); + let offset = 0; + + while (offset !== n) { + const next = this.#buffers[0]; + const { length } = next; + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset); + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset); + this.#buffers[0] = next.subarray(n - offset); + break + } else { + buffer.set(this.#buffers.shift(), offset); + offset += next.length; + } + } + + this.#byteOffset -= n; + + return buffer + } + + writeFragments (fragment) { + if ( + this.#maxFragments > 0 && + this.#fragments.length === this.#maxFragments + ) { + failWebsocketConnectionWithCode(this.ws, 1008, 'Too many message fragments'); + return false + } + + this.#fragmentsBytes += fragment.length; + this.#fragments.push(fragment); + return true + } + + consumeFragments () { + const fragments = this.#fragments; + + if (fragments.length === 1) { + this.#fragmentsBytes = 0; + return fragments.shift() + } + + const output = Buffer.concat(fragments, this.#fragmentsBytes); + this.#fragments = []; + this.#fragmentsBytes = 0; + + return output + } + + parseCloseBody (data) { + assert(data.length !== 1); + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code; + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0); + } + + if (code !== undefined && !isValidStatusCode(code)) { + return { code: 1002, reason: 'Invalid status code', error: true } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2); + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3); + } + + try { + reason = utf8Decode(reason); + } catch { + return { code: 1007, reason: 'Invalid UTF-8', error: true } + } + + return { code, reason, error: false } + } + + /** + * Parses control frames. + * @param {Buffer} body + */ + parseControlFrame (body) { + const { opcode, payloadLength } = this.#info; + + if (opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.'); + return false + } + + this.#info.closeInfo = this.parseCloseBody(body); + + if (this.#info.closeInfo.error) { + const { code, reason } = this.#info.closeInfo; + + closeWebSocketConnection(this.ws, code, reason, reason.length); + failWebsocketConnection(this.ws, reason); + return false + } + + if (this.ws[kSentClose] !== sentCloseFrameState.SENT) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + let body = emptyBuffer; + if (this.#info.closeInfo.code) { + body = Buffer.allocUnsafe(2); + body.writeUInt16BE(this.#info.closeInfo.code, 0); + } + const closeFrame = new WebsocketFrameSend(body); + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = sentCloseFrameState.SENT; + } + } + ); + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING; + this.ws[kReceivedClose] = true; + + return false + } else if (opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body); + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)); + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }); + } + } + } else if (opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }); + } + } + + return true + } + + get closingInfo () { + return this.#info.closeInfo + } + } + + receiver = { + ByteParser + }; + return receiver; +} + +var sender; +var hasRequiredSender; + +function requireSender () { + if (hasRequiredSender) return sender; + hasRequiredSender = 1; + + const { WebsocketFrameSend } = requireFrame(); + const { opcodes, sendHints } = requireConstants(); + const FixedQueue = requireFixedQueue(); + + /** @type {typeof Uint8Array} */ + const FastBuffer = Buffer[Symbol.species]; + + /** + * @typedef {object} SendQueueNode + * @property {Promise | null} promise + * @property {((...args: any[]) => any)} callback + * @property {Buffer | null} frame + */ + + class SendQueue { + /** + * @type {FixedQueue} + */ + #queue = new FixedQueue() + + /** + * @type {boolean} + */ + #running = false + + /** @type {import('node:net').Socket} */ + #socket + + constructor (socket) { + this.#socket = socket; + } + + add (item, cb, hint) { + if (hint !== sendHints.blob) { + const frame = createFrame(item, hint); + if (!this.#running) { + // fast-path + this.#socket.write(frame, cb); + } else { + /** @type {SendQueueNode} */ + const node = { + promise: null, + callback: cb, + frame + }; + this.#queue.push(node); + } + return + } + + /** @type {SendQueueNode} */ + const node = { + promise: item.arrayBuffer().then((ab) => { + node.promise = null; + node.frame = createFrame(ab, hint); + }), + callback: cb, + frame: null + }; + + this.#queue.push(node); + + if (!this.#running) { + this.#run(); + } + } + + async #run () { + this.#running = true; + const queue = this.#queue; + while (!queue.isEmpty()) { + const node = queue.shift(); + // wait pending promise + if (node.promise !== null) { + await node.promise; + } + // write + this.#socket.write(node.frame, node.callback); + // cleanup + node.callback = node.frame = null; + } + this.#running = false; + } + } + + function createFrame (data, hint) { + return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY) + } + + function toBuffer (data, hint) { + switch (hint) { + case sendHints.string: + return Buffer.from(data) + case sendHints.arrayBuffer: + case sendHints.blob: + return new FastBuffer(data) + case sendHints.typedArray: + return new FastBuffer(data.buffer, data.byteOffset, data.byteLength) + } + } + + sender = { SendQueue }; + return sender; +} + +var websocket; +var hasRequiredWebsocket; + +function requireWebsocket () { + if (hasRequiredWebsocket) return websocket; + hasRequiredWebsocket = 1; + + const { webidl } = requireWebidl(); + const { URLSerializer } = requireDataUrl(); + const { environmentSettingsObject } = requireUtil$8(); + const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = requireConstants(); + const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser + } = requireSymbols(); + const { + isConnecting, + isEstablished, + isClosing, + isValidSubprotocol, + fireEvent + } = requireUtil$3(); + const { establishWebSocketConnection, closeWebSocketConnection } = requireConnection(); + const { ByteParser } = requireReceiver(); + const { kEnumerableProperty, isBlobLike } = requireUtil$9(); + const { getGlobalDispatcher } = requireGlobal(); + const { types } = require$$0$7; + const { ErrorEvent, CloseEvent } = requireEvents(); + const { SendQueue } = requireSender(); + + // https://websockets.spec.whatwg.org/#interface-definition + class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** @type {SendQueue} */ + #sendQueue + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super(); + + webidl.util.markAsUncloneable(this); + + const prefix = 'WebSocket constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options'); + + url = webidl.converters.USVString(url, prefix, 'url'); + protocols = options.protocols; + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = environmentSettingsObject.settingsObject.baseUrl; + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord; + + try { + urlRecord = new URL(url, baseURL); + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:'; + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:'; + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols]; + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href); + + // 11. Let client be this's relevant settings object. + const client = environmentSettingsObject.settingsObject; + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + client, + this, + (response, extensions) => this.#onConnectionEstablished(response, extensions), + options + ); + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING; + + this[kSentClose] = sentCloseFrameState.NOT_SENT; + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob'; + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket); + + const prefix = 'WebSocket.close'; + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }); + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason, prefix, 'reason'); + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0; + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason); + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + closeWebSocketConnection(this, code, reason, reasonByteLength); + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket); + + const prefix = 'WebSocket.send'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + data = webidl.converters.WebSocketSendData(data, prefix, 'data'); + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (isConnecting(this)) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const length = Buffer.byteLength(data); + + this.#bufferedAmount += length; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= length; + }, sendHints.string); + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + this.#bufferedAmount += data.byteLength; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength; + }, sendHints.arrayBuffer); + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + this.#bufferedAmount += data.byteLength; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.byteLength; + }, sendHints.typedArray); + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + this.#bufferedAmount += data.size; + this.#sendQueue.add(data, () => { + this.#bufferedAmount -= data.size; + }, sendHints.blob); + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket); + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket); + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket); + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket); + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket); + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket); + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open); + } + + if (typeof fn === 'function') { + this.#events.open = fn; + this.addEventListener('open', fn); + } else { + this.#events.open = null; + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket); + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error); + } + + if (typeof fn === 'function') { + this.#events.error = fn; + this.addEventListener('error', fn); + } else { + this.#events.error = null; + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket); + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close); + } + + if (typeof fn === 'function') { + this.#events.close = fn; + this.addEventListener('close', fn); + } else { + this.#events.close = null; + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket); + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message); + } + + if (typeof fn === 'function') { + this.#events.message = fn; + this.addEventListener('message', fn); + } else { + this.#events.message = null; + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket); + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket); + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob'; + } else { + this[kBinaryType] = type; + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response, parsedExtensions) { + // processResponse is called when the "response's header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response; + + const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions; + const maxFragments = webSocketOptions?.maxFragments; + const maxPayloadSize = webSocketOptions?.maxPayloadSize; + + const parser = new ByteParser(this, parsedExtensions, { + maxFragments, + maxPayloadSize + }); + parser.on('drain', onParserDrain); + parser.on('error', onParserError.bind(this)); + + response.socket.ws = this; + this[kByteParser] = parser; + + this.#sendQueue = new SendQueue(response.socket); + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN; + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions'); + + if (extensions !== null) { + this.#extensions = extensions; + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol'); + + if (protocol !== null) { + this.#protocol = protocol; + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this); + } + } + + // https://websockets.spec.whatwg.org/#dom-websocket-connecting + WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING; + // https://websockets.spec.whatwg.org/#dom-websocket-open + WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN; + // https://websockets.spec.whatwg.org/#dom-websocket-closing + WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING; + // https://websockets.spec.whatwg.org/#dom-websocket-closed + WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED; + + Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } + }); + + Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors + }); + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString + ); + + webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V, prefix, argument) + }; + + // This implements the proposal made in https://github.com/whatwg/websockets/issues/42 + webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + defaultValue: () => new Array(0) + }, + { + key: 'dispatcher', + converter: webidl.converters.any, + defaultValue: () => getGlobalDispatcher() + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } + ]); + + webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } + }; + + webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) + }; + + function onParserDrain () { + this.ws[kResponse].socket.resume(); + } + + function onParserError (err) { + let message; + let code; + + if (err instanceof CloseEvent) { + message = err.reason; + code = err.code; + } else { + message = err.message; + } + + fireEvent('error', this, () => new ErrorEvent('error', { error: err, message })); + + closeWebSocketConnection(this, code); + } + + websocket = { + WebSocket + }; + return websocket; +} + +var util$2; +var hasRequiredUtil$2; + +function requireUtil$2 () { + if (hasRequiredUtil$2) return util$2; + hasRequiredUtil$2 = 1; + + /** + * Checks if the given value is a valid LastEventId. + * @param {string} value + * @returns {boolean} + */ + function isValidLastEventId (value) { + // LastEventId should not contain U+0000 NULL + return value.indexOf('\u0000') === -1 + } + + /** + * Checks if the given value is a base 10 digit. + * @param {string} value + * @returns {boolean} + */ + function isASCIINumber (value) { + if (value.length === 0) return false + for (let i = 0; i < value.length; i++) { + if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false + } + return true + } + + // https://github.com/nodejs/undici/issues/2664 + function delay (ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms).unref(); + }) + } + + util$2 = { + isValidLastEventId, + isASCIINumber, + delay + }; + return util$2; +} + +var eventsourceStream; +var hasRequiredEventsourceStream; + +function requireEventsourceStream () { + if (hasRequiredEventsourceStream) return eventsourceStream; + hasRequiredEventsourceStream = 1; + const { Transform } = require$$0$5; + const { isASCIINumber, isValidLastEventId } = requireUtil$2(); + + /** + * @type {number[]} BOM + */ + const BOM = [0xEF, 0xBB, 0xBF]; + /** + * @type {10} LF + */ + const LF = 0x0A; + /** + * @type {13} CR + */ + const CR = 0x0D; + /** + * @type {58} COLON + */ + const COLON = 0x3A; + /** + * @type {32} SPACE + */ + const SPACE = 0x20; + + /** + * @typedef {object} EventSourceStreamEvent + * @type {object} + * @property {string} [event] The event type. + * @property {string} [data] The data of the message. + * @property {string} [id] A unique ID for the event. + * @property {string} [retry] The reconnection time, in milliseconds. + */ + + /** + * @typedef eventSourceSettings + * @type {object} + * @property {string} lastEventId The last event ID received from the server. + * @property {string} origin The origin of the event source. + * @property {number} reconnectionTime The reconnection time, in milliseconds. + */ + + class EventSourceStream extends Transform { + /** + * @type {eventSourceSettings} + */ + state = null + + /** + * Leading byte-order-mark check. + * @type {boolean} + */ + checkBOM = true + + /** + * @type {boolean} + */ + crlfCheck = false + + /** + * @type {boolean} + */ + eventEndCheck = false + + /** + * @type {Buffer} + */ + buffer = null + + pos = 0 + + event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + } + + /** + * @param {object} options + * @param {eventSourceSettings} options.eventSourceSettings + * @param {Function} [options.push] + */ + constructor (options = {}) { + // Enable object mode as EventSourceStream emits objects of shape + // EventSourceStreamEvent + options.readableObjectMode = true; + + super(options); + + this.state = options.eventSourceSettings || {}; + if (options.push) { + this.push = options.push; + } + } + + /** + * @param {Buffer} chunk + * @param {string} _encoding + * @param {Function} callback + * @returns {void} + */ + _transform (chunk, _encoding, callback) { + if (chunk.length === 0) { + callback(); + return + } + + // Cache the chunk in the buffer, as the data might not be complete while + // processing it + // TODO: Investigate if there is a more performant way to handle + // incoming chunks + // see: https://github.com/nodejs/undici/issues/2630 + if (this.buffer) { + this.buffer = Buffer.concat([this.buffer, chunk]); + } else { + this.buffer = chunk; + } + + // Strip leading byte-order-mark if we opened the stream and started + // the processing of the incoming data + if (this.checkBOM) { + switch (this.buffer.length) { + case 1: + // Check if the first byte is the same as the first byte of the BOM + if (this.buffer[0] === BOM[0]) { + // If it is, we need to wait for more data + callback(); + return + } + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false; + + // The buffer only contains one byte so we need to wait for more data + callback(); + return + case 2: + // Check if the first two bytes are the same as the first two bytes + // of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] + ) { + // If it is, we need to wait for more data, because the third byte + // is needed to determine if it is the BOM or not + callback(); + return + } + + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false; + break + case 3: + // Check if the first three bytes are the same as the first three + // bytes of the BOM + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // If it is, we can drop the buffered data, as it is only the BOM + this.buffer = Buffer.alloc(0); + // Set the checkBOM flag to false as we don't need to check for the + // BOM anymore + this.checkBOM = false; + + // Await more data + callback(); + return + } + // If it is not the BOM, we can start processing the data + this.checkBOM = false; + break + default: + // The buffer is longer than 3 bytes, so we can drop the BOM if it is + // present + if ( + this.buffer[0] === BOM[0] && + this.buffer[1] === BOM[1] && + this.buffer[2] === BOM[2] + ) { + // Remove the BOM from the buffer + this.buffer = this.buffer.subarray(3); + } + + // Set the checkBOM flag to false as we don't need to check for the + this.checkBOM = false; + break + } + } + + while (this.pos < this.buffer.length) { + // If the previous line ended with an end-of-line, we need to check + // if the next character is also an end-of-line. + if (this.eventEndCheck) { + // If the the current character is an end-of-line, then the event + // is finished and we can process it + + // If the previous line ended with a carriage return, we need to + // check if the current character is a line feed and remove it + // from the buffer. + if (this.crlfCheck) { + // If the current character is a line feed, we can remove it + // from the buffer and reset the crlfCheck flag + if (this.buffer[this.pos] === LF) { + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + this.crlfCheck = false; + + // It is possible that the line feed is not the end of the + // event. We need to check if the next character is an + // end-of-line character to determine if the event is + // finished. We simply continue the loop to check the next + // character. + + // As we removed the line feed from the buffer and set the + // crlfCheck flag to false, we basically don't make any + // distinction between a line feed and a carriage return. + continue + } + this.crlfCheck = false; + } + + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed so we can remove it from the + // buffer + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true; + } + + this.buffer = this.buffer.subarray(this.pos + 1); + this.pos = 0; + if ( + this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { + this.processEvent(this.event); + } + this.clearEvent(); + continue + } + // If the current character is not an end-of-line, then the event + // is not finished and we have to reset the eventEndCheck flag + this.eventEndCheck = false; + continue + } + + // If the current character is an end-of-line, we can process the + // line + if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { + // If the current character is a carriage return, we need to + // set the crlfCheck flag to true, as we need to check if the + // next character is a line feed + if (this.buffer[this.pos] === CR) { + this.crlfCheck = true; + } + + // In any case, we can process the line as we reached an + // end-of-line character + this.parseLine(this.buffer.subarray(0, this.pos), this.event); + + // Remove the processed line from the buffer + this.buffer = this.buffer.subarray(this.pos + 1); + // Reset the position as we removed the processed line from the buffer + this.pos = 0; + // A line was processed and this could be the end of the event. We need + // to check if the next line is empty to determine if the event is + // finished. + this.eventEndCheck = true; + continue + } + + this.pos++; + } + + callback(); + } + + /** + * @param {Buffer} line + * @param {EventStreamEvent} event + */ + parseLine (line, event) { + // If the line is empty (a blank line) + // Dispatch the event, as defined below. + // This will be handled in the _transform method + if (line.length === 0) { + return + } + + // If the line starts with a U+003A COLON character (:) + // Ignore the line. + const colonPosition = line.indexOf(COLON); + if (colonPosition === 0) { + return + } + + let field = ''; + let value = ''; + + // If the line contains a U+003A COLON character (:) + if (colonPosition !== -1) { + // Collect the characters on the line before the first U+003A COLON + // character (:), and let field be that string. + // TODO: Investigate if there is a more performant way to extract the + // field + // see: https://github.com/nodejs/undici/issues/2630 + field = line.subarray(0, colonPosition).toString('utf8'); + + // Collect the characters on the line after the first U+003A COLON + // character (:), and let value be that string. + // If value starts with a U+0020 SPACE character, remove it from value. + let valueStart = colonPosition + 1; + if (line[valueStart] === SPACE) { + ++valueStart; + } + // TODO: Investigate if there is a more performant way to extract the + // value + // see: https://github.com/nodejs/undici/issues/2630 + value = line.subarray(valueStart).toString('utf8'); + + // Otherwise, the string is not empty but does not contain a U+003A COLON + // character (:) + } else { + // Process the field using the steps described below, using the whole + // line as the field name, and the empty string as the field value. + field = line.toString('utf8'); + value = ''; + } + + // Modify the event with the field name and value. The value is also + // decoded as UTF-8 + switch (field) { + case 'data': + if (event[field] === undefined) { + event[field] = value; + } else { + event[field] += `\n${value}`; + } + break + case 'retry': + if (isASCIINumber(value)) { + event[field] = value; + } + break + case 'id': + if (isValidLastEventId(value)) { + event[field] = value; + } + break + case 'event': + if (value.length > 0) { + event[field] = value; + } + break + } + } + + /** + * @param {EventSourceStreamEvent} event + */ + processEvent (event) { + if (event.retry && isASCIINumber(event.retry)) { + this.state.reconnectionTime = parseInt(event.retry, 10); + } + + if (event.id && isValidLastEventId(event.id)) { + this.state.lastEventId = event.id; + } + + // only dispatch event, when data is provided + if (event.data !== undefined) { + this.push({ + type: event.event || 'message', + options: { + data: event.data, + lastEventId: this.state.lastEventId, + origin: this.state.origin + } + }); + } + } + + clearEvent () { + this.event = { + data: undefined, + event: undefined, + id: undefined, + retry: undefined + }; + } + } + + eventsourceStream = { + EventSourceStream + }; + return eventsourceStream; +} + +var eventsource; +var hasRequiredEventsource; + +function requireEventsource () { + if (hasRequiredEventsource) return eventsource; + hasRequiredEventsource = 1; + + const { pipeline } = require$$0$5; + const { fetching } = requireFetch(); + const { makeRequest } = requireRequest(); + const { webidl } = requireWebidl(); + const { EventSourceStream } = requireEventsourceStream(); + const { parseMIMEType } = requireDataUrl(); + const { createFastMessageEvent } = requireEvents(); + const { isNetworkError } = requireResponse(); + const { delay } = requireUtil$2(); + const { kEnumerableProperty } = requireUtil$9(); + const { environmentSettingsObject } = requireUtil$8(); + + let experimentalWarned = false; + + /** + * A reconnection time, in milliseconds. This must initially be an implementation-defined value, + * probably in the region of a few seconds. + * + * In Comparison: + * - Chrome uses 3000ms. + * - Deno uses 5000ms. + * + * @type {3000} + */ + const defaultReconnectionTime = 3000; + + /** + * The readyState attribute represents the state of the connection. + * @enum + * @readonly + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev + */ + + /** + * The connection has not yet been established, or it was closed and the user + * agent is reconnecting. + * @type {0} + */ + const CONNECTING = 0; + + /** + * The user agent has an open connection and is dispatching events as it + * receives them. + * @type {1} + */ + const OPEN = 1; + + /** + * The connection is not open, and the user agent is not trying to reconnect. + * @type {2} + */ + const CLOSED = 2; + + /** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". + * @type {'anonymous'} + */ + const ANONYMOUS = 'anonymous'; + + /** + * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". + * @type {'use-credentials'} + */ + const USE_CREDENTIALS = 'use-credentials'; + + /** + * The EventSource interface is used to receive server-sent events. It + * connects to a server over HTTP and receives events in text/event-stream + * format without closing the connection. + * @extends {EventTarget} + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events + * @api public + */ + class EventSource extends EventTarget { + #events = { + open: null, + error: null, + message: null + } + + #url = null + #withCredentials = false + + #readyState = CONNECTING + + #request = null + #controller = null + + #dispatcher + + /** + * @type {import('./eventsource-stream').eventSourceSettings} + */ + #state + + /** + * Creates a new EventSource object. + * @param {string} url + * @param {EventSourceInit} [eventSourceInitDict] + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface + */ + constructor (url, eventSourceInitDict = {}) { + // 1. Let ev be a new EventSource object. + super(); + + webidl.util.markAsUncloneable(this); + + const prefix = 'EventSource constructor'; + webidl.argumentLengthCheck(arguments, 1, prefix); + + if (!experimentalWarned) { + experimentalWarned = true; + process.emitWarning('EventSource is experimental, expect them to change at any time.', { + code: 'UNDICI-ES' + }); + } + + url = webidl.converters.USVString(url, prefix, 'url'); + eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict'); + + this.#dispatcher = eventSourceInitDict.dispatcher; + this.#state = { + lastEventId: '', + reconnectionTime: defaultReconnectionTime + }; + + // 2. Let settings be ev's relevant settings object. + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + const settings = environmentSettingsObject; + + let urlRecord; + + try { + // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. + urlRecord = new URL(url, settings.settingsObject.baseUrl); + this.#state.origin = urlRecord.origin; + } catch (e) { + // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 5. Set ev's url to urlRecord. + this.#url = urlRecord.href; + + // 6. Let corsAttributeState be Anonymous. + let corsAttributeState = ANONYMOUS; + + // 7. If the value of eventSourceInitDict's withCredentials member is true, + // then set corsAttributeState to Use Credentials and set ev's + // withCredentials attribute to true. + if (eventSourceInitDict.withCredentials) { + corsAttributeState = USE_CREDENTIALS; + this.#withCredentials = true; + } + + // 8. Let request be the result of creating a potential-CORS request given + // urlRecord, the empty string, and corsAttributeState. + const initRequest = { + redirect: 'follow', + keepalive: true, + // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes + mode: 'cors', + credentials: corsAttributeState === 'anonymous' + ? 'same-origin' + : 'omit', + referrer: 'no-referrer' + }; + + // 9. Set request's client to settings. + initRequest.client = environmentSettingsObject.settingsObject; + + // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. + initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]; + + // 11. Set request's cache mode to "no-store". + initRequest.cache = 'no-store'; + + // 12. Set request's initiator type to "other". + initRequest.initiator = 'other'; + + initRequest.urlList = [new URL(this.#url)]; + + // 13. Set ev's request to request. + this.#request = makeRequest(initRequest); + + this.#connect(); + } + + /** + * Returns the state of this EventSource object's connection. It can have the + * values described below. + * @returns {0|1|2} + * @readonly + */ + get readyState () { + return this.#readyState + } + + /** + * Returns the URL providing the event stream. + * @readonly + * @returns {string} + */ + get url () { + return this.#url + } + + /** + * Returns a boolean indicating whether the EventSource object was + * instantiated with CORS credentials set (true), or not (false, the default). + */ + get withCredentials () { + return this.#withCredentials + } + + #connect () { + if (this.#readyState === CLOSED) return + + this.#readyState = CONNECTING; + + const fetchParams = { + request: this.#request, + dispatcher: this.#dispatcher + }; + + // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. + const processEventSourceEndOfBody = (response) => { + if (isNetworkError(response)) { + this.dispatchEvent(new Event('error')); + this.close(); + } + + this.#reconnect(); + }; + + // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... + fetchParams.processResponseEndOfBody = processEventSourceEndOfBody; + + // and processResponse set to the following steps given response res: + fetchParams.processResponse = (response) => { + // 1. If res is an aborted network error, then fail the connection. + + if (isNetworkError(response)) { + // 1. When a user agent is to fail the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to CLOSED + // and fires an event named error at the EventSource object. Once the + // user agent has failed the connection, it does not attempt to + // reconnect. + if (response.aborted) { + this.close(); + this.dispatchEvent(new Event('error')); + return + // 2. Otherwise, if res is a network error, then reestablish the + // connection, unless the user agent knows that to be futile, in + // which case the user agent may fail the connection. + } else { + this.#reconnect(); + return + } + } + + // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` + // is not `text/event-stream`, then fail the connection. + const contentType = response.headersList.get('content-type', true); + const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'; + const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'; + if ( + response.status !== 200 || + contentTypeValid === false + ) { + this.close(); + this.dispatchEvent(new Event('error')); + return + } + + // 4. Otherwise, announce the connection and interpret res's body + // line by line. + + // When a user agent is to announce the connection, the user agent + // must queue a task which, if the readyState attribute is set to a + // value other than CLOSED, sets the readyState attribute to OPEN + // and fires an event named open at the EventSource object. + // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + this.#readyState = OPEN; + this.dispatchEvent(new Event('open')); + + // If redirected to a different origin, set the origin to the new origin. + this.#state.origin = response.urlList[response.urlList.length - 1].origin; + + const eventSourceStream = new EventSourceStream({ + eventSourceSettings: this.#state, + push: (event) => { + this.dispatchEvent(createFastMessageEvent( + event.type, + event.options + )); + } + }); + + pipeline(response.body.stream, + eventSourceStream, + (error) => { + if ( + error?.aborted === false + ) { + this.close(); + this.dispatchEvent(new Event('error')); + } + }); + }; + + this.#controller = fetching(fetchParams); + } + + /** + * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model + * @returns {Promise} + */ + async #reconnect () { + // When a user agent is to reestablish the connection, the user agent must + // run the following steps. These steps are run in parallel, not as part of + // a task. (The tasks that it queues, of course, are run like normal tasks + // and not themselves in parallel.) + + // 1. Queue a task to run the following steps: + + // 1. If the readyState attribute is set to CLOSED, abort the task. + if (this.#readyState === CLOSED) return + + // 2. Set the readyState attribute to CONNECTING. + this.#readyState = CONNECTING; + + // 3. Fire an event named error at the EventSource object. + this.dispatchEvent(new Event('error')); + + // 2. Wait a delay equal to the reconnection time of the event source. + await delay(this.#state.reconnectionTime); + + // 5. Queue a task to run the following steps: + + // 1. If the EventSource object's readyState attribute is not set to + // CONNECTING, then return. + if (this.#readyState !== CONNECTING) return + + // 2. Let request be the EventSource object's request. + // 3. If the EventSource object's last event ID string is not the empty + // string, then: + // 1. Let lastEventIDValue be the EventSource object's last event ID + // string, encoded as UTF-8. + // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header + // list. + if (this.#state.lastEventId.length) { + this.#request.headersList.set('last-event-id', this.#state.lastEventId, true); + } + + // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. + this.#connect(); + } + + /** + * Closes the connection, if any, and sets the readyState attribute to + * CLOSED. + */ + close () { + webidl.brandCheck(this, EventSource); + + if (this.#readyState === CLOSED) return + this.#readyState = CLOSED; + this.#controller.abort(); + this.#request = null; + } + + get onopen () { + return this.#events.open + } + + set onopen (fn) { + if (this.#events.open) { + this.removeEventListener('open', this.#events.open); + } + + if (typeof fn === 'function') { + this.#events.open = fn; + this.addEventListener('open', fn); + } else { + this.#events.open = null; + } + } + + get onmessage () { + return this.#events.message + } + + set onmessage (fn) { + if (this.#events.message) { + this.removeEventListener('message', this.#events.message); + } + + if (typeof fn === 'function') { + this.#events.message = fn; + this.addEventListener('message', fn); + } else { + this.#events.message = null; + } + } + + get onerror () { + return this.#events.error + } + + set onerror (fn) { + if (this.#events.error) { + this.removeEventListener('error', this.#events.error); + } + + if (typeof fn === 'function') { + this.#events.error = fn; + this.addEventListener('error', fn); + } else { + this.#events.error = null; + } + } + } + + const constantsPropertyDescriptors = { + CONNECTING: { + __proto__: null, + configurable: false, + enumerable: true, + value: CONNECTING, + writable: false + }, + OPEN: { + __proto__: null, + configurable: false, + enumerable: true, + value: OPEN, + writable: false + }, + CLOSED: { + __proto__: null, + configurable: false, + enumerable: true, + value: CLOSED, + writable: false + } + }; + + Object.defineProperties(EventSource, constantsPropertyDescriptors); + Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors); + + Object.defineProperties(EventSource.prototype, { + close: kEnumerableProperty, + onerror: kEnumerableProperty, + onmessage: kEnumerableProperty, + onopen: kEnumerableProperty, + readyState: kEnumerableProperty, + url: kEnumerableProperty, + withCredentials: kEnumerableProperty + }); + + webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ + { + key: 'withCredentials', + converter: webidl.converters.boolean, + defaultValue: () => false + }, + { + key: 'dispatcher', // undici only + converter: webidl.converters.any + } + ]); + + eventsource = { + EventSource, + defaultReconnectionTime + }; + return eventsource; +} + +var hasRequiredUndici; + +function requireUndici () { + if (hasRequiredUndici) return undici; + hasRequiredUndici = 1; + + const Client = requireClient(); + const Dispatcher = requireDispatcher(); + const Pool = requirePool(); + const BalancedPool = requireBalancedPool(); + const Agent = requireAgent(); + const ProxyAgent = requireProxyAgent(); + const EnvHttpProxyAgent = requireEnvHttpProxyAgent(); + const RetryAgent = requireRetryAgent(); + const errors = requireErrors(); + const util = requireUtil$9(); + const { InvalidArgumentError } = errors; + const api = requireApi(); + const buildConnector = requireConnect(); + const MockClient = requireMockClient(); + const MockAgent = requireMockAgent(); + const MockPool = requireMockPool(); + const mockErrors = requireMockErrors(); + const RetryHandler = requireRetryHandler(); + const { getGlobalDispatcher, setGlobalDispatcher } = requireGlobal(); + const DecoratorHandler = requireDecoratorHandler(); + const RedirectHandler = requireRedirectHandler(); + const createRedirectInterceptor = requireRedirectInterceptor(); + + Object.assign(Dispatcher.prototype, api); + + undici.Dispatcher = Dispatcher; + undici.Client = Client; + undici.Pool = Pool; + undici.BalancedPool = BalancedPool; + undici.Agent = Agent; + undici.ProxyAgent = ProxyAgent; + undici.EnvHttpProxyAgent = EnvHttpProxyAgent; + undici.RetryAgent = RetryAgent; + undici.RetryHandler = RetryHandler; + + undici.DecoratorHandler = DecoratorHandler; + undici.RedirectHandler = RedirectHandler; + undici.createRedirectInterceptor = createRedirectInterceptor; + undici.interceptors = { + redirect: requireRedirect(), + retry: requireRetry(), + dump: requireDump(), + dns: requireDns() + }; + + undici.buildConnector = buildConnector; + undici.errors = errors; + undici.util = { + parseHeaders: util.parseHeaders, + headerNameToString: util.headerNameToString + }; + + function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts; + opts = null; + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path; + if (!opts.path.startsWith('/')) { + path = `/${path}`; + } + + url = new URL(util.parseOrigin(url).origin + path); + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {}; + } + + url = util.parseURL(url); + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts; + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } + } + + undici.setGlobalDispatcher = setGlobalDispatcher; + undici.getGlobalDispatcher = getGlobalDispatcher; + + const fetchImpl = requireFetch().fetch; + undici.fetch = async function fetch (init, options = undefined) { + try { + return await fetchImpl(init, options) + } catch (err) { + if (err && typeof err === 'object') { + Error.captureStackTrace(err); + } + + throw err + } + }; + undici.Headers = requireHeaders().Headers; + undici.Response = requireResponse().Response; + undici.Request = requireRequest().Request; + undici.FormData = requireFormdata().FormData; + undici.File = globalThis.File ?? require$$0$3.File; + undici.FileReader = requireFilereader().FileReader; + + const { setGlobalOrigin, getGlobalOrigin } = requireGlobal$1(); + + undici.setGlobalOrigin = setGlobalOrigin; + undici.getGlobalOrigin = getGlobalOrigin; + + const { CacheStorage } = requireCachestorage(); + const { kConstruct } = requireSymbols$1(); + + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + undici.caches = new CacheStorage(kConstruct); + + const { deleteCookie, getCookies, getSetCookies, setCookie } = requireCookies(); + + undici.deleteCookie = deleteCookie; + undici.getCookies = getCookies; + undici.getSetCookies = getSetCookies; + undici.setCookie = setCookie; + + const { parseMIMEType, serializeAMimeType } = requireDataUrl(); + + undici.parseMIMEType = parseMIMEType; + undici.serializeAMimeType = serializeAMimeType; + + const { CloseEvent, ErrorEvent, MessageEvent } = requireEvents(); + undici.WebSocket = requireWebsocket().WebSocket; + undici.CloseEvent = CloseEvent; + undici.ErrorEvent = ErrorEvent; + undici.MessageEvent = MessageEvent; + + undici.request = makeDispatcher(api.request); + undici.stream = makeDispatcher(api.stream); + undici.pipeline = makeDispatcher(api.pipeline); + undici.connect = makeDispatcher(api.connect); + undici.upgrade = makeDispatcher(api.upgrade); + + undici.MockClient = MockClient; + undici.MockPool = MockPool; + undici.MockAgent = MockAgent; + undici.mockErrors = mockErrors; + + const { EventSource } = requireEventsource(); + + undici.EventSource = EventSource; + return undici; +} + +var undiciExports = requireUndici(); + +/* eslint-disable @typescript-eslint/no-explicit-any */ +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (MediaTypes = {})); +[ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +[ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const { access, appendFile, writeFile } = promises; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const { chmod, copyFile, lstat, mkdir, open, readdir, rename, rm, rmdir, stat, symlink, unlink } = fs.promises; +// export const {open} = 'fs' +process.platform === 'win32'; +fs.constants.O_RDONLY; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/* eslint-disable @typescript-eslint/unbound-method */ +process.platform === 'win32'; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +os__default.platform(); +os__default.arch(); + +(undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (ExitCode = {})); +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + return val.trim(); +} +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + issueCommand('error', toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + issueCommand('warning', toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} + +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if (existsSync(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = + (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} + +var lib$2 = {}; + +var proxy = {}; + +var hasRequiredProxy; + +function requireProxy () { + if (hasRequiredProxy) return proxy; + hasRequiredProxy = 1; + Object.defineProperty(proxy, "__esModule", { value: true }); + proxy.getProxyUrl = getProxyUrl; + proxy.checkBypass = checkBypass; + function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } + } + else { + return undefined; + } + } + function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; + } + function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); + } + class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } + } + + return proxy; +} + +var hasRequiredLib$2; + +function requireLib$2 () { + if (hasRequiredLib$2) return lib$2; + hasRequiredLib$2 = 1; + /* eslint-disable @typescript-eslint/no-explicit-any */ + var __createBinding = (lib$2 && lib$2.__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 = (lib$2 && lib$2.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (lib$2 && lib$2.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + })(); + var __awaiter = (lib$2 && lib$2.__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(lib$2, "__esModule", { value: true }); + lib$2.HttpClient = lib$2.HttpClientResponse = lib$2.HttpClientError = lib$2.MediaTypes = lib$2.Headers = lib$2.HttpCodes = void 0; + lib$2.getProxyUrl = getProxyUrl; + lib$2.isHttps = isHttps; + const http$1 = __importStar(http); + const https$1 = __importStar(https); + const pm = __importStar(requireProxy()); + const tunnel = __importStar(requireTunnel()); + const undici_1 = requireUndici(); + var HttpCodes; + (function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; + })(HttpCodes || (lib$2.HttpCodes = HttpCodes = {})); + var Headers; + (function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; + })(Headers || (lib$2.Headers = Headers = {})); + var MediaTypes; + (function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; + })(MediaTypes || (lib$2.MediaTypes = MediaTypes = {})); + /** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; + } + const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect + ]; + const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout + ]; + const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; + const ExponentialBackoffCeiling = 10; + const ExponentialBackoffTimeSlice = 5; + class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } + } + lib$2.HttpClientError = HttpClientError; + class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } + } + lib$2.HttpClientResponse = HttpClientResponse; + function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; + } + class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = this._getUserAgentWithOrchestrationId(userAgent); + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl_1, obj_1) { + return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = + this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https$1 : http$1; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + /** + * Gets an existing header value or returns a default. + * Handles converting number header values to strings since HTTP headers must be strings. + * Note: This returns string | string[] since some headers can have multiple values. + * For headers that must always be a single string (like Content-Type), use the + * specialized _getExistingOrDefaultContentTypeHeader method instead. + */ + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; + if (headerValue) { + clientHeader = + typeof headerValue === 'number' ? headerValue.toString() : headerValue; + } + } + const additionalValue = additionalHeaders[header]; + if (additionalValue !== undefined) { + return typeof additionalValue === 'number' + ? additionalValue.toString() + : additionalValue; + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _default; + } + /** + * Specialized version of _getExistingOrDefaultHeader for Content-Type header. + * Always returns a single string (not an array) since Content-Type should be a single value. + * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. + * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers + * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). + */ + _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; + if (headerValue) { + if (typeof headerValue === 'number') { + clientHeader = String(headerValue); + } + else if (Array.isArray(headerValue)) { + clientHeader = headerValue.join(', '); + } + else { + clientHeader = headerValue; + } + } + } + const additionalValue = additionalHeaders[Headers.ContentType]; + // Return the first non-undefined value, converting numbers or arrays to strings if necessary + if (additionalValue !== undefined) { + if (typeof additionalValue === 'number') { + return String(additionalValue); + } + else if (Array.isArray(additionalValue)) { + return additionalValue.join(', '); + } + else { + return additionalValue; + } + } + if (clientHeader !== undefined) { + return clientHeader; + } + return _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http$1.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if tunneling agent isn't assigned create a new agent + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https$1.Agent(options) : new http$1.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _getUserAgentWithOrchestrationId(userAgent) { + const baseUserAgent = userAgent || 'actions/http-client'; + const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; + if (orchId) { + // Sanitize the orchestration ID to ensure it contains only valid characters + // Valid characters: 0-9, a-z, _, -, . + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); + return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; + } + return baseUserAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); + } + } + lib$2.HttpClient = HttpClient; + const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); + + return lib$2; +} + +var libExports = requireLib$2(); + +var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +function getProxyAgent(destinationUrl) { + const hc = new libExports.HttpClient(); + return hc.getAgent(destinationUrl); +} +function getProxyAgentDispatcher(destinationUrl) { + const hc = new libExports.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + return undiciExports.fetch(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +function getUserAgentWithOrchestrationId(baseUserAgent) { + var _a; + const orchId = (_a = process.env['ACTIONS_ORCHESTRATION_ID']) === null || _a === void 0 ? void 0 : _a.trim(); + if (orchId) { + const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); + const tag = `actions_orchestration_id/${sanitizedId}`; + if (baseUserAgent === null || baseUserAgent === void 0 ? void 0 : baseUserAgent.includes(tag)) + return baseUserAgent; + const ua = baseUserAgent ? `${baseUserAgent} ` : ''; + return `${ua}${tag}`; + } + return baseUserAgent; +} + +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && process.version !== undefined) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${ + process.arch + })`; + } + + return ""; +} + +// @ts-check + +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce((callback, name) => { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(() => { + if (!state.registry[name]) { + return method(options); + } + + return state.registry[name].reduce((method, registered) => { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} + +// @ts-check + +function addHook(state, kind, name, hook) { + const orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } + + if (kind === "before") { + hook = (method, options) => { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } + + if (kind === "after") { + hook = (method, options) => { + let result; + return Promise.resolve() + .then(method.bind(null, options)) + .then((result_) => { + result = result_; + return orig(result, options); + }) + .then(() => { + return result; + }); + }; + } + + if (kind === "error") { + hook = (method, options) => { + return Promise.resolve() + .then(method.bind(null, options)) + .catch((error) => { + return orig(error, options); + }); + }; + } + + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} + +// @ts-check + +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + + const index = state.registry[name] + .map((registered) => { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); +} + +// @ts-check + + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +const bind = Function.bind; +const bindable = bind.bind(bind); + +function bindApi(hook, state, name) { + const removeHookRef = bindable(removeHook, null).apply( + null, + [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach((kind) => { + const args = [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} + +function Collection() { + const state = { + registry: {}, + }; + + const hook = register.bind(null, state); + bindApi(hook, state); + + return hook; +} + +var Hook = { Collection }; + +// pkg/dist-src/defaults.js + +// pkg/dist-src/version.js +var VERSION$5 = "0.0.0-development"; + +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION$5} ${getUserAgent()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; + +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +// pkg/dist-src/util/is-plain-object.js +function isPlainObject$1(value) { + if (typeof value !== "object" || value === null) return false; + if (Object.prototype.toString.call(value) !== "[object Object]") return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject$1(options[key])) { + if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); + else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} + +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} + +// pkg/dist-src/merge.js +function merge$1(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} + +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} + +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} + +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} + +// pkg/dist-src/parse.js +function parse$1(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} + +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse$1(merge$1(defaults, route, options)); +} + +// pkg/dist-src/with-defaults.js +function withDefaults$2(oldDefaults, newDefaults) { + const DEFAULTS2 = merge$1(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults$2.bind(null, DEFAULTS2), + merge: merge$1.bind(null, DEFAULTS2), + parse: parse$1 + }); +} + +// pkg/dist-src/index.js +var endpoint = withDefaults$2(null, DEFAULTS); + +var dist = {}; + +var hasRequiredDist; + +function requireDist () { + if (hasRequiredDist) return dist; + hasRequiredDist = 1; + /*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + Object.defineProperty(dist, "__esModule", { value: true }); + dist.format = format; + dist.parse = parse; + const TEXT_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]*$/; + const TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + /** + * RegExp to match chars that must be quoted-pair in RFC 9110 sec 5.6.4 + */ + const QUOTE_REGEXP = /[\\"]/g; + /** + * RegExp to match type in RFC 9110 sec 8.3.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + const TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + /** + * Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`. + */ + const NullObject = /* @__PURE__ */ (() => { + const C = function () { }; + C.prototype = Object.create(null); + return C; + })(); + /** + * Format an object into a `Content-Type` header. + */ + function format(obj) { + const { type, parameters } = obj; + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError(`Invalid type: ${type}`); + } + let result = type; + if (parameters) { + for (const param of Object.keys(parameters)) { + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError(`Invalid parameter name: ${param}`); + } + result += `; ${param}=${qstring(parameters[param])}`; + } + } + return result; + } + /** + * Parse a `Content-Type` header. + */ + function parse(header, options) { + const len = header.length; + let index = skipOWS(header, 0, len); + const valueStart = index; + index = skipValue(header, index, len); + const valueEnd = trailingOWS(header, valueStart, index); + const type = header.slice(valueStart, valueEnd).toLowerCase(); + const parameters = options?.parameters === false + ? new NullObject() + : parseParameters(header, index, len); + return { type, parameters }; + } + const SP = 32; // " " + const HTAB = 9; // "\t" + const SEMI = 59; // ";" + const EQ = 61; // "=" + const DQUOTE = 34; // '"' + const BSLASH = 92; // "\\" + /** + * Parses the parameters of a `Content-Type` header starting at the given index. + */ + function parseParameters(header, index, len) { + const parameters = new NullObject(); + parameter: while (index < len) { + index = skipOWS(header, index + 1 /* Skip over ; */, len); + const keyStart = index; + while (index < len) { + const code = header.charCodeAt(index); + if (code === SEMI) + continue parameter; + if (code === EQ) { + const keyEnd = trailingOWS(header, keyStart, index); + const key = header.slice(keyStart, keyEnd).toLowerCase(); + index = skipOWS(header, index + 1, len); + if (index < len && header.charCodeAt(index) === DQUOTE) { + index++; + let value = ""; + while (index < len) { + const code = header.charCodeAt(index++); + if (code === DQUOTE) { + index = skipValue(header, index, len); + if (parameters[key] === undefined) + parameters[key] = value; + break; + } + if (code === BSLASH && index < len) { + value += header[index++]; + continue; + } + value += String.fromCharCode(code); + } + continue parameter; + } + const valueStart = index; + index = skipValue(header, index, len); + if (parameters[key] === undefined) { + const valueEnd = trailingOWS(header, valueStart, index); + parameters[key] = header.slice(valueStart, valueEnd); + } + continue parameter; + } + index++; + } + } + return parameters; + } + /** + * Skip over characters until a semicolon. + */ + function skipValue(str, index, len) { + while (index < len) { + const char = str.charCodeAt(index); + if (char === SEMI) + break; + index++; + } + return index; + } + /** + * Skip optional whitespace (OWS) in an HTTP header value. + * + * OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t"). + */ + function skipOWS(header, index, len) { + while (index < len) { + const char = header.charCodeAt(index); + if (char !== SP && char !== HTAB) + break; + index++; + } + return index; + } + /** + * Trim optional whitespace (OWS) from the end of a substring. + * + * OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t"). + */ + function trailingOWS(header, start, end) { + while (end > start) { + const char = header.charCodeAt(end - 1); + if (char !== SP && char !== HTAB) + break; + end--; + } + return end; + } + /** + * Serialize a parameter value. + */ + function qstring(str) { + if (TOKEN_REGEXP.test(str)) + return str; + if (TEXT_REGEXP.test(str)) + return `"${str.replace(QUOTE_REGEXP, "\\$&")}"`; + throw new TypeError(`Invalid parameter value: ${str}`); + } + + return dist; +} + +var distExports = requireDist(); + +const intRegex = /^-?\d+$/; +const noiseValue = /^-?\d+n+$/; // Noise - strings that match the custom format before being converted to it +const originalStringify = JSON.stringify; +const originalParse = JSON.parse; +const customFormat = /^-?\d+n$/; + +const bigIntsStringify = /([\[:])?"(-?\d+)n"($|([\\n]|\s)*(\s|[\\n])*[,\}\]])/g; +const noiseStringify = + /([\[:])?("-?\d+n+)n("$|"([\\n]|\s)*(\s|[\\n])*[,\}\]])/g; + +/** + * @typedef {(this: any, key: string | number | undefined, value: any) => any} Replacer + * @typedef {(key: string | number | undefined, value: any, context?: { source: string }) => any} Reviver + */ + +/** + * Converts a JavaScript value to a JSON string. + * + * Supports serialization of BigInt values using two strategies: + * 1. Custom format "123n" → "123" (universal fallback) + * 2. Native JSON.rawJSON() (Node.js 22+, fastest) when available + * + * All other values are serialized exactly like native JSON.stringify(). + * + * @param {*} value The value to convert to a JSON string. + * @param {Replacer | Array | null} [replacer] + * A function that alters the behavior of the stringification process, + * or an array of strings/numbers to indicate properties to exclude. + * @param {string | number} [space] + * A string or number to specify indentation or pretty-printing. + * @returns {string} The JSON string representation. + */ +const JSONStringify = (value, replacer, space) => { + if ("rawJSON" in JSON) { + return originalStringify( + value, + (key, value) => { + if (typeof value === "bigint") return JSON.rawJSON(value.toString()); + + if (Array.isArray(replacer) && replacer.includes(key)) return value; + + return value; + }, + space, + ); + } + + if (!value) return originalStringify(value, replacer, space); + + const convertedToCustomJSON = originalStringify( + value, + (key, value) => { + const isNoise = typeof value === "string" && noiseValue.test(value); + + if (isNoise) return value.toString() + "n"; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing + + if (typeof value === "bigint") return value.toString() + "n"; + + if (Array.isArray(replacer) && replacer.includes(key)) return value; + + return value; + }, + space, + ); + const processedJSON = convertedToCustomJSON.replace( + bigIntsStringify, + "$1$2$3", + ); // Delete one "n" off the end of every BigInt value + const denoisedJSON = processedJSON.replace(noiseStringify, "$1$2$3"); // Remove one "n" off the end of every noisy string + + return denoisedJSON; +}; + +const featureCache = new Map(); + +/** + * Detects if the current JSON.parse implementation supports the context.source feature. + * + * Uses toString() fingerprinting to cache results and automatically detect runtime + * replacements of JSON.parse (polyfills, mocks, etc.). + * + * @returns {boolean} true if context.source is supported, false otherwise. + */ +const isContextSourceSupported = () => { + const parseFingerprint = JSON.parse.toString(); + + if (featureCache.has(parseFingerprint)) { + return featureCache.get(parseFingerprint); + } + + try { + const result = JSON.parse( + "1", + (_, __, context) => !!context?.source && context.source === "1", + ); + featureCache.set(parseFingerprint, result); + + return result; + } catch { + featureCache.set(parseFingerprint, false); + + return false; + } +}; + +/** + * Reviver function that converts custom-format BigInt strings back to BigInt values. + * Also handles "noise" strings that accidentally match the BigInt format. + * + * @param {string | number | undefined} key The object key. + * @param {*} value The value being parsed. + * @param {object} [context] Parse context (if supported by JSON.parse). + * @param {Reviver} [userReviver] User's custom reviver function. + * @returns {any} The transformed value. + */ +const convertMarkedBigIntsReviver = (key, value, context, userReviver) => { + const isCustomFormatBigInt = + typeof value === "string" && customFormat.test(value); + if (isCustomFormatBigInt) return BigInt(value.slice(0, -1)); + + const isNoiseValue = typeof value === "string" && noiseValue.test(value); + if (isNoiseValue) return value.slice(0, -1); + + return value; +}; + +/** + * Fast JSON.parse implementation (~2x faster than classic fallback). + * Uses JSON.parse's context.source feature to detect integers and convert + * large numbers directly to BigInt without string manipulation. + * + * Does not support legacy custom format from v1 of this library. + * + * @param {string} text JSON string to parse. + * @param {Reviver} [reviver] Transform function to apply to each value. + * @returns {any} Parsed JavaScript value. + */ +const JSONParseV2 = (text, reviver) => { + return JSON.parse(text, (key, value, context) => { + const isBigNumber = + typeof value === "number" && + (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER); + const isInt = context && intRegex.test(context.source); + const isBigInt = isBigNumber && isInt; + + if (isBigInt) return BigInt(context.source); + + return value; + }); +}; + +const MAX_INT = Number.MAX_SAFE_INTEGER.toString(); +const MAX_DIGITS = MAX_INT.length; +const stringsOrLargeNumbers = + /"(?:\\.|[^"])*"|-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/g; +const noiseValueWithQuotes = /^"-?\d+n+"$/; // Noise - strings that match the custom format before being converted to it + +/** + * Converts a JSON string into a JavaScript value. + * + * Supports parsing of large integers using two strategies: + * 1. Classic fallback: Marks large numbers with "123n" format, then converts to BigInt + * 2. Fast path (JSONParseV2): Uses context.source feature (~2x faster) when available + * + * All other JSON values are parsed exactly like native JSON.parse(). + * + * @param {string} text A valid JSON string. + * @param {Reviver} [reviver] + * A function that transforms the results. This function is called for each member + * of the object. If a member contains nested objects, the nested objects are + * transformed before the parent object is. + * @returns {any} The parsed JavaScript value. + * @throws {SyntaxError} If text is not valid JSON. + */ +const JSONParse = (text, reviver) => { + if (!text) return originalParse(text, reviver); + + if (isContextSourceSupported()) return JSONParseV2(text); // Shortcut to a faster (2x) and simpler version + + // Find and mark big numbers with "n" + const serializedData = text.replace( + stringsOrLargeNumbers, + (text, digits, fractional, exponential) => { + const isString = text[0] === '"'; + const isNoise = isString && noiseValueWithQuotes.test(text); + + if (isNoise) return text.substring(0, text.length - 1) + 'n"'; // Mark noise values with additional "n" to offset the deletion of one "n" during the processing + + const isFractionalOrExponential = fractional || exponential; + const isLessThanMaxSafeInt = + digits && + (digits.length < MAX_DIGITS || + (digits.length === MAX_DIGITS && digits <= MAX_INT)); // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison + + if (isString || isFractionalOrExponential || isLessThanMaxSafeInt) + return text; + + return '"' + text + 'n"'; + }, + ); + + return originalParse(serializedData, (key, value, context) => + convertMarkedBigIntsReviver(key, value), + ); +}; + +class RequestError extends Error { + name; + /** + * http status code + */ + status; + /** + * Request options that lead to the error. + */ + request; + /** + * Response object if a response was received + */ + response; + constructor(message, statusCode, options) { + super(message, { cause: options.cause }); + this.name = "HttpError"; + this.status = Number.parseInt(statusCode); + if (Number.isNaN(this.status)) { + this.status = 0; + } + /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */ + if ("response" in options) { + this.response = options.response; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? ""; +async function fetchWrapper(requestOptions) { + const fetch = requestOptions.request?.fetch || globalThis.fetch; + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + const log = requestOptions.request?.log || console; + const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; + const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body; + const requestHeaders = Object.fromEntries( + Object.entries(requestOptions.headers).map(([name, value]) => [ + name, + String(value) + ]) + ); + let fetchResponse; + try { + fetchResponse = await fetch(requestOptions.url, { + method: requestOptions.method, + body, + redirect: requestOptions.request?.redirect, + headers: requestHeaders, + signal: requestOptions.request?.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }); + } catch (error) { + let message = "Unknown Error"; + if (error instanceof Error) { + if (error.name === "AbortError") { + error.status = 500; + throw error; + } + message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + } + const requestError = new RequestError(message, 500, { + request: requestOptions + }); + requestError.cause = error; + throw requestError; + } + const status = fetchResponse.status; + const url = fetchResponse.url; + const responseHeaders = {}; + for (const [key, value] of fetchResponse.headers) { + responseHeaders[key] = value; + } + const octokitResponse = { + url, + status, + headers: responseHeaders, + data: "" + }; + if ("deprecation" in responseHeaders) { + const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return octokitResponse; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return octokitResponse; + } + throw new RequestError(fetchResponse.statusText, status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status === 304) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError("Not modified", status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status >= 400) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError(toErrorMessage(octokitResponse.data), status, { + response: octokitResponse, + request: requestOptions + }); + } + octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; + return octokitResponse; +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (!contentType) { + return response.text().catch(noop$1); + } + const mimetype = distExports.parse(contentType); + if (isJSONResponse(mimetype)) { + let text = ""; + try { + text = await response.text(); + return JSONParse(text); + } catch (err) { + return text; + } + } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { + return response.text().catch(noop$1); + } else { + return response.arrayBuffer().catch( + /* v8 ignore next -- @preserve */ + () => new ArrayBuffer(0) + ); + } +} +function isJSONResponse(mimetype) { + return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; +} +function toErrorMessage(data) { + if (typeof data === "string") { + return data; + } + if (data instanceof ArrayBuffer) { + return "Unknown error"; + } + if ("message" in data) { + const suffix = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; + return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix}` : `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} + +// pkg/dist-src/with-defaults.js +function withDefaults$1(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults$1.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults$1.bind(null, endpoint2) + }); +} + +// pkg/dist-src/index.js +var request = withDefaults$1(endpoint, defaults_default); +/* v8 ignore next -- @preserve */ +/* v8 ignore else -- @preserve */ + +// pkg/dist-src/index.js + +// pkg/dist-src/version.js +var VERSION$3 = "0.0.0-development"; + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + name = "GraphqlResponseError"; + errors; + data; +}; + +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType", + "operationName" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} + +// pkg/dist-src/index.js +withDefaults(request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION$3} ${getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +// pkg/dist-src/is-jwt.js +var b64url = "(?:[a-zA-Z0-9_-]+)"; +var sep = "\\."; +var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); +var isJWT = jwtRE.test.bind(jwtRE); + +// pkg/dist-src/auth.js +async function auth(token) { + const isApp = isJWT(token); + const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); + const isUserToServer = token.startsWith("ghu_"); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + +const VERSION$2 = "7.0.6"; + +const noop = () => { +}; +const consoleWarn = console.warn.bind(console); +const consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop; + } + if (typeof logger.info !== "function") { + logger.info = noop; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +const userAgentTrail = `octokit-core.js/${VERSION$2} ${getUserAgent()}`; +class Octokit { + static VERSION = VERSION$2; + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static plugins = []; + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new Hook.Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = createTokenAuth(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } + // assigned during constructor + request; + graphql; + log; + hook; + // TODO: type `octokit.auth` based on passed options.authStrategy + auth; +} + +const VERSION$1 = "17.0.0"; + +const Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addRepoAccessToSelfHostedRunnerGroupInOrg: [ + "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], + createOrUpdateEnvironmentSecret: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteCustomImageFromOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" + ], + deleteCustomImageVersionFromOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" + ], + deleteEnvironmentSecret: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + deleteHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomImageForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}" + ], + getCustomImageVersionForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}" + ], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + getHostedRunnersGithubOwnedImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/github-owned" + ], + getHostedRunnersLimitsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/limits" + ], + getHostedRunnersMachineSpecsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/machine-sizes" + ], + getHostedRunnersPartnerImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/partner" + ], + getHostedRunnersPlatformsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/platforms" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listCustomImageVersionsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions" + ], + listCustomImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/custom" + ], + listEnvironmentSecrets: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + listGithubHostedRunnersInGroupForOrg: [ + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" + ], + listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + updateHostedRunnerForOrg: [ + "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubBillingPremiumRequestUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/premium_request/usage" + ], + getGithubBillingPremiumRequestUsageReportUser: [ + "GET /users/{username}/settings/billing/premium_request/usage" + ], + getGithubBillingUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/usage" + ], + getGithubBillingUsageReportUser: [ + "GET /users/{username}/settings/billing/usage" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + campaigns: { + createCampaign: ["POST /orgs/{org}/campaigns"], + deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], + getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], + listOrgCampaigns: ["GET /orgs/{org}/campaigns"], + updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + commitAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" + ], + createAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + createVariantAnalysis: [ + "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" + ], + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + deleteCodeqlDatabase: [ + "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getAutofix: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + getVariantAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" + ], + getVariantAnalysisRepoTask: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" + ], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codeSecurity: { + attachConfiguration: [ + "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" + ], + attachEnterpriseConfiguration: [ + "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" + ], + createConfiguration: ["POST /orgs/{org}/code-security/configurations"], + createConfigurationForEnterprise: [ + "POST /enterprises/{enterprise}/code-security/configurations" + ], + deleteConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" + ], + deleteConfigurationForEnterprise: [ + "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + detachConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/detach" + ], + getConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}" + ], + getConfigurationForRepository: [ + "GET /repos/{owner}/{repo}/code-security-configuration" + ], + getConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations" + ], + getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], + getDefaultConfigurations: [ + "GET /orgs/{org}/code-security/configurations/defaults" + ], + getDefaultConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/defaults" + ], + getRepositoriesForConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" + ], + getRepositoriesForEnterpriseConfiguration: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" + ], + getSingleConfigurationForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + setConfigurationAsDefault: [ + "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" + ], + setConfigurationAsDefaultForEnterprise: [ + "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" + ], + updateConfiguration: [ + "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" + ], + updateEnterpriseConfiguration: [ + "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], + copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + credentials: { revoke: ["POST /credentials/revoke"] }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + repositoryAccessForOrg: [ + "GET /organizations/{org}/dependabot/repository-access" + ], + setRepositoryAccessDefaultLevel: [ + "PUT /organizations/{org}/dependabot/repository-access/default-level" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ], + updateRepositoryAccessForOrg: [ + "PATCH /organizations/{org}/dependabot/repository-access" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + enterpriseTeamMemberships: { + add: [ + "PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ], + bulkAdd: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add" + ], + bulkRemove: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove" + ], + get: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ], + list: ["GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships"], + remove: [ + "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}" + ] + }, + enterpriseTeamOrganizations: { + add: [ + "PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + bulkAdd: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add" + ], + bulkRemove: [ + "POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove" + ], + delete: [ + "DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + getAssignment: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}" + ], + getAssignments: [ + "GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations" + ] + }, + enterpriseTeams: { + create: ["POST /enterprises/{enterprise}/teams"], + delete: ["DELETE /enterprises/{enterprise}/teams/{team_slug}"], + get: ["GET /enterprises/{enterprise}/teams/{team_slug}"], + list: ["GET /enterprises/{enterprise}/teams"], + update: ["PATCH /enterprises/{enterprise}/teams/{team_slug}"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + hostedCompute: { + createNetworkConfigurationForOrg: [ + "POST /orgs/{org}/settings/network-configurations" + ], + deleteNetworkConfigurationFromOrg: [ + "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkConfigurationForOrg: [ + "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkSettingsForOrg: [ + "GET /orgs/{org}/settings/network-settings/{network_settings_id}" + ], + listNetworkConfigurationsForOrg: [ + "GET /orgs/{org}/settings/network-configurations" + ], + updateNetworkConfigurationForOrg: [ + "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addBlockedByDependency: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + addSubIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listDependenciesBlockedBy: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + listDependenciesBlocking: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" + ], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + listSubIssues: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeDependencyBlockedBy: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + removeSubIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" + ], + reprioritizeSubIssue: [ + "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" + } + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createArtifactStorageRecord: [ + "POST /orgs/{org}/artifacts/metadata/storage-record" + ], + createInvitation: ["POST /orgs/{org}/invitations"], + createIssueType: ["POST /orgs/{org}/issue-types"], + createWebhook: ["POST /orgs/{org}/hooks"], + customPropertiesForOrgsCreateOrUpdateOrganizationValues: [ + "PATCH /organizations/{org}/org-properties/values" + ], + customPropertiesForOrgsGetOrganizationValues: [ + "GET /organizations/{org}/org-properties/values" + ], + customPropertiesForReposCreateOrUpdateOrganizationDefinition: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposCreateOrUpdateOrganizationDefinitions: [ + "PATCH /orgs/{org}/properties/schema" + ], + customPropertiesForReposCreateOrUpdateOrganizationValues: [ + "PATCH /orgs/{org}/properties/values" + ], + customPropertiesForReposDeleteOrganizationDefinition: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposGetOrganizationDefinition: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + customPropertiesForReposGetOrganizationDefinitions: [ + "GET /orgs/{org}/properties/schema" + ], + customPropertiesForReposGetOrganizationValues: [ + "GET /orgs/{org}/properties/values" + ], + delete: ["DELETE /orgs/{org}"], + deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], + deleteAttestationsById: [ + "DELETE /orgs/{org}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /orgs/{org}/attestations/digest/{subject_digest}" + ], + deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + disableSelectedRepositoryImmutableReleasesOrganization: [ + "DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" + ], + enableSelectedRepositoryImmutableReleasesOrganization: [ + "PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}" + ], + get: ["GET /orgs/{org}"], + getImmutableReleasesSettings: [ + "GET /orgs/{org}/settings/immutable-releases" + ], + getImmutableReleasesSettingsRepositories: [ + "GET /orgs/{org}/settings/immutable-releases/repositories" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], + getOrgRulesetVersion: [ + "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" + ], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listArtifactStorageRecords: [ + "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" + ], + listAttestationRepositories: ["GET /orgs/{org}/attestations/repositories"], + listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listIssueTypes: ["GET /orgs/{org}/issue-types"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: [ + "GET /orgs/{org}/security-managers", + {}, + { + deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" + } + ], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" + } + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setImmutableReleasesSettings: [ + "PUT /orgs/{org}/settings/immutable-releases" + ], + setImmutableReleasesSettingsRepositories: [ + "PUT /orgs/{org}/settings/immutable-releases/repositories" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + privateRegistries: { + createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], + deleteOrgPrivateRegistry: [ + "DELETE /orgs/{org}/private-registries/{secret_name}" + ], + getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], + getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], + listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], + updateOrgPrivateRegistry: [ + "PATCH /orgs/{org}/private-registries/{secret_name}" + ] + }, + projects: { + addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], + addItemForUser: [ + "POST /users/{username}/projectsV2/{project_number}/items" + ], + deleteItemForOrg: [ + "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + deleteItemForUser: [ + "DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}" + ], + getFieldForOrg: [ + "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" + ], + getFieldForUser: [ + "GET /users/{username}/projectsV2/{project_number}/fields/{field_id}" + ], + getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], + getForUser: ["GET /users/{username}/projectsV2/{project_number}"], + getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], + getUserItem: [ + "GET /users/{username}/projectsV2/{project_number}/items/{item_id}" + ], + listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], + listFieldsForUser: [ + "GET /users/{username}/projectsV2/{project_number}/fields" + ], + listForOrg: ["GET /orgs/{org}/projectsV2"], + listForUser: ["GET /users/{username}/projectsV2"], + listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], + listItemsForUser: [ + "GET /users/{username}/projectsV2/{project_number}/items" + ], + updateItemForOrg: [ + "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + updateItemForUser: [ + "PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}" + ] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkImmutableReleases: ["GET /repos/{owner}/{repo}/immutable-releases"], + checkPrivateVulnerabilityReporting: [ + "GET /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAttestation: ["POST /repos/{owner}/{repo}/attestations"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + customPropertiesForReposCreateOrUpdateRepositoryValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + customPropertiesForReposGetRepositoryValues: [ + "GET /repos/{owner}/{repo}/properties/values" + ], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disableImmutableReleases: [ + "DELETE /repos/{owner}/{repo}/immutable-releases" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enableImmutableReleases: ["PUT /repos/{owner}/{repo}/immutable-releases"], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesetHistory: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" + ], + getRepoRulesetVersion: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" + ], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAttestations: [ + "GET /repos/{owner}/{repo}/attestations/{subject_digest}" + ], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + createPushProtectionBypass: [ + "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + listOrgPatternConfigs: [ + "GET /orgs/{org}/secret-scanning/pattern-configurations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + updateOrgPatternConfigs: [ + "PATCH /orgs/{org}/secret-scanning/pattern-configurations" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteAttestationsBulk: [ + "POST /users/{username}/attestations/delete-request" + ], + deleteAttestationsById: [ + "DELETE /users/{username}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /users/{username}/attestations/digest/{subject_digest}" + ], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getById: ["GET /user/{account_id}"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; +var endpoints_default = Endpoints; + +const endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +const handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} + +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION$1; + +// pkg/dist-src/version.js +var VERSION = "0.0.0-development"; + +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); + if (!responseNeedsNormalization) return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + const totalCommits = response.data.total_commits; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + delete response.data.total_commits; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + response.data.total_commits = totalCommits; + return response; +} + +// pkg/dist-src/iterator.js +function iterator$1(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) return { done: true }; + try { + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + if (!url && "total_commits" in normalizedResponse.data) { + const parsedUrl = new URL(normalizedResponse.url); + const params = parsedUrl.searchParams; + const page = parseInt(params.get("page") || "1", 10); + const per_page = parseInt(params.get("per_page") || "250", 10); + if (page * per_page < normalizedResponse.data.total_commits) { + params.set("page", String(page + 1)); + url = parsedUrl.toString(); + } + } + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} + +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator$1(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} + +// pkg/dist-src/compose-paginate.js +Object.assign(paginate, { + iterator: iterator$1 +}); + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator$1.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; + +new Context(); +const baseUrl = getApiBaseUrl(); +const defaults = { + baseUrl, + request: { + agent: getProxyAgent(baseUrl), + fetch: getProxyFetch(baseUrl) + } +}; +const GitHub = Octokit.plugin(restEndpointMethods, paginateRest).defaults(defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + // Orchestration ID + const userAgent = getUserAgentWithOrchestrationId(opts.userAgent); + if (userAgent) { + opts.userAgent = userAgent; + } + return opts; +} + +const context = new Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(getOctokitOptions(token)); +} + +var adaptivecardsTemplating = {}; + +var templateEngine = {}; + +var lib$1 = {}; + +var expressionFunctions = {}; + +var builtinFunctions = {}; + +var abs = {}; + +var expressionType = {}; + +var hasRequiredExpressionType; + +function requireExpressionType () { + if (hasRequiredExpressionType) return expressionType; + hasRequiredExpressionType = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(expressionType, "__esModule", { value: true }); + expressionType.ExpressionType = void 0; + /** + * Built-in expression types. + */ + class ExpressionType { + } + expressionType.ExpressionType = ExpressionType; + // Math + ExpressionType.Add = '+'; + ExpressionType.Subtract = '-'; + ExpressionType.Multiply = '*'; + ExpressionType.Divide = '/'; + ExpressionType.Min = 'min'; + ExpressionType.Max = 'max'; + ExpressionType.Power = '^'; + ExpressionType.Mod = '%'; + ExpressionType.Average = 'average'; + ExpressionType.Sum = 'sum'; + ExpressionType.Count = 'count'; + ExpressionType.Range = 'range'; + ExpressionType.Floor = 'floor'; + ExpressionType.Ceiling = 'ceiling'; + ExpressionType.Round = 'round'; + ExpressionType.Abs = 'abs'; + ExpressionType.Sqrt = 'sqrt'; + // Comparisons + ExpressionType.LessThan = '<'; + ExpressionType.LessThanOrEqual = '<='; + ExpressionType.Equal = '=='; + ExpressionType.NotEqual = '!='; + ExpressionType.GreaterThan = '>'; + ExpressionType.GreaterThanOrEqual = '>='; + ExpressionType.Exists = 'exists'; + ExpressionType.Contains = 'contains'; + ExpressionType.Empty = 'empty'; + // Logic + ExpressionType.And = '&&'; + ExpressionType.Or = '||'; + ExpressionType.Not = '!'; + // String + ExpressionType.Concat = 'concat'; + ExpressionType.Length = 'length'; + ExpressionType.Replace = 'replace'; + ExpressionType.ReplaceIgnoreCase = 'replaceIgnoreCase'; + ExpressionType.Split = 'split'; + ExpressionType.Substring = 'substring'; + ExpressionType.ToLower = 'toLower'; + ExpressionType.ToUpper = 'toUpper'; + ExpressionType.Trim = 'trim'; + ExpressionType.Join = 'join'; + ExpressionType.EndsWith = 'endsWith'; + ExpressionType.StartsWith = 'startsWith'; + ExpressionType.CountWord = 'countWord'; + ExpressionType.AddOrdinal = 'addOrdinal'; + ExpressionType.NewGuid = 'newGuid'; + ExpressionType.IndexOf = 'indexOf'; + ExpressionType.LastIndexOf = 'lastIndexOf'; + ExpressionType.EOL = 'EOL'; + ExpressionType.SentenceCase = 'sentenceCase'; + ExpressionType.TitleCase = 'titleCase'; + // DateTime + ExpressionType.AddDays = 'addDays'; + ExpressionType.AddHours = 'addHours'; + ExpressionType.AddMinutes = 'addMinutes'; + ExpressionType.AddSeconds = 'addSeconds'; + ExpressionType.DayOfMonth = 'dayOfMonth'; + ExpressionType.DayOfWeek = 'dayOfWeek'; + ExpressionType.DayOfYear = 'dayOfYear'; + ExpressionType.Month = 'month'; + ExpressionType.Date = 'date'; + ExpressionType.Year = 'year'; + ExpressionType.UtcNow = 'utcNow'; + ExpressionType.FormatDateTime = 'formatDateTime'; + ExpressionType.FormatEpoch = 'formatEpoch'; + ExpressionType.FormatTicks = 'formatTicks'; + ExpressionType.SubtractFromTime = 'subtractFromTime'; + ExpressionType.DateReadBack = 'dateReadBack'; + ExpressionType.GetTimeOfDay = 'getTimeOfDay'; + ExpressionType.GetFutureTime = 'getFutureTime'; + ExpressionType.GetPastTime = 'getPastTime'; + ExpressionType.ConvertFromUTC = 'convertFromUTC'; + ExpressionType.ConvertToUTC = 'convertToUTC'; + ExpressionType.AddToTime = 'addToTime'; + ExpressionType.StartOfDay = 'startOfDay'; + ExpressionType.StartOfHour = 'startOfHour'; + ExpressionType.StartOfMonth = 'startOfMonth'; + ExpressionType.Ticks = 'ticks'; + ExpressionType.TicksToDays = 'ticksToDays'; + ExpressionType.TicksToHours = 'ticksToHours'; + ExpressionType.TicksToMinutes = 'ticksToMinutes'; + ExpressionType.DateTimeDiff = 'dateTimeDiff'; + // timex + ExpressionType.IsDefinite = 'isDefinite'; + ExpressionType.IsTime = 'isTime'; + ExpressionType.IsDuration = 'isDuration'; + ExpressionType.IsDate = 'isDate'; + ExpressionType.IsTimeRange = 'isTimeRange'; + ExpressionType.IsDateRange = 'isDateRange'; + ExpressionType.IsPresent = 'isPresent'; + ExpressionType.GetNextViableDate = 'getNextViableDate'; + ExpressionType.GetPreviousViableDate = 'getPreviousViableDate'; + ExpressionType.GetNextViableTime = 'getNextViableTime'; + ExpressionType.GetPreviousViableTime = 'getPreviousViableTime'; + ExpressionType.TimexResolve = 'resolve'; + // Conversions + ExpressionType.Float = 'float'; + ExpressionType.Int = 'int'; + ExpressionType.String = 'string'; + ExpressionType.Bool = 'bool'; + ExpressionType.Binary = 'binary'; + ExpressionType.Base64 = 'base64'; + ExpressionType.Base64ToBinary = 'base64ToBinary'; + ExpressionType.Base64ToString = 'base64ToString'; + ExpressionType.DataUri = 'dataUri'; + ExpressionType.DataUriToBinary = 'dataUriToBinary'; + ExpressionType.DataUriToString = 'dataUriToString'; + ExpressionType.UriComponent = 'uriComponent'; + ExpressionType.UriComponentToString = 'uriComponentToString'; + ExpressionType.FormatNumber = 'formatNumber'; + ExpressionType.JsonStringify = 'jsonStringify'; + // Memory + ExpressionType.Accessor = 'Accessor'; + ExpressionType.Element = 'Element'; + ExpressionType.CreateArray = 'createArray'; + // Collection + ExpressionType.First = 'first'; + ExpressionType.Last = 'last'; + ExpressionType.Foreach = 'foreach'; + ExpressionType.Select = 'select'; + ExpressionType.Where = 'where'; + ExpressionType.Union = 'union'; + ExpressionType.Intersection = 'intersection'; + ExpressionType.Skip = 'skip'; + ExpressionType.Take = 'take'; + ExpressionType.FilterNotEqual = 'filterNotEqual'; + ExpressionType.SubArray = 'subArray'; + ExpressionType.SortBy = 'sortBy'; + ExpressionType.SortByDescending = 'sortByDescending'; + ExpressionType.IndicesAndValues = 'indicesAndValues'; + ExpressionType.Flatten = 'flatten'; + ExpressionType.Unique = 'unique'; + ExpressionType.Reverse = 'reverse'; + ExpressionType.Any = 'any'; + ExpressionType.All = 'all'; + // Misc + ExpressionType.Constant = 'Constant'; + ExpressionType.Lambda = 'Lambda'; + ExpressionType.If = 'if'; + ExpressionType.Rand = 'rand'; + // Object manipulation and construction functions + ExpressionType.Json = 'json'; + ExpressionType.AddProperty = 'addProperty'; + ExpressionType.RemoveProperty = 'removeProperty'; + ExpressionType.SetProperty = 'setProperty'; + ExpressionType.GetProperty = 'getProperty'; + ExpressionType.Coalesce = 'coalesce'; + ExpressionType.JPath = 'jPath'; + ExpressionType.SetPathToValue = 'setPathToValue'; + ExpressionType.Merge = 'merge'; + ExpressionType.XML = 'xml'; + ExpressionType.XPath = 'xPath'; + // URI parsing functions + ExpressionType.UriHost = 'uriHost'; + ExpressionType.UriPath = 'uriPath'; + ExpressionType.UriPathAndQuery = 'uriPathAndQuery'; + ExpressionType.UriPort = 'uriPort'; + ExpressionType.UriQuery = 'uriQuery'; + ExpressionType.UriScheme = 'uriScheme'; + // Regar expression + ExpressionType.IsMatch = 'isMatch'; + //Type Checking + ExpressionType.IsString = 'isString'; + ExpressionType.IsInteger = 'isInteger'; + ExpressionType.IsArray = 'isArray'; + ExpressionType.IsObject = 'isObject'; + ExpressionType.IsFloat = 'isFloat'; + ExpressionType.IsDateTime = 'isDateTime'; + ExpressionType.IsBoolean = 'isBoolean'; + // StringOrValue + ExpressionType.StringOrValue = 'stringOrValue'; + ExpressionType.Ignore = 'ignore'; + ExpressionType.Optional = 'optional'; + + return expressionType; +} + +var numberTransformEvaluator = {}; + +var expressionEvaluator = {}; + +var returnType = {}; + +var hasRequiredReturnType; + +function requireReturnType () { + if (hasRequiredReturnType) return returnType; + hasRequiredReturnType = 1; + (function (exports) { + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ReturnType = void 0; + (function (ReturnType) { + /** + * True or false boolean value. + */ + ReturnType[ReturnType["Boolean"] = 1] = "Boolean"; + /** + * Numerical value like int, float, double, ... + */ + ReturnType[ReturnType["Number"] = 2] = "Number"; + /** + * Any value is possible. + */ + ReturnType[ReturnType["Object"] = 4] = "Object"; + /** + * String value. + */ + ReturnType[ReturnType["String"] = 8] = "String"; + /** + * Array value. + */ + ReturnType[ReturnType["Array"] = 16] = "Array"; + })(exports.ReturnType || (exports.ReturnType = {})); + + } (returnType)); + return returnType; +} + +var hasRequiredExpressionEvaluator; + +function requireExpressionEvaluator () { + if (hasRequiredExpressionEvaluator) return expressionEvaluator; + hasRequiredExpressionEvaluator = 1; + Object.defineProperty(expressionEvaluator, "__esModule", { value: true }); + expressionEvaluator.ExpressionEvaluator = void 0; + const returnType_1 = requireReturnType(); + /** + * Information on how to evaluate an expression. + */ + class ExpressionEvaluator { + /** + * Initializes a new instance of the class. + * + * @param type Expression type. + * @param evaluator Delegate to evaluate an expression. + * @param returnType Type expected from evaluation. + * @param validator Static validation of expression. + */ + constructor(type, evaluator, returnType = returnType_1.ReturnType.Object, validator) { + /** + * Evaluate an expression. + * + * @param expression Expression to evaluate. + * @param state Global state information. + * @param options Options used in the evaluation. + * @returns The value and error string that is non-null if there is an error. + */ + this.tryEvaluate = (expression, state, options) => this._evaluator(expression, state, options); + /** + * Validate an expression. + * + * @param expression Expression to validate. + * @returns The validated expression. + */ + this.validateExpression = (expression) => this._validator(expression); + this.type = type; + this._evaluator = evaluator; + this.returnType = returnType; + this._validator = + validator || + ((_expr) => { + //noop + }); + } + /** + * Gets the evaluator that is a negation of this one. + * + * @returns The evaluator that is a negation of this one. + */ + get negation() { + return this._negation; + } + /** + * Sets the evaluator that is a negation of this one. + */ + set negation(value) { + value._negation = this; + this._negation = value; + } + } + expressionEvaluator.ExpressionEvaluator = ExpressionEvaluator; + + return expressionEvaluator; +} + +var functionUtils = {}; + +var datetimeFormatConverter = {}; + +var hasRequiredDatetimeFormatConverter; + +function requireDatetimeFormatConverter () { + if (hasRequiredDatetimeFormatConverter) return datetimeFormatConverter; + hasRequiredDatetimeFormatConverter = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(datetimeFormatConverter, "__esModule", { value: true }); + datetimeFormatConverter.convertCSharpDateTimeToDayjs = void 0; + var State; + (function (State) { + State[State["None"] = 0] = "None"; + State[State["LowerD1"] = 1] = "LowerD1"; + State[State["LowerD2"] = 2] = "LowerD2"; + State[State["LowerD3"] = 3] = "LowerD3"; + State[State["LowerD4"] = 4] = "LowerD4"; + State[State["LowerF1"] = 5] = "LowerF1"; + State[State["LowerF2"] = 6] = "LowerF2"; + State[State["LowerF3"] = 7] = "LowerF3"; + State[State["CapitalF1"] = 8] = "CapitalF1"; + State[State["CapitalF2"] = 9] = "CapitalF2"; + State[State["CapitalF3"] = 10] = "CapitalF3"; + State[State["LowerG"] = 11] = "LowerG"; + State[State["LowerH1"] = 12] = "LowerH1"; + State[State["LowerH2"] = 13] = "LowerH2"; + State[State["CapitalH1"] = 14] = "CapitalH1"; + State[State["CapitalH2"] = 15] = "CapitalH2"; + State[State["CapitalK"] = 16] = "CapitalK"; + State[State["LowerM1"] = 17] = "LowerM1"; + State[State["LowerM2"] = 18] = "LowerM2"; + State[State["CapitalM1"] = 19] = "CapitalM1"; + State[State["CapitalM2"] = 20] = "CapitalM2"; + State[State["CapitalM3"] = 21] = "CapitalM3"; + State[State["CapitalM4"] = 22] = "CapitalM4"; + State[State["LowerS1"] = 23] = "LowerS1"; + State[State["LowerS2"] = 24] = "LowerS2"; + State[State["LowerT1"] = 25] = "LowerT1"; + State[State["LowerT2"] = 26] = "LowerT2"; + State[State["LowerY1"] = 27] = "LowerY1"; + State[State["LowerY2"] = 28] = "LowerY2"; + State[State["LowerY3"] = 29] = "LowerY3"; + State[State["LowerY4"] = 30] = "LowerY4"; + State[State["LowerZ1"] = 31] = "LowerZ1"; + State[State["LowerZ2"] = 32] = "LowerZ2"; + State[State["LowerZ3"] = 33] = "LowerZ3"; + State[State["InSingleQuoteLiteral"] = 34] = "InSingleQuoteLiteral"; + State[State["InDoubleQuoteLiteral"] = 35] = "InDoubleQuoteLiteral"; + State[State["EscapeSequence"] = 36] = "EscapeSequence"; + })(State || (State = {})); + /** + * Convert a CSharp style datetime format string to a Day.js style datetime format string. Ref: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings + * + * @param fmtString A CSharp style datetime format string. Ref: https://day.js.org/docs/en/display/format + * @returns A Momengt.js style datetime format string. + */ + function convertCSharpDateTimeToDayjs(fmtString) { + let fmtResult = ''; + let fmtState = State.None; + let lTokenBuffer = ''; + if (fmtString.length === 0) { + return fmtResult; + } + if (fmtString.length === 1) { + switch (fmtString) { + case 'R': + case 'r': + throw Error('RFC 1123 not supported in Day.js'); + case 'O': + case 'o': + fmtString = 'YYYY-MM-DDTHH:mm:ss.SSS0000Z'; + break; + case 'U': + throw new Error('Universal Fulll Format not supported in Day.js'); + case 'u': + throw new Error('Universal Sortable Format not supported in Day.js'); + } + } + const changeState = (newState) => { + switch (fmtState) { + case State.LowerD1: + fmtResult += 'D'; + break; + case State.LowerD2: + fmtResult += 'DD'; + break; + case State.LowerD3: + fmtResult += 'ddd'; + break; + case State.LowerD4: + fmtResult += 'dddd'; + break; + case State.LowerF1: + case State.CapitalF1: + throw Error('S not supported in Day.js'); + case State.LowerF2: + case State.CapitalF2: + throw Error('SS not supported in Day.js'); + case State.LowerF3: + case State.CapitalF3: + fmtResult += 'SSS'; + break; + case State.LowerG: + throw Error('Era not supported in Day.js'); + case State.LowerH1: + fmtResult += 'h'; + break; + case State.LowerH2: + fmtResult += 'hh'; + break; + case State.CapitalH1: + fmtResult += 'H'; + break; + case State.CapitalH2: + fmtResult += 'HH'; + break; + case State.LowerM1: + fmtResult += 'm'; + break; + case State.LowerM2: + fmtResult += 'mm'; + break; + case State.CapitalM1: + fmtResult += 'M'; + break; + case State.CapitalM2: + fmtResult += 'MM'; + break; + case State.CapitalM3: + fmtResult += 'MMM'; + break; + case State.CapitalM4: + fmtResult += 'MMMM'; + break; + case State.LowerS1: + fmtResult += 's'; + break; + case State.LowerS2: + fmtResult += 'ss'; + break; + case State.LowerT1: + case State.LowerT2: + fmtResult += 'A'; + break; + case State.LowerY1: + case State.LowerY2: + fmtResult += 'YY'; + break; + case State.LowerY3: + case State.LowerY4: + fmtResult += 'YYYY'; + break; + case State.LowerZ1: + case State.LowerZ2: + fmtResult += 'ZZ'; + break; + case State.LowerZ3: + fmtResult += 'Z'; + break; + case State.InSingleQuoteLiteral: + case State.InDoubleQuoteLiteral: + case State.EscapeSequence: + for (const lCharacter of lTokenBuffer) { + fmtResult += lCharacter; + } + break; + } + lTokenBuffer = ''; + fmtState = newState; + }; + for (const character of fmtString) { + if (fmtState === State.EscapeSequence) { + lTokenBuffer += character; + changeState(State.None); + } + else if (fmtState === State.InDoubleQuoteLiteral) { + if (character === '`') { + changeState(State.None); + } + else { + lTokenBuffer += character; + } + } + else if (fmtState === State.InSingleQuoteLiteral) { + if (character === "'") { + changeState(State.None); + } + else { + lTokenBuffer += character; + } + } + else { + switch (character) { + case 'd': + switch (fmtState) { + case State.LowerD1: + fmtState = State.LowerD2; + break; + case State.LowerD2: + fmtState = State.LowerD3; + break; + case State.LowerD3: + fmtState = State.LowerD4; + break; + case State.LowerD4: + break; + default: + changeState(State.LowerD1); + break; + } + break; + case 'f': + switch (fmtState) { + case State.LowerF1: + fmtState = State.LowerF2; + break; + case State.LowerF2: + fmtState = State.LowerF3; + break; + case State.LowerF3: + break; + default: + changeState(State.LowerF1); + break; + } + break; + case 'F': + switch (fmtState) { + case State.CapitalF1: + fmtState = State.CapitalF2; + break; + case State.CapitalF2: + fmtState = State.CapitalF3; + break; + case State.CapitalF3: + break; + default: + changeState(State.CapitalF1); + break; + } + break; + case 'g': + switch (fmtState) { + case State.LowerG: + break; + default: + changeState(State.LowerG); + break; + } + break; + case 'h': + switch (fmtState) { + case State.LowerH1: + fmtState = State.LowerH2; + break; + case State.LowerH2: + break; + default: + changeState(State.LowerH1); + break; + } + break; + case 'H': + switch (fmtState) { + case State.CapitalH1: + fmtState = State.CapitalH2; + break; + case State.CapitalH2: + break; + default: + changeState(State.CapitalH1); + break; + } + break; + case 'K': + changeState(State.None); + fmtResult += 'Z'; + break; + case 'm': + switch (fmtState) { + case State.LowerM1: + fmtState = State.LowerM2; + break; + case State.LowerM2: + break; + default: + changeState(State.LowerM1); + break; + } + break; + case 'M': + switch (fmtState) { + case State.CapitalM1: + fmtState = State.CapitalM2; + break; + case State.CapitalM2: + fmtState = State.CapitalM3; + break; + case State.CapitalM3: + fmtState = State.CapitalM4; + break; + case State.CapitalM4: + break; + default: + changeState(State.CapitalM1); + break; + } + break; + case 's': + switch (fmtState) { + case State.LowerS1: + fmtState = State.LowerS2; + break; + case State.LowerS2: + break; + default: + changeState(State.LowerS1); + break; + } + break; + case 't': + switch (fmtState) { + case State.LowerT1: + fmtState = State.LowerT2; + break; + case State.LowerT2: + break; + default: + changeState(State.LowerT1); + break; + } + break; + case 'y': + switch (fmtState) { + case State.LowerY1: + fmtState = State.LowerY2; + break; + case State.LowerY2: + fmtState = State.LowerY3; + break; + case State.LowerY3: + fmtState = State.LowerY4; + break; + case State.LowerY4: + break; + default: + changeState(State.LowerY1); + break; + } + break; + case 'z': + switch (fmtState) { + case State.LowerZ1: + fmtState = State.LowerZ2; + break; + case State.LowerZ2: + fmtState = State.LowerZ3; + break; + case State.LowerZ3: + break; + default: + changeState(State.LowerZ1); + break; + } + break; + case ':': + changeState(State.None); + fmtResult += ':'; + break; + case '/': + changeState(State.None); + fmtResult += '/'; + break; + case '`': + changeState(State.InDoubleQuoteLiteral); + break; + case "'": + changeState(State.InSingleQuoteLiteral); + break; + case '%': + changeState(State.None); + break; + case '\\': + changeState(State.EscapeSequence); + break; + default: + changeState(State.None); + fmtResult += character; + break; + } + } + } + if (fmtState === State.EscapeSequence || + fmtState === State.InDoubleQuoteLiteral || + fmtState === State.InSingleQuoteLiteral) { + throw Error('Invalid Format String'); + } + changeState(State.None); + return fmtResult; + } + datetimeFormatConverter.convertCSharpDateTimeToDayjs = convertCSharpDateTimeToDayjs; + + return datetimeFormatConverter; +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + +var _listCacheClear; +var hasRequired_listCacheClear; + +function require_listCacheClear () { + if (hasRequired_listCacheClear) return _listCacheClear; + hasRequired_listCacheClear = 1; + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + _listCacheClear = listCacheClear; + return _listCacheClear; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + +var eq_1; +var hasRequiredEq; + +function requireEq () { + if (hasRequiredEq) return eq_1; + hasRequiredEq = 1; + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + eq_1 = eq; + return eq_1; +} + +var _assocIndexOf; +var hasRequired_assocIndexOf; + +function require_assocIndexOf () { + if (hasRequired_assocIndexOf) return _assocIndexOf; + hasRequired_assocIndexOf = 1; + var eq = requireEq(); + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + _assocIndexOf = assocIndexOf; + return _assocIndexOf; +} + +var _listCacheDelete; +var hasRequired_listCacheDelete; + +function require_listCacheDelete () { + if (hasRequired_listCacheDelete) return _listCacheDelete; + hasRequired_listCacheDelete = 1; + var assocIndexOf = require_assocIndexOf(); + + /** Used for built-in method references. */ + var arrayProto = Array.prototype; + + /** Built-in value references. */ + var splice = arrayProto.splice; + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + _listCacheDelete = listCacheDelete; + return _listCacheDelete; +} + +var _listCacheGet; +var hasRequired_listCacheGet; + +function require_listCacheGet () { + if (hasRequired_listCacheGet) return _listCacheGet; + hasRequired_listCacheGet = 1; + var assocIndexOf = require_assocIndexOf(); + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + _listCacheGet = listCacheGet; + return _listCacheGet; +} + +var _listCacheHas; +var hasRequired_listCacheHas; + +function require_listCacheHas () { + if (hasRequired_listCacheHas) return _listCacheHas; + hasRequired_listCacheHas = 1; + var assocIndexOf = require_assocIndexOf(); + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + _listCacheHas = listCacheHas; + return _listCacheHas; +} + +var _listCacheSet; +var hasRequired_listCacheSet; + +function require_listCacheSet () { + if (hasRequired_listCacheSet) return _listCacheSet; + hasRequired_listCacheSet = 1; + var assocIndexOf = require_assocIndexOf(); + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + _listCacheSet = listCacheSet; + return _listCacheSet; +} + +var _ListCache; +var hasRequired_ListCache; + +function require_ListCache () { + if (hasRequired_ListCache) return _ListCache; + hasRequired_ListCache = 1; + var listCacheClear = require_listCacheClear(), + listCacheDelete = require_listCacheDelete(), + listCacheGet = require_listCacheGet(), + listCacheHas = require_listCacheHas(), + listCacheSet = require_listCacheSet(); + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + _ListCache = ListCache; + return _ListCache; +} + +var _stackClear; +var hasRequired_stackClear; + +function require_stackClear () { + if (hasRequired_stackClear) return _stackClear; + hasRequired_stackClear = 1; + var ListCache = require_ListCache(); + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + _stackClear = stackClear; + return _stackClear; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +var _stackDelete; +var hasRequired_stackDelete; + +function require_stackDelete () { + if (hasRequired_stackDelete) return _stackDelete; + hasRequired_stackDelete = 1; + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + _stackDelete = stackDelete; + return _stackDelete; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +var _stackGet; +var hasRequired_stackGet; + +function require_stackGet () { + if (hasRequired_stackGet) return _stackGet; + hasRequired_stackGet = 1; + function stackGet(key) { + return this.__data__.get(key); + } + + _stackGet = stackGet; + return _stackGet; +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +var _stackHas; +var hasRequired_stackHas; + +function require_stackHas () { + if (hasRequired_stackHas) return _stackHas; + hasRequired_stackHas = 1; + function stackHas(key) { + return this.__data__.has(key); + } + + _stackHas = stackHas; + return _stackHas; +} + +/** Detect free variable `global` from Node.js. */ + +var _freeGlobal; +var hasRequired_freeGlobal; + +function require_freeGlobal () { + if (hasRequired_freeGlobal) return _freeGlobal; + hasRequired_freeGlobal = 1; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + + _freeGlobal = freeGlobal; + return _freeGlobal; +} + +var _root; +var hasRequired_root; + +function require_root () { + if (hasRequired_root) return _root; + hasRequired_root = 1; + var freeGlobal = require_freeGlobal(); + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + _root = root; + return _root; +} + +var _Symbol; +var hasRequired_Symbol; + +function require_Symbol () { + if (hasRequired_Symbol) return _Symbol; + hasRequired_Symbol = 1; + var root = require_root(); + + /** Built-in value references. */ + var Symbol = root.Symbol; + + _Symbol = Symbol; + return _Symbol; +} + +var _getRawTag; +var hasRequired_getRawTag; + +function require_getRawTag () { + if (hasRequired_getRawTag) return _getRawTag; + hasRequired_getRawTag = 1; + var Symbol = require_Symbol(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Built-in value references. */ + var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + _getRawTag = getRawTag; + return _getRawTag; +} + +/** Used for built-in method references. */ + +var _objectToString; +var hasRequired_objectToString; + +function require_objectToString () { + if (hasRequired_objectToString) return _objectToString; + hasRequired_objectToString = 1; + var objectProto = Object.prototype; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + _objectToString = objectToString; + return _objectToString; +} + +var _baseGetTag; +var hasRequired_baseGetTag; + +function require_baseGetTag () { + if (hasRequired_baseGetTag) return _baseGetTag; + hasRequired_baseGetTag = 1; + var Symbol = require_Symbol(), + getRawTag = require_getRawTag(), + objectToString = require_objectToString(); + + /** `Object#toString` result references. */ + var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + + /** Built-in value references. */ + var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + _baseGetTag = baseGetTag; + return _baseGetTag; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + +var isObject_1; +var hasRequiredIsObject$1; + +function requireIsObject$1 () { + if (hasRequiredIsObject$1) return isObject_1; + hasRequiredIsObject$1 = 1; + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + isObject_1 = isObject; + return isObject_1; +} + +var isFunction_1; +var hasRequiredIsFunction; + +function requireIsFunction () { + if (hasRequiredIsFunction) return isFunction_1; + hasRequiredIsFunction = 1; + var baseGetTag = require_baseGetTag(), + isObject = requireIsObject$1(); + + /** `Object#toString` result references. */ + var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + isFunction_1 = isFunction; + return isFunction_1; +} + +var _coreJsData; +var hasRequired_coreJsData; + +function require_coreJsData () { + if (hasRequired_coreJsData) return _coreJsData; + hasRequired_coreJsData = 1; + var root = require_root(); + + /** Used to detect overreaching core-js shims. */ + var coreJsData = root['__core-js_shared__']; + + _coreJsData = coreJsData; + return _coreJsData; +} + +var _isMasked; +var hasRequired_isMasked; + +function require_isMasked () { + if (hasRequired_isMasked) return _isMasked; + hasRequired_isMasked = 1; + var coreJsData = require_coreJsData(); + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + _isMasked = isMasked; + return _isMasked; +} + +/** Used for built-in method references. */ + +var _toSource; +var hasRequired_toSource; + +function require_toSource () { + if (hasRequired_toSource) return _toSource; + hasRequired_toSource = 1; + var funcProto = Function.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + _toSource = toSource; + return _toSource; +} + +var _baseIsNative; +var hasRequired_baseIsNative; + +function require_baseIsNative () { + if (hasRequired_baseIsNative) return _baseIsNative; + hasRequired_baseIsNative = 1; + var isFunction = requireIsFunction(), + isMasked = require_isMasked(), + isObject = requireIsObject$1(), + toSource = require_toSource(); + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used for built-in method references. */ + var funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + _baseIsNative = baseIsNative; + return _baseIsNative; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + +var _getValue; +var hasRequired_getValue; + +function require_getValue () { + if (hasRequired_getValue) return _getValue; + hasRequired_getValue = 1; + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + _getValue = getValue; + return _getValue; +} + +var _getNative; +var hasRequired_getNative; + +function require_getNative () { + if (hasRequired_getNative) return _getNative; + hasRequired_getNative = 1; + var baseIsNative = require_baseIsNative(), + getValue = require_getValue(); + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + _getNative = getNative; + return _getNative; +} + +var _Map; +var hasRequired_Map; + +function require_Map () { + if (hasRequired_Map) return _Map; + hasRequired_Map = 1; + var getNative = require_getNative(), + root = require_root(); + + /* Built-in method references that are verified to be native. */ + var Map = getNative(root, 'Map'); + + _Map = Map; + return _Map; +} + +var _nativeCreate; +var hasRequired_nativeCreate; + +function require_nativeCreate () { + if (hasRequired_nativeCreate) return _nativeCreate; + hasRequired_nativeCreate = 1; + var getNative = require_getNative(); + + /* Built-in method references that are verified to be native. */ + var nativeCreate = getNative(Object, 'create'); + + _nativeCreate = nativeCreate; + return _nativeCreate; +} + +var _hashClear; +var hasRequired_hashClear; + +function require_hashClear () { + if (hasRequired_hashClear) return _hashClear; + hasRequired_hashClear = 1; + var nativeCreate = require_nativeCreate(); + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + _hashClear = hashClear; + return _hashClear; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +var _hashDelete; +var hasRequired_hashDelete; + +function require_hashDelete () { + if (hasRequired_hashDelete) return _hashDelete; + hasRequired_hashDelete = 1; + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + _hashDelete = hashDelete; + return _hashDelete; +} + +var _hashGet; +var hasRequired_hashGet; + +function require_hashGet () { + if (hasRequired_hashGet) return _hashGet; + hasRequired_hashGet = 1; + var nativeCreate = require_nativeCreate(); + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + _hashGet = hashGet; + return _hashGet; +} + +var _hashHas; +var hasRequired_hashHas; + +function require_hashHas () { + if (hasRequired_hashHas) return _hashHas; + hasRequired_hashHas = 1; + var nativeCreate = require_nativeCreate(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + _hashHas = hashHas; + return _hashHas; +} + +var _hashSet; +var hasRequired_hashSet; + +function require_hashSet () { + if (hasRequired_hashSet) return _hashSet; + hasRequired_hashSet = 1; + var nativeCreate = require_nativeCreate(); + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + _hashSet = hashSet; + return _hashSet; +} + +var _Hash; +var hasRequired_Hash; + +function require_Hash () { + if (hasRequired_Hash) return _Hash; + hasRequired_Hash = 1; + var hashClear = require_hashClear(), + hashDelete = require_hashDelete(), + hashGet = require_hashGet(), + hashHas = require_hashHas(), + hashSet = require_hashSet(); + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + _Hash = Hash; + return _Hash; +} + +var _mapCacheClear; +var hasRequired_mapCacheClear; + +function require_mapCacheClear () { + if (hasRequired_mapCacheClear) return _mapCacheClear; + hasRequired_mapCacheClear = 1; + var Hash = require_Hash(), + ListCache = require_ListCache(), + Map = require_Map(); + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + _mapCacheClear = mapCacheClear; + return _mapCacheClear; +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + +var _isKeyable; +var hasRequired_isKeyable; + +function require_isKeyable () { + if (hasRequired_isKeyable) return _isKeyable; + hasRequired_isKeyable = 1; + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + _isKeyable = isKeyable; + return _isKeyable; +} + +var _getMapData; +var hasRequired_getMapData; + +function require_getMapData () { + if (hasRequired_getMapData) return _getMapData; + hasRequired_getMapData = 1; + var isKeyable = require_isKeyable(); + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + _getMapData = getMapData; + return _getMapData; +} + +var _mapCacheDelete; +var hasRequired_mapCacheDelete; + +function require_mapCacheDelete () { + if (hasRequired_mapCacheDelete) return _mapCacheDelete; + hasRequired_mapCacheDelete = 1; + var getMapData = require_getMapData(); + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + _mapCacheDelete = mapCacheDelete; + return _mapCacheDelete; +} + +var _mapCacheGet; +var hasRequired_mapCacheGet; + +function require_mapCacheGet () { + if (hasRequired_mapCacheGet) return _mapCacheGet; + hasRequired_mapCacheGet = 1; + var getMapData = require_getMapData(); + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + _mapCacheGet = mapCacheGet; + return _mapCacheGet; +} + +var _mapCacheHas; +var hasRequired_mapCacheHas; + +function require_mapCacheHas () { + if (hasRequired_mapCacheHas) return _mapCacheHas; + hasRequired_mapCacheHas = 1; + var getMapData = require_getMapData(); + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + _mapCacheHas = mapCacheHas; + return _mapCacheHas; +} + +var _mapCacheSet; +var hasRequired_mapCacheSet; + +function require_mapCacheSet () { + if (hasRequired_mapCacheSet) return _mapCacheSet; + hasRequired_mapCacheSet = 1; + var getMapData = require_getMapData(); + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + _mapCacheSet = mapCacheSet; + return _mapCacheSet; +} + +var _MapCache; +var hasRequired_MapCache; + +function require_MapCache () { + if (hasRequired_MapCache) return _MapCache; + hasRequired_MapCache = 1; + var mapCacheClear = require_mapCacheClear(), + mapCacheDelete = require_mapCacheDelete(), + mapCacheGet = require_mapCacheGet(), + mapCacheHas = require_mapCacheHas(), + mapCacheSet = require_mapCacheSet(); + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + _MapCache = MapCache; + return _MapCache; +} + +var _stackSet; +var hasRequired_stackSet; + +function require_stackSet () { + if (hasRequired_stackSet) return _stackSet; + hasRequired_stackSet = 1; + var ListCache = require_ListCache(), + Map = require_Map(), + MapCache = require_MapCache(); + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + _stackSet = stackSet; + return _stackSet; +} + +var _Stack; +var hasRequired_Stack; + +function require_Stack () { + if (hasRequired_Stack) return _Stack; + hasRequired_Stack = 1; + var ListCache = require_ListCache(), + stackClear = require_stackClear(), + stackDelete = require_stackDelete(), + stackGet = require_stackGet(), + stackHas = require_stackHas(), + stackSet = require_stackSet(); + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + _Stack = Stack; + return _Stack; +} + +/** Used to stand-in for `undefined` hash values. */ + +var _setCacheAdd; +var hasRequired_setCacheAdd; + +function require_setCacheAdd () { + if (hasRequired_setCacheAdd) return _setCacheAdd; + hasRequired_setCacheAdd = 1; + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + _setCacheAdd = setCacheAdd; + return _setCacheAdd; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + */ + +var _setCacheHas; +var hasRequired_setCacheHas; + +function require_setCacheHas () { + if (hasRequired_setCacheHas) return _setCacheHas; + hasRequired_setCacheHas = 1; + function setCacheHas(value) { + return this.__data__.has(value); + } + + _setCacheHas = setCacheHas; + return _setCacheHas; +} + +var _SetCache; +var hasRequired_SetCache; + +function require_SetCache () { + if (hasRequired_SetCache) return _SetCache; + hasRequired_SetCache = 1; + var MapCache = require_MapCache(), + setCacheAdd = require_setCacheAdd(), + setCacheHas = require_setCacheHas(); + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + _SetCache = SetCache; + return _SetCache; +} + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + +var _arraySome; +var hasRequired_arraySome; + +function require_arraySome () { + if (hasRequired_arraySome) return _arraySome; + hasRequired_arraySome = 1; + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + _arraySome = arraySome; + return _arraySome; +} + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +var _cacheHas; +var hasRequired_cacheHas; + +function require_cacheHas () { + if (hasRequired_cacheHas) return _cacheHas; + hasRequired_cacheHas = 1; + function cacheHas(cache, key) { + return cache.has(key); + } + + _cacheHas = cacheHas; + return _cacheHas; +} + +var _equalArrays; +var hasRequired_equalArrays; + +function require_equalArrays () { + if (hasRequired_equalArrays) return _equalArrays; + hasRequired_equalArrays = 1; + var SetCache = require_SetCache(), + arraySome = require_arraySome(), + cacheHas = require_cacheHas(); + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + _equalArrays = equalArrays; + return _equalArrays; +} + +var _Uint8Array; +var hasRequired_Uint8Array; + +function require_Uint8Array () { + if (hasRequired_Uint8Array) return _Uint8Array; + hasRequired_Uint8Array = 1; + var root = require_root(); + + /** Built-in value references. */ + var Uint8Array = root.Uint8Array; + + _Uint8Array = Uint8Array; + return _Uint8Array; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + +var _mapToArray; +var hasRequired_mapToArray; + +function require_mapToArray () { + if (hasRequired_mapToArray) return _mapToArray; + hasRequired_mapToArray = 1; + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + _mapToArray = mapToArray; + return _mapToArray; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + +var _setToArray; +var hasRequired_setToArray; + +function require_setToArray () { + if (hasRequired_setToArray) return _setToArray; + hasRequired_setToArray = 1; + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + _setToArray = setToArray; + return _setToArray; +} + +var _equalByTag; +var hasRequired_equalByTag; + +function require_equalByTag () { + if (hasRequired_equalByTag) return _equalByTag; + hasRequired_equalByTag = 1; + var Symbol = require_Symbol(), + Uint8Array = require_Uint8Array(), + eq = requireEq(), + equalArrays = require_equalArrays(), + mapToArray = require_mapToArray(), + setToArray = require_setToArray(); + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** `Object#toString` result references. */ + var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + _equalByTag = equalByTag; + return _equalByTag; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + +var _arrayPush; +var hasRequired_arrayPush; + +function require_arrayPush () { + if (hasRequired_arrayPush) return _arrayPush; + hasRequired_arrayPush = 1; + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + _arrayPush = arrayPush; + return _arrayPush; +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + +var isArray_1; +var hasRequiredIsArray$1; + +function requireIsArray$1 () { + if (hasRequiredIsArray$1) return isArray_1; + hasRequiredIsArray$1 = 1; + var isArray = Array.isArray; + + isArray_1 = isArray; + return isArray_1; +} + +var _baseGetAllKeys; +var hasRequired_baseGetAllKeys; + +function require_baseGetAllKeys () { + if (hasRequired_baseGetAllKeys) return _baseGetAllKeys; + hasRequired_baseGetAllKeys = 1; + var arrayPush = require_arrayPush(), + isArray = requireIsArray$1(); + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + _baseGetAllKeys = baseGetAllKeys; + return _baseGetAllKeys; +} + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + +var _arrayFilter; +var hasRequired_arrayFilter; + +function require_arrayFilter () { + if (hasRequired_arrayFilter) return _arrayFilter; + hasRequired_arrayFilter = 1; + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + _arrayFilter = arrayFilter; + return _arrayFilter; +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + +var stubArray_1; +var hasRequiredStubArray; + +function requireStubArray () { + if (hasRequiredStubArray) return stubArray_1; + hasRequiredStubArray = 1; + function stubArray() { + return []; + } + + stubArray_1 = stubArray; + return stubArray_1; +} + +var _getSymbols; +var hasRequired_getSymbols; + +function require_getSymbols () { + if (hasRequired_getSymbols) return _getSymbols; + hasRequired_getSymbols = 1; + var arrayFilter = require_arrayFilter(), + stubArray = requireStubArray(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeGetSymbols = Object.getOwnPropertySymbols; + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + _getSymbols = getSymbols; + return _getSymbols; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + +var _baseTimes; +var hasRequired_baseTimes; + +function require_baseTimes () { + if (hasRequired_baseTimes) return _baseTimes; + hasRequired_baseTimes = 1; + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + _baseTimes = baseTimes; + return _baseTimes; +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + +var isObjectLike_1; +var hasRequiredIsObjectLike; + +function requireIsObjectLike () { + if (hasRequiredIsObjectLike) return isObjectLike_1; + hasRequiredIsObjectLike = 1; + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + isObjectLike_1 = isObjectLike; + return isObjectLike_1; +} + +var _baseIsArguments; +var hasRequired_baseIsArguments; + +function require_baseIsArguments () { + if (hasRequired_baseIsArguments) return _baseIsArguments; + hasRequired_baseIsArguments = 1; + var baseGetTag = require_baseGetTag(), + isObjectLike = requireIsObjectLike(); + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + _baseIsArguments = baseIsArguments; + return _baseIsArguments; +} + +var isArguments_1; +var hasRequiredIsArguments; + +function requireIsArguments () { + if (hasRequiredIsArguments) return isArguments_1; + hasRequiredIsArguments = 1; + var baseIsArguments = require_baseIsArguments(), + isObjectLike = requireIsObjectLike(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Built-in value references. */ + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + isArguments_1 = isArguments; + return isArguments_1; +} + +var isBuffer = {exports: {}}; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + +var stubFalse_1; +var hasRequiredStubFalse; + +function requireStubFalse () { + if (hasRequiredStubFalse) return stubFalse_1; + hasRequiredStubFalse = 1; + function stubFalse() { + return false; + } + + stubFalse_1 = stubFalse; + return stubFalse_1; +} + +isBuffer.exports; + +var hasRequiredIsBuffer; + +function requireIsBuffer () { + if (hasRequiredIsBuffer) return isBuffer.exports; + hasRequiredIsBuffer = 1; + (function (module, exports) { + var root = require_root(), + stubFalse = requireStubFalse(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Built-in value references. */ + var Buffer = moduleExports ? root.Buffer : undefined; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + module.exports = isBuffer; + } (isBuffer, isBuffer.exports)); + return isBuffer.exports; +} + +/** Used as references for various `Number` constants. */ + +var _isIndex; +var hasRequired_isIndex; + +function require_isIndex () { + if (hasRequired_isIndex) return _isIndex; + hasRequired_isIndex = 1; + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + _isIndex = isIndex; + return _isIndex; +} + +/** Used as references for various `Number` constants. */ + +var isLength_1; +var hasRequiredIsLength; + +function requireIsLength () { + if (hasRequiredIsLength) return isLength_1; + hasRequiredIsLength = 1; + var MAX_SAFE_INTEGER = 9007199254740991; + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + isLength_1 = isLength; + return isLength_1; +} + +var _baseIsTypedArray; +var hasRequired_baseIsTypedArray; + +function require_baseIsTypedArray () { + if (hasRequired_baseIsTypedArray) return _baseIsTypedArray; + hasRequired_baseIsTypedArray = 1; + var baseGetTag = require_baseGetTag(), + isLength = requireIsLength(), + isObjectLike = requireIsObjectLike(); + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + _baseIsTypedArray = baseIsTypedArray; + return _baseIsTypedArray; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + +var _baseUnary; +var hasRequired_baseUnary; + +function require_baseUnary () { + if (hasRequired_baseUnary) return _baseUnary; + hasRequired_baseUnary = 1; + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + _baseUnary = baseUnary; + return _baseUnary; +} + +var _nodeUtil = {exports: {}}; + +_nodeUtil.exports; + +var hasRequired_nodeUtil; + +function require_nodeUtil () { + if (hasRequired_nodeUtil) return _nodeUtil.exports; + hasRequired_nodeUtil = 1; + (function (module, exports) { + var freeGlobal = require_freeGlobal(); + + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + module.exports = nodeUtil; + } (_nodeUtil, _nodeUtil.exports)); + return _nodeUtil.exports; +} + +var isTypedArray_1; +var hasRequiredIsTypedArray; + +function requireIsTypedArray () { + if (hasRequiredIsTypedArray) return isTypedArray_1; + hasRequiredIsTypedArray = 1; + var baseIsTypedArray = require_baseIsTypedArray(), + baseUnary = require_baseUnary(), + nodeUtil = require_nodeUtil(); + + /* Node.js helper references. */ + var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + isTypedArray_1 = isTypedArray; + return isTypedArray_1; +} + +var _arrayLikeKeys; +var hasRequired_arrayLikeKeys; + +function require_arrayLikeKeys () { + if (hasRequired_arrayLikeKeys) return _arrayLikeKeys; + hasRequired_arrayLikeKeys = 1; + var baseTimes = require_baseTimes(), + isArguments = requireIsArguments(), + isArray = requireIsArray$1(), + isBuffer = requireIsBuffer(), + isIndex = require_isIndex(), + isTypedArray = requireIsTypedArray(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + _arrayLikeKeys = arrayLikeKeys; + return _arrayLikeKeys; +} + +/** Used for built-in method references. */ + +var _isPrototype; +var hasRequired_isPrototype; + +function require_isPrototype () { + if (hasRequired_isPrototype) return _isPrototype; + hasRequired_isPrototype = 1; + var objectProto = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + _isPrototype = isPrototype; + return _isPrototype; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + +var _overArg; +var hasRequired_overArg; + +function require_overArg () { + if (hasRequired_overArg) return _overArg; + hasRequired_overArg = 1; + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + _overArg = overArg; + return _overArg; +} + +var _nativeKeys; +var hasRequired_nativeKeys; + +function require_nativeKeys () { + if (hasRequired_nativeKeys) return _nativeKeys; + hasRequired_nativeKeys = 1; + var overArg = require_overArg(); + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeKeys = overArg(Object.keys, Object); + + _nativeKeys = nativeKeys; + return _nativeKeys; +} + +var _baseKeys; +var hasRequired_baseKeys; + +function require_baseKeys () { + if (hasRequired_baseKeys) return _baseKeys; + hasRequired_baseKeys = 1; + var isPrototype = require_isPrototype(), + nativeKeys = require_nativeKeys(); + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + _baseKeys = baseKeys; + return _baseKeys; +} + +var isArrayLike_1; +var hasRequiredIsArrayLike; + +function requireIsArrayLike () { + if (hasRequiredIsArrayLike) return isArrayLike_1; + hasRequiredIsArrayLike = 1; + var isFunction = requireIsFunction(), + isLength = requireIsLength(); + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + isArrayLike_1 = isArrayLike; + return isArrayLike_1; +} + +var keys_1; +var hasRequiredKeys; + +function requireKeys () { + if (hasRequiredKeys) return keys_1; + hasRequiredKeys = 1; + var arrayLikeKeys = require_arrayLikeKeys(), + baseKeys = require_baseKeys(), + isArrayLike = requireIsArrayLike(); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + keys_1 = keys; + return keys_1; +} + +var _getAllKeys; +var hasRequired_getAllKeys; + +function require_getAllKeys () { + if (hasRequired_getAllKeys) return _getAllKeys; + hasRequired_getAllKeys = 1; + var baseGetAllKeys = require_baseGetAllKeys(), + getSymbols = require_getSymbols(), + keys = requireKeys(); + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + _getAllKeys = getAllKeys; + return _getAllKeys; +} + +var _equalObjects; +var hasRequired_equalObjects; + +function require_equalObjects () { + if (hasRequired_equalObjects) return _equalObjects; + hasRequired_equalObjects = 1; + var getAllKeys = require_getAllKeys(); + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1; + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + _equalObjects = equalObjects; + return _equalObjects; +} + +var _DataView; +var hasRequired_DataView; + +function require_DataView () { + if (hasRequired_DataView) return _DataView; + hasRequired_DataView = 1; + var getNative = require_getNative(), + root = require_root(); + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(root, 'DataView'); + + _DataView = DataView; + return _DataView; +} + +var _Promise; +var hasRequired_Promise; + +function require_Promise () { + if (hasRequired_Promise) return _Promise; + hasRequired_Promise = 1; + var getNative = require_getNative(), + root = require_root(); + + /* Built-in method references that are verified to be native. */ + var Promise = getNative(root, 'Promise'); + + _Promise = Promise; + return _Promise; +} + +var _Set; +var hasRequired_Set; + +function require_Set () { + if (hasRequired_Set) return _Set; + hasRequired_Set = 1; + var getNative = require_getNative(), + root = require_root(); + + /* Built-in method references that are verified to be native. */ + var Set = getNative(root, 'Set'); + + _Set = Set; + return _Set; +} + +var _WeakMap; +var hasRequired_WeakMap; + +function require_WeakMap () { + if (hasRequired_WeakMap) return _WeakMap; + hasRequired_WeakMap = 1; + var getNative = require_getNative(), + root = require_root(); + + /* Built-in method references that are verified to be native. */ + var WeakMap = getNative(root, 'WeakMap'); + + _WeakMap = WeakMap; + return _WeakMap; +} + +var _getTag; +var hasRequired_getTag; + +function require_getTag () { + if (hasRequired_getTag) return _getTag; + hasRequired_getTag = 1; + var DataView = require_DataView(), + Map = require_Map(), + Promise = require_Promise(), + Set = require_Set(), + WeakMap = require_WeakMap(), + baseGetTag = require_baseGetTag(), + toSource = require_toSource(); + + /** `Object#toString` result references. */ + var mapTag = '[object Map]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]'; + + var dataViewTag = '[object DataView]'; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + _getTag = getTag; + return _getTag; +} + +var _baseIsEqualDeep; +var hasRequired_baseIsEqualDeep; + +function require_baseIsEqualDeep () { + if (hasRequired_baseIsEqualDeep) return _baseIsEqualDeep; + hasRequired_baseIsEqualDeep = 1; + var Stack = require_Stack(), + equalArrays = require_equalArrays(), + equalByTag = require_equalByTag(), + equalObjects = require_equalObjects(), + getTag = require_getTag(), + isArray = requireIsArray$1(), + isBuffer = requireIsBuffer(), + isTypedArray = requireIsTypedArray(); + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; + + /** Used for built-in method references. */ + var objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + _baseIsEqualDeep = baseIsEqualDeep; + return _baseIsEqualDeep; +} + +var _baseIsEqual; +var hasRequired_baseIsEqual; + +function require_baseIsEqual () { + if (hasRequired_baseIsEqual) return _baseIsEqual; + hasRequired_baseIsEqual = 1; + var baseIsEqualDeep = require_baseIsEqualDeep(), + isObjectLike = requireIsObjectLike(); + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + _baseIsEqual = baseIsEqual; + return _baseIsEqual; +} + +var isEqual_1; +var hasRequiredIsEqual; + +function requireIsEqual () { + if (hasRequiredIsEqual) return isEqual_1; + hasRequiredIsEqual = 1; + var baseIsEqual = require_baseIsEqual(); + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + isEqual_1 = isEqual; + return isEqual_1; +} + +var hasRequiredFunctionUtils; + +function requireFunctionUtils () { + if (hasRequiredFunctionUtils) return functionUtils; + hasRequiredFunctionUtils = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (functionUtils && functionUtils.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(functionUtils, "__esModule", { value: true }); + functionUtils.FunctionUtils = void 0; + const datetimeFormatConverter_1 = requireDatetimeFormatConverter(); + const expressionType_1 = requireExpressionType(); + const returnType_1 = requireReturnType(); + const isEqual_1 = __importDefault(requireIsEqual()); + /** + * Utility functions in AdaptiveExpression. + */ + class FunctionUtils { + /** + * Validate that expression has a certain number of children that are of any of the supported types. + * + * @param expression Expression to validate. + * @param minArity Minimum number of children. + * @param maxArity Maximum number of children. + * @param returnType Allowed return types for children. + * If a child has a return type of Object then validation will happen at runtime. + */ + static validateArityAndAnyType(expression, minArity, maxArity, returnType = returnType_1.ReturnType.Object) { + if (expression.children.length < minArity) { + throw new Error(`${expression} should have at least ${minArity} children.`); + } + if (expression.children.length > maxArity) { + throw new Error(`${expression} can't have more than ${maxArity} children.`); + } + if ((returnType & returnType_1.ReturnType.Object) === 0) { + for (const child of expression.children) { + if ((child.returnType & returnType_1.ReturnType.Object) === 0 && (returnType & child.returnType) === 0) { + throw new Error(FunctionUtils.buildTypeValidatorError(returnType, child, expression)); + } + } + } + } + /** + * Validate the number and type of arguments to a function. + * + * @param expression Expression to validate. + * @param optional Optional types in order. + * @param types Expected types in order. + */ + static validateOrder(expression, optional, ...types) { + if (optional === undefined) { + optional = []; + } + if (expression.children.length < types.length || expression.children.length > types.length + optional.length) { + throw new Error(optional.length === 0 + ? `${expression} should have ${types.length} children.` + : `${expression} should have between ${types.length} and ${types.length + optional.length} children.`); + } + for (let i = 0; i < types.length; i++) { + const child = expression.children[i]; + const type = types[i]; + if ((type & returnType_1.ReturnType.Object) === 0 && + (child.returnType & returnType_1.ReturnType.Object) === 0 && + (type & child.returnType) === 0) { + throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression)); + } + } + for (let i = 0; i < optional.length; i++) { + const ic = i + types.length; + if (ic >= expression.children.length) { + break; + } + const child = expression.children[ic]; + const type = optional[i]; + if ((type & returnType_1.ReturnType.Object) === 0 && + (child.returnType & returnType_1.ReturnType.Object) === 0 && + (type & child.returnType) === 0) { + throw new Error(FunctionUtils.buildTypeValidatorError(type, child, expression)); + } + } + } + /** + * Validate at least 1 argument of any type. + * + * @param expression Expression to validate. + */ + static validateAtLeastOne(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER); + } + /** + * Validate 1 or more numeric arguments. + * + * @param expression Expression to validate. + */ + static validateNumber(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.Number); + } + /** + * Validate 1 or more string arguments. + * + * @param expression Expression to validate. + */ + static validateString(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.String); + } + /** + * Validate there are two children. + * + * @param expression Expression to validate. + */ + static validateBinary(expression) { + FunctionUtils.validateArityAndAnyType(expression, 2, 2); + } + /** + * Validate 2 numeric arguments. + * + * @param expression Expression to validate. + */ + static validateBinaryNumber(expression) { + FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.Number); + } + /** + * Validate 1 or 2 numeric arguments. + * + * @param expression Expression to validate. + */ + static validateUnaryOrBinaryNumber(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, 2, returnType_1.ReturnType.Number); + } + /** + * Validate 2 or more than 2 numeric arguments. + * + * @param expression Expression to validate. + */ + static validateTwoOrMoreThanTwoNumbers(expression) { + FunctionUtils.validateArityAndAnyType(expression, 2, Number.MAX_VALUE, returnType_1.ReturnType.Number); + } + /** + * Validate there are 2 numeric or string arguments. + * + * @param expression Expression to validate. + */ + static validateBinaryNumberOrString(expression) { + FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.Number | returnType_1.ReturnType.String); + } + /** + * Validate there is a single argument. + * + * @param expression Expression to validate. + */ + static validateUnary(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, 1); + } + /** + * Validate there is a single argument. + * + * @param expression Expression to validate. + */ + static validateUnaryNumber(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.Number); + } + /** + * Validate there is a single string argument. + * + * @param expression Expression to validate. + */ + static validateUnaryString(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.String); + } + /** + * Validate there is one or two string arguments. + * + * @param expression Expression to validate. + */ + static validateUnaryOrBinaryString(expression) { + FunctionUtils.validateArityAndAnyType(expression, 1, 2, returnType_1.ReturnType.String); + } + /** + * Validate there is a single boolean argument. + * + * @param expression Expression to validate. + */ + static validateUnaryBoolean(expression) { + FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Boolean); + } + /** + * Verify value is numeric. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyNumber(value, expression, _) { + let error; + if (!FunctionUtils.isNumber(value)) { + error = `${expression} is not a number.`; + } + return error; + } + /** + * Verify value is numeric. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyNumberOrNumericList(value, expression, _) { + let error; + if (FunctionUtils.isNumber(value)) { + return error; + } + if (!Array.isArray(value)) { + error = `${expression} is neither a list nor a number.`; + } + else { + for (const elt of value) { + if (!FunctionUtils.isNumber(elt)) { + error = `${elt} is not a number in ${expression}.`; + break; + } + } + } + return error; + } + /** + * Verify value is numeric list. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyNumericList(value, expression, _) { + let error; + if (!Array.isArray(value)) { + error = `${expression} is not a list.`; + } + else { + for (const elt of value) { + if (!FunctionUtils.isNumber(elt)) { + error = `${elt} is not a number in ${expression}.`; + break; + } + } + } + return error; + } + /** + * Verify value contains elements. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyContainer(value, expression, _) { + let error; + if (!(typeof value === 'string') && + !Array.isArray(value) && + !(value instanceof Map) && + !(typeof value === 'object')) { + error = `${expression} must be a string, list, map or object.`; + } + return error; + } + /** + * Verify value contains elements or null. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyContainerOrNull(value, expression, _) { + let error; + if (value != null && + !(typeof value === 'string') && + !Array.isArray(value) && + !(value instanceof Map) && + !(typeof value === 'object')) { + error = `${expression} must be a string, list, map or object.`; + } + return error; + } + /** + * Verify value is not null or undefined. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if valid. + */ + static verifyNotNull(value, expression, _) { + let error; + if (value == null) { + error = `${expression} is null.`; + } + return error; + } + /** + * Verify value is an integer. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyInteger(value, expression, _) { + let error; + if (!Number.isInteger(value)) { + error = `${expression} is not a integer.`; + } + return error; + } + /** + * Verify value is an list. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @returns Error or undefined if invalid. + */ + static verifyList(value, expression) { + let error; + if (!Array.isArray(value)) { + error = `${expression} is not a list or array.`; + } + return error; + } + /** + * Verify value is a string. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyString(value, expression, _) { + let error; + if (typeof value !== 'string') { + error = `${expression} is not a string.`; + } + return error; + } + /** + * Verify an object is neither a string nor null. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyStringOrNull(value, expression, _) { + let error; + if (typeof value !== 'string' && value !== undefined) { + error = `${expression} is neither a string nor a null object.`; + } + return error; + } + /** + * Verify value is a number or string or null. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyNumberOrStringOrNull(value, expression, _) { + let error; + if (typeof value !== 'string' && value !== undefined && !FunctionUtils.isNumber(value)) { + error = `${expression} is neither a number nor string`; + } + return error; + } + /** + * Verify value is a number or string. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyNumberOrString(value, expression, _) { + let error; + if (value === undefined || (!FunctionUtils.isNumber(value) && typeof value !== 'string')) { + error = `${expression} is not string or number.`; + } + return error; + } + /** + * Verify value is boolean. + * + * @param value Value to check. + * @param expression Expression that led to value. + * @param _ No function. + * @returns Error or undefined if invalid. + */ + static verifyBoolean(value, expression, _) { + let error; + if (typeof value !== 'boolean') { + error = `${expression} is not a boolean.`; + } + return error; + } + /** + * Evaluate expression children and return them. + * + * @param expression Expression with children. + * @param state Global state. + * @param options Options used in evaluation. + * @param verify Optional function to verify each child's result. + * @returns List of child values or error message. + */ + static evaluateChildren(expression, state, options, verify) { + const args = []; + let value; + let error; + let pos = 0; + for (const child of expression.children) { + ({ value, error } = child.tryEvaluate(state, options)); + if (error) { + break; + } + if (verify !== undefined) { + error = verify(value, child, pos); + } + if (error) { + break; + } + args.push(value); + ++pos; + } + return { args, error }; + } + /** + * Generate an expression delegate that applies function after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static apply(func, verify) { + return (expression, state, options) => { + let value; + const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); + let error = childrenError; + if (!error) { + try { + value = func(args); + } + catch (e) { + error = e.message; + } + } + return { value, error }; + }; + } + /** + * Generate an expression delegate that applies function after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static applyWithError(func, verify) { + return (expression, state, options) => { + let value; + const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); + let error = childrenError; + if (!error) { + try { + ({ value, error } = func(args)); + } + catch (e) { + error = e.message; + } + } + return { value, error }; + }; + } + /** + * Generate an expression delegate that applies function after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static applyWithOptionsAndError(func, verify) { + return (expression, state, options) => { + let value; + const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); + let error = childrenError; + if (!error) { + try { + ({ value, error } = func(args, options)); + } + catch (e) { + error = e.message; + } + } + return { value, error }; + }; + } + /** + * Generate an expression delegate that applies function after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static applyWithOptions(func, verify) { + return (expression, state, options) => { + let value; + const { args, error: childrenError } = FunctionUtils.evaluateChildren(expression, state, options, verify); + let error = childrenError; + if (!error) { + try { + value = func(args, options); + } + catch (e) { + error = e.message; + } + } + return { value, error }; + }; + } + /** + * Generate an expression delegate that applies function on the accumulated value after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static applySequence(func, verify) { + return FunctionUtils.apply((args) => { + const binaryArgs = [undefined, undefined]; + let soFar = args[0]; + for (let i = 1; i < args.length; i++) { + binaryArgs[0] = soFar; + binaryArgs[1] = args[i]; + soFar = func(binaryArgs); + } + return soFar; + }, verify); + } + /** + * Generate an expression delegate that applies function on the accumulated value after verifying all children. + * + * @param func Function to apply. + * @param verify Function to check each arg for validity. + * @returns Delegate for evaluating an expression. + */ + static applySequenceWithError(func, verify) { + return FunctionUtils.applyWithError((args) => { + const binaryArgs = [undefined, undefined]; + let soFar = args[0]; + let value; + let error; + for (let i = 1; i < args.length; i++) { + binaryArgs[0] = soFar; + binaryArgs[1] = args[i]; + ({ value, error } = func(binaryArgs)); + if (error) { + return { value, error }; + } + else { + soFar = value; + } + } + return { value: soFar, error: undefined }; + }, verify); + } + /** + * + * @param args An array of arguments. + * @param maxArgsLength The max length of a given function. + * @param locale A locale string + * @returns The last item from the args param, otherwise the locale string. + */ + static determineLocale(args, maxArgsLength, locale = 'en-us') { + if (args.length === maxArgsLength) { + const lastArg = args[maxArgsLength - 1]; + if (typeof lastArg === 'string') { + locale = lastArg; + } + } + return locale; + } + /** + * + * @param args An array of arguments. + * @param maxArgsLength The max length of a given function. + * @param format A format string. + * @param locale A locale string. + * @returns The format and the locale from the args param, otherwise the locale and format strings. + */ + static determineFormatAndLocale(args, maxArgsLength, format, locale = 'en-us') { + if (maxArgsLength >= 2) { + if (args.length === maxArgsLength) { + const lastArg = args[maxArgsLength - 1]; + const secondLastArg = args[maxArgsLength - 2]; + if (typeof lastArg === 'string' && typeof secondLastArg === 'string') { + format = + secondLastArg !== '' + ? FunctionUtils.timestampFormatter(secondLastArg) + : FunctionUtils.DefaultDateTimeFormat; + locale = lastArg.substr(0, 2); //dayjs only support two-letter locale representattion + } + } + else if (args.length === maxArgsLength - 1) { + const lastArg = args[maxArgsLength - 2]; + if (typeof lastArg === 'string') { + format = FunctionUtils.timestampFormatter(lastArg); + } + } + } + return { format: format, locale: locale }; + } + /** + * Timestamp formatter, convert C# datetime to day.js format. + * + * @param formatter C# datetime format + * @returns The formated datetime. + */ + static timestampFormatter(formatter) { + if (!formatter) { + return FunctionUtils.DefaultDateTimeFormat; + } + let result = formatter; + try { + result = (0, datetimeFormatConverter_1.convertCSharpDateTimeToDayjs)(formatter); + } + catch (_a) { + // do nothing + } + return result; + } + /** + * State object for resolving memory paths. + * + * @param expression Expression. + * @param state Scope. + * @param options Options used in evaluation. + * @returns Return the accumulated path and the expression left unable to accumulate. + */ + static tryAccumulatePath(expression, state, options) { + let path = ''; + let left = expression; + while (left !== undefined) { + if (left.type === expressionType_1.ExpressionType.Accessor) { + path = left.children[0].value + '.' + path; + left = left.children.length === 2 ? left.children[1] : undefined; + } + else if (left.type === expressionType_1.ExpressionType.Element) { + const { value, error } = left.children[1].tryEvaluate(state, options); + if (error !== undefined) { + return { path: undefined, left: undefined, error }; + } + if (FunctionUtils.isNumber(parseInt(value))) { + path = `[${value}].${path}`; + } + else if (typeof value === 'string') { + path = `['${value}'].${path}`; + } + else { + return { + path: undefined, + left: undefined, + error: `${left.children[1].toString()} doesn't return an int or string`, + }; + } + left = left.children[0]; + } + else { + break; + } + } + // make sure we generated a valid path + path = path.replace(/(\.*$)/g, '').replace(/(\.\[)/g, '['); + if (path === '') { + path = undefined; + } + return { path, left, error: undefined }; + } + /** + * Is number helper function. + * + * @param instance Input. + * @returns True if the input is a number. + */ + static isNumber(instance) { + return instance != null && typeof instance === 'number' && !Number.isNaN(instance); + } + /** + * Equal helper function. + * Compare the first param and second param. + * + * @param obj1 The first value to compare. + * @param obj2 The second value to compare. + * @returns A boolean based on the comparison. + */ + static commonEquals(obj1, obj2) { + if (obj1 == null || obj2 == null) { + return obj1 == null && obj2 == null; + } + // Array Comparison + if (Array.isArray(obj1) && Array.isArray(obj2)) { + if (obj1.length !== obj2.length) { + return false; + } + return obj1.every((item, i) => FunctionUtils.commonEquals(item, obj2[i])); + } + // Object Comparison + const propertyCountOfObj1 = FunctionUtils.getPropertyCount(obj1); + const propertyCountOfObj2 = FunctionUtils.getPropertyCount(obj2); + if (propertyCountOfObj1 >= 0 && propertyCountOfObj2 >= 0) { + if (propertyCountOfObj1 !== propertyCountOfObj2) { + return false; + } + const jsonObj1 = FunctionUtils.convertToObj(obj1); + const jsonObj2 = FunctionUtils.convertToObj(obj2); + return (0, isEqual_1.default)(jsonObj1, jsonObj2); + } + // Number Comparison + if (FunctionUtils.isNumber(obj1) && FunctionUtils.isNumber(obj2)) { + if (Math.abs(obj1 - obj2) < Number.EPSILON) { + return true; + } + } + try { + return obj1 === obj2; + } + catch (_a) { + return false; + } + } + /** + * @private + */ + static buildTypeValidatorError(returnType, childExpr, expr) { + const names = Object.keys(returnType_1.ReturnType).filter((x) => !(parseInt(x) >= 0)); + const types = []; + for (const name of names) { + const value = returnType_1.ReturnType[name]; + if ((returnType & value) !== 0) { + types.push(name); + } + } + if (types.length === 1) { + return `${childExpr} is not a ${types[0]} expression in ${expr}.`; + } + else { + const typesStr = types.join(', '); + return `${childExpr} in ${expr} is not any of [${typesStr}].`; + } + } + /** + * Helper function of get the number of properties of an object. + * + * @param obj An object. + * @returns The number of properties. + */ + static getPropertyCount(obj) { + let count = -1; + if (obj != null && !Array.isArray(obj)) { + if (obj instanceof Map) { + count = obj.size; + } + else if (typeof obj === 'object' && !(obj instanceof Date)) { + count = Object.keys(obj).length; + } + } + return count; + } + /** + * @private + */ + static convertToObj(instance) { + if (FunctionUtils.getPropertyCount(instance) >= 0) { + const entries = instance instanceof Map ? Array.from(instance.entries()) : Object.entries(instance); + return entries.reduce((acc, [key, value]) => (Object.assign(Object.assign({}, acc), { [key]: FunctionUtils.convertToObj(value) })), {}); + } + else if (Array.isArray(instance)) { + // Convert Array + return instance.map((item) => FunctionUtils.convertToObj(item)); + } + return instance; + } + } + functionUtils.FunctionUtils = FunctionUtils; + /** + * The default date time format string. + */ + FunctionUtils.DefaultDateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS[Z]'; + + return functionUtils; +} + +var hasRequiredNumberTransformEvaluator; + +function requireNumberTransformEvaluator () { + if (hasRequiredNumberTransformEvaluator) return numberTransformEvaluator; + hasRequiredNumberTransformEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(numberTransformEvaluator, "__esModule", { value: true }); + numberTransformEvaluator.NumberTransformEvaluator = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Evaluator that transforms a number to another number. + */ + class NumberTransformEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [NumberTransformEvaluator](xref:adaptive-expressions.NumberTransformEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The evaluation function, it takes a list of objects and returns a number. + */ + constructor(type, func) { + super(type, NumberTransformEvaluator.evaluator(func), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryNumber); + } + /** + * @private + */ + static evaluator(func) { + return functionUtils_1.FunctionUtils.apply(func, functionUtils_1.FunctionUtils.verifyNumber); + } + } + numberTransformEvaluator.NumberTransformEvaluator = NumberTransformEvaluator; + + return numberTransformEvaluator; +} + +var hasRequiredAbs; + +function requireAbs () { + if (hasRequiredAbs) return abs; + hasRequiredAbs = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(abs, "__esModule", { value: true }); + abs.Abs = void 0; + const expressionType_1 = requireExpressionType(); + const numberTransformEvaluator_1 = requireNumberTransformEvaluator(); + /** + * Returns the absolute value of the specified number. + */ + class Abs extends numberTransformEvaluator_1.NumberTransformEvaluator { + /** + * Initializes a new instance of the [Floor](xref:adaptive-expressions.Abs) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Abs, Abs.func); + } + /** + * @private + */ + static func(args) { + return Math.abs(args[0]); + } + } + abs.Abs = Abs; + + return abs; +} + +var accessor = {}; + +var functionUtils_internal = {}; + +var constant = {}; + +var expression = {}; + +var extensions = {}; + +var hasRequiredExtensions; + +function requireExtensions () { + if (hasRequiredExtensions) return extensions; + hasRequiredExtensions = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(extensions, "__esModule", { value: true }); + extensions.Extensions = void 0; + /** + * Some util and extension functions + */ + class Extensions { + /** + * Patch method + * TODO: is there any better solution? + * To judge if an object is implements MemoryInterface. Same with 'is MemoryInterface' in C# + * + * @param obj The object to evaluate. + * @returns True if the object implements MemoryInterface; False if it isn't. + */ + static isMemoryInterface(obj) { + if (obj === undefined) { + return false; + } + if (typeof obj !== 'object') { + return false; + } + return ('getValue' in obj && + 'setValue' in obj && + 'version' in obj && + typeof obj.getValue === 'function' && + typeof obj.setValue === 'function' && + typeof obj.version === 'function'); + } + /** + * Generator random seed and value from properties. + * If value is not null, the mock random value result would be: min + (value % (max - min)). + * + * @param memory memory state. + * @param min The inclusive lower bound of the random number returned. + * @param max The exclusive upper bound of the random number returned. max must be greater than or equal to min. + * @returns Random value. + */ + static randomNext(memory, min, max) { + const randomValue = memory.getValue('Conversation.TestOptions.randomValue'); + if (randomValue !== undefined) { + return min + (randomValue % (max - min)); + } + return Math.floor(min + Math.random() * (max - min)); + } + } + extensions.Extensions = Extensions; + + return extensions; +} + +var functionTable = {}; + +var hasRequiredFunctionTable; + +function requireFunctionTable () { + if (hasRequiredFunctionTable) return functionTable; + hasRequiredFunctionTable = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(functionTable, "__esModule", { value: true }); + functionTable.FunctionTable = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionFunctions_1 = requireExpressionFunctions(); + const functionUtils_1 = requireFunctionUtils(); + /** + * FunctionTable is a dictionary which merges BuiltinFunctions.Functions with a CustomDictionary. + */ + class FunctionTable { + constructor() { + this.customFunctions = new Map(); + } + /** + * Gets a collection of string values that represent the keys of the [ExpressionFunctions.standardFunctions](xref:adaptive-expressions.ExpressionFunctions.standardFunctions). + * + * @returns A list of string values. + */ + keys() { + const keysOfAllFunctions = Array.from(expressionFunctions_1.ExpressionFunctions.standardFunctions.keys()).concat(Array.from(this.customFunctions.keys())); + return keysOfAllFunctions[Symbol.iterator](); + } + /** + * Gets a collection of [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) which is the value of the StandardFunctions. + * + * @returns A list of [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator). + */ + values() { + const valuesOfAllFunctions = Array.from(expressionFunctions_1.ExpressionFunctions.standardFunctions.values()).concat(Array.from(this.customFunctions.values())); + return valuesOfAllFunctions[Symbol.iterator](); + } + /** + * Gets the total number of [ExpressionFunctions.standardFunctions](xref:adaptive-expressions.ExpressionFunctions.standardFunctions) and user [customFunctions](xref:adaptive-expressions.FunctionTable.customFunctions). + * + * @returns An integer value. + */ + get size() { + return expressionFunctions_1.ExpressionFunctions.standardFunctions.size + this.customFunctions.size; + } + /** + * Gets a value indicating whether the [FunctionTable](xref:adaptive-expressions.FunctionTable) is readonly. + * + * @returns A boolean value indicating whether the [FunctionTable](xref:adaptive-expressions.FunctionTable) is readonly. + */ + get isReadOnly() { + return false; + } + /** + * Gets a value of [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) corresponding to the given key. + * + * @param key A string value of function name. + * @returns An [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator). + */ + get(key) { + if (expressionFunctions_1.ExpressionFunctions.standardFunctions.get(key)) { + return expressionFunctions_1.ExpressionFunctions.standardFunctions.get(key); + } + if (this.customFunctions.get(key)) { + return this.customFunctions.get(key); + } + return undefined; + } + /** + * Sets a value of [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) corresponding to the given key. + * + * @param key A string value of function name. + * @param value The value to set for the [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator). + * @returns The value of the [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator). + */ + set(key, value) { + if (expressionFunctions_1.ExpressionFunctions.standardFunctions.get(key)) { + throw Error("You can't overwrite a built in function."); + } + this.customFunctions.set(key, value); + return this; + } + /** + * Inserts a mapping of a string key to [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) into [FunctionTable](xref:adaptive-expressions.FunctionTable). + * + * @param param1 Key-Value pair for the [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) or the function name to be added. + * @param param2 Value of the [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) to be added or value of the user customized function to be added. + */ + add(param1, param2) { + if (arguments.length === 1) { + if (param1 instanceof Object) { + this.set(param1.key, param1.value); + } + } + else { + if (typeof param1 === 'string') { + if (param2 instanceof expressionEvaluator_1.ExpressionEvaluator) { + this.set(param1, param2); + } + else { + this.set(param1, new expressionEvaluator_1.ExpressionEvaluator(param1, functionUtils_1.FunctionUtils.apply(param2))); + } + } + } + } + /** + * Clears the user [customFunctions](xref:adaptive-expressions.FunctionTable.customFunctions). + */ + clear() { + this.customFunctions.clear(); + } + /** + * Determines if the [FunctionTable](xref:adaptive-expressions.FunctionTable) has a given string key. + * + * @param key A string key. + * @returns `True` if the key is contained, otherwise returns `False`. + */ + has(key) { + return expressionFunctions_1.ExpressionFunctions.standardFunctions.has(key) || this.customFunctions.has(key); + } + /** + * Deletes a specified key from user [customFunctions](xref:adaptive-expressions.FunctionTable.customFunctions). + * + * @param key A string key of function name. + * @returns A boolean value indicating whether the key is successfully deleted. + */ + delete(key) { + return this.customFunctions.delete(key); + } + /** + * Operates on each element of the [ExpressionFunctions.standardFunctions](xref:adaptive-expressions.ExpressionFunctions.standardFunctions). + * Not implemented. + * + * @param _callbackfn Callback function. + * @param _thisArg Optional. This args. + */ + forEach(_callbackfn, _thisArg) { + throw Error('forEach function not implemented'); + } + /** + * Returns an iterable of key, value pairs for every entry in the map. + * Not implemented. + */ + entries() { + throw Error('entries function not implemented'); + } + /** + * Returns an iterable of key, value pairs. + * Not implemented. + */ + get [Symbol.iterator]() { + throw Error('Symbol.iterator function not implemented'); + } + /** + * Returns a string value. + * Not implemented. + */ + get [Symbol.toStringTag]() { + throw Error('Symbol.toStringTag function not implemented'); + } + } + functionTable.FunctionTable = FunctionTable; + + return functionTable; +} + +var memory = {}; + +var memoryInterface = {}; + +var hasRequiredMemoryInterface; + +function requireMemoryInterface () { + if (hasRequiredMemoryInterface) return memoryInterface; + hasRequiredMemoryInterface = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(memoryInterface, "__esModule", { value: true }); + + return memoryInterface; +} + +var simpleObjectMemory = {}; + +var hasRequiredSimpleObjectMemory; + +function requireSimpleObjectMemory () { + if (hasRequiredSimpleObjectMemory) return simpleObjectMemory; + hasRequiredSimpleObjectMemory = 1; + Object.defineProperty(simpleObjectMemory, "__esModule", { value: true }); + simpleObjectMemory.SimpleObjectMemory = void 0; + const extensions_1 = requireExtensions(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + /** + * Simple implement of MemoryInterface + */ + class SimpleObjectMemory { + /** + * Initializes a new instance of the [SimpleObjectMemory](xref:adaptive-expressions.SimpleObjectMemory) class. + * This wraps a simple object as [MemoryInterface](xref:adaptive-expressions.MemoryInterface). + * + * @param memory The object to wrap. + */ + constructor(memory) { + this.memory = undefined; + this.memory = memory; + } + /** + * Transfer a common object to simple memory. + * + * @param obj Common object. + * @returns Simple memory instance. + */ + static wrap(obj) { + if (extensions_1.Extensions.isMemoryInterface(obj)) { + return obj; + } + return new SimpleObjectMemory(obj); + } + /** + * Gets the value from a given path. + * + * @param path Given path. + * @returns The value in the given path or undefined. + */ + getValue(path) { + if (this.memory === undefined || path.length === 0) { + return undefined; + } + const parts = path + .split(/[.[\]]+/) + .filter((u) => u !== undefined && u !== '') + .map((u) => { + if ((u.startsWith('"') && u.endsWith('"')) || (u.startsWith("'") && u.endsWith("'"))) { + return u.substr(1, u.length - 2); + } + else { + return u; + } + }); + let value; + let curScope = this.memory; + for (const part of parts) { + let error; + const idx = parseInt(part); + if (!isNaN(idx) && Array.isArray(curScope)) { + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.accessIndex(curScope, idx)); + } + else { + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.accessProperty(curScope, part)); + } + if (error) { + return undefined; + } + curScope = value; + } + return value; + } + /** + * In this simple object scope, we don't allow you to set a path in which some parts in middle don't exist + * for example + * if you set dialog.a.b = x, but dialog.a don't exist, this will result in an error + * because we can't and shouldn't smart create structure in the middle + * you can implement a customzied Scope that support such behavior + * + * @param path Memory path. + * @param input Value to set. + */ + setValue(path, input) { + if (this.memory === undefined) { + return; + } + const parts = path + .split(/[.[\]]+/) + .filter((u) => u !== undefined && u !== '') + .map((u) => { + if ((u.startsWith('"') && u.endsWith('"')) || (u.startsWith("'") && u.endsWith("'"))) { + return u.substr(1, u.length - 2); + } + else { + return u; + } + }); + let curScope = this.memory; + let curPath = ''; + let error = undefined; + // find the 2nd last value, ie, the container + for (let i = 0; i < parts.length - 1; i++) { + const idx = parseInt(parts[i]); + if (!isNaN(idx) && Array.isArray(curScope)) { + curPath = `[${parts[i]}]`; + ({ value: curScope, error } = functionUtils_internal_1.InternalFunctionUtils.accessIndex(curScope, idx)); + } + else { + curPath = `.${parts[i]}`; + ({ value: curScope, error } = functionUtils_internal_1.InternalFunctionUtils.accessProperty(curScope, parts[i])); + } + if (error) { + return; + } + if (curScope === undefined) { + curPath = curPath.replace(/(^\.*)/g, ''); + return; + } + } + // set the last value + const idx = parseInt(parts[parts.length - 1]); + if (!isNaN(idx)) { + if (Array.isArray(curScope)) { + if (idx > curScope.length) { + error = `${idx} index out of range`; + } + else if (idx === curScope.length) { + curScope.push(input); + } + else { + curScope[idx] = input; + } + } + else { + error = 'set value for an index to a non-list object'; + } + if (error) { + return; + } + } + else { + error = this.setProperty(curScope, parts[parts.length - 1], input).error; + if (error) { + return; + } + } + return; + } + /** + * Returns the version info of [SimpleObjectMemory](xref:adaptive-expressions.SimpleObjectMemory). + * + * @returns A string value representing the version info. + */ + version() { + return this.toString(); + } + /** + * Returns a string that represents the current [SimpleObjectMemory](xref:adaptive-expressions.SimpleObjectMemory) object. + * + * @returns A string value representing the current [SimpleObjectMemory](xref:adaptive-expressions.SimpleObjectMemory) object. + */ + toString() { + return JSON.stringify(this.memory, this.getCircularReplacer()); + } + /** + * @private + */ + getCircularReplacer() { + const seen = new WeakSet(); + return (_key, value) => { + if (typeof value === 'object' && value) { + if (seen.has(value)) { + return; + } + seen.add(value); + } + return value; + }; + } + /** + * @private + */ + setProperty(instance, property, value) { + const result = value; + if (instance instanceof Map) { + instance.set(property, value); + } + else { + instance[property] = value; + } + return { value: result, error: undefined }; + } + } + simpleObjectMemory.SimpleObjectMemory = SimpleObjectMemory; + + return simpleObjectMemory; +} + +var stackedMemory = {}; + +var hasRequiredStackedMemory; + +function requireStackedMemory () { + if (hasRequiredStackedMemory) return stackedMemory; + hasRequiredStackedMemory = 1; + Object.defineProperty(stackedMemory, "__esModule", { value: true }); + stackedMemory.StackedMemory = void 0; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + /** + * Stack implements of MemoryInterface. + * Memory variables have a hierarchical relationship. + */ + class StackedMemory extends Array { + /** + * Wraps an object that implements [MemoryInterface](xref:adaptive-expressions.MemoryInterface) into a [StackedMemory](xref:adaptive-expressions.StackedMemory) object. + * + * @param memory An object that implements [MemoryInterface](xref:adaptive-expressions.MemoryInterface). + * @returns A [StackedMemory](xref:adaptive-expressions.StackedMemory) object. + */ + static wrap(memory) { + if (memory instanceof StackedMemory) { + return memory; + } + else { + const stackedMemory = new StackedMemory(); + stackedMemory.push(memory); + return stackedMemory; + } + } + /** + * Gets the value from a given path. + * + * @param path Given path. + * @returns The value from the given path if found, otherwise, undefined. + */ + getValue(path) { + if (this.length === 0) { + return undefined; + } + else { + for (const memory of Array.from(this).reverse()) { + if (memory.getValue(path) !== undefined) { + return memory.getValue(path); + } + } + return undefined; + } + } + /** + * Sets value to a given path. + * + * @param _path Memory path. + * @param _value Value to set. + */ + setValue(_path, _value) { + throw new Error(`Can't set value to ${_path}, stacked memory is read-only`); + } + /** + * Gets the version of the current [StackedMemory](xref:adaptive-expressions.StackedMemory). + * + * @returns A string value representing the version. + */ + version() { + return '0'; + } + } + stackedMemory.StackedMemory = StackedMemory; + + return stackedMemory; +} + +var hasRequiredMemory; + +function requireMemory () { + if (hasRequiredMemory) return memory; + hasRequiredMemory = 1; + (function (exports) { + var __createBinding = (memory && memory.__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 = (memory && memory.__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 }); + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + __exportStar(requireMemoryInterface(), exports); + __exportStar(requireSimpleObjectMemory(), exports); + __exportStar(requireStackedMemory(), exports); + + } (memory)); + return memory; +} + +var options = {}; + +var hasRequiredOptions; + +function requireOptions () { + if (hasRequiredOptions) return options; + hasRequiredOptions = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(options, "__esModule", { value: true }); + options.Options = void 0; + /** + * Options used to define evaluation behaviors. + */ + class Options { + /** + * Initializes a new instance of the [Options](xref:adaptive-expressions.Options) class. + * + * @param opt Optional. An [Options](xref:adaptive-expressions.Options) instance. + */ + constructor(opt) { + this.nullSubstitution = opt ? opt.nullSubstitution : undefined; + this.locale = opt ? opt.locale : undefined; + } + } + options.Options = Options; + + return options; +} + +var parser = {}; + +var parseErrorListener = {}; + +var hasRequiredParseErrorListener; + +function requireParseErrorListener () { + if (hasRequiredParseErrorListener) return parseErrorListener; + hasRequiredParseErrorListener = 1; + Object.defineProperty(parseErrorListener, "__esModule", { value: true }); + parseErrorListener.ParseErrorListener = void 0; + // tslint:disable-next-line: completed-docs + /** + * Expression parser error listener. + */ + class ParseErrorListener { + /** + * Throws a syntax error based on the current context. + * + * @param _recognizer An Antlr4 runtime recognizer. + * @param _offendingSymbol The token violating the lexer rules. + * @param line The line number where the error occurred. + * @param charPositionInLine The position of character in the line where the error occurred. + * @param _msg The error message. + * @param _e The `RecognitionException`. + */ + syntaxError(_recognizer, _offendingSymbol, line, charPositionInLine, _msg, _e) { + const syntaxErrorMessage = 'Invalid expression format.'; + throw Error(`syntax error at line ${line}:${charPositionInLine} ${syntaxErrorMessage}`); + } + } + parseErrorListener.ParseErrorListener = ParseErrorListener; + ParseErrorListener.Instance = new ParseErrorListener(); + + return parseErrorListener; +} + +var expressionParser = {}; + +var antlr4ts = {}; + +var ANTLRErrorListener = {}; + +var hasRequiredANTLRErrorListener; + +function requireANTLRErrorListener () { + if (hasRequiredANTLRErrorListener) return ANTLRErrorListener; + hasRequiredANTLRErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ANTLRErrorListener, "__esModule", { value: true }); + + return ANTLRErrorListener; +} + +var ANTLRErrorStrategy = {}; + +var hasRequiredANTLRErrorStrategy; + +function requireANTLRErrorStrategy () { + if (hasRequiredANTLRErrorStrategy) return ANTLRErrorStrategy; + hasRequiredANTLRErrorStrategy = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ANTLRErrorStrategy, "__esModule", { value: true }); + + return ANTLRErrorStrategy; +} + +var ANTLRInputStream = {}; + +var Decorators = {}; + +var hasRequiredDecorators; + +function requireDecorators () { + if (hasRequiredDecorators) return Decorators; + hasRequiredDecorators = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Decorators, "__esModule", { value: true }); + Decorators.SuppressWarnings = Decorators.Override = Decorators.Nullable = Decorators.NotNull = void 0; + function NotNull(target, propertyKey, propertyDescriptor) { + // intentionally empty + } + Decorators.NotNull = NotNull; + function Nullable(target, propertyKey, propertyDescriptor) { + // intentionally empty + } + Decorators.Nullable = Nullable; + function Override(target, propertyKey, propertyDescriptor) { + // do something with 'target' ... + } + Decorators.Override = Override; + function SuppressWarnings(options) { + return (target, propertyKey, descriptor) => { + // intentionally empty + }; + } + Decorators.SuppressWarnings = SuppressWarnings; + + return Decorators; +} + +var IntStream = {}; + +var hasRequiredIntStream; + +function requireIntStream () { + if (hasRequiredIntStream) return IntStream; + hasRequiredIntStream = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IntStream = void 0; + (function (IntStream) { + /** + * The value returned by {@link #LA LA()} when the end of the stream is + * reached. + */ + IntStream.EOF = -1; + /** + * The value returned by {@link #getSourceName} when the actual name of the + * underlying source is not known. + */ + IntStream.UNKNOWN_SOURCE_NAME = ""; + })(exports.IntStream || (exports.IntStream = {})); + + } (IntStream)); + return IntStream; +} + +var hasRequiredANTLRInputStream; + +function requireANTLRInputStream () { + if (hasRequiredANTLRInputStream) return ANTLRInputStream; + hasRequiredANTLRInputStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + // ConvertTo-TS run at 2016-10-04T11:26:49.0828748-07:00 + var __decorate = (ANTLRInputStream && ANTLRInputStream.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ANTLRInputStream, "__esModule", { value: true }); + ANTLRInputStream.ANTLRInputStream = void 0; + const assert = require$$0$9; + const Decorators_1 = requireDecorators(); + const IntStream_1 = requireIntStream(); + /** + * Vacuum all input from a {@link Reader}/{@link InputStream} and then treat it + * like a `char[]` buffer. Can also pass in a {@link String} or + * `char[]` to use. + * + * If you need encoding, pass in stream/reader with correct encoding. + * + * @deprecated as of 4.7, please use `CharStreams` interface. + */ + let ANTLRInputStream$1 = class ANTLRInputStream { + /** Copy data in string to a local char array */ + constructor(input) { + /** 0..n-1 index into string of next char */ + this.p = 0; + this.data = input; + this.n = input.length; + } + /** Reset the stream so that it's in the same state it was + * when the object was created *except* the data array is not + * touched. + */ + reset() { + this.p = 0; + } + consume() { + if (this.p >= this.n) { + assert(this.LA(1) === IntStream_1.IntStream.EOF); + throw new Error("cannot consume EOF"); + } + //System.out.println("prev p="+p+", c="+(char)data[p]); + if (this.p < this.n) { + this.p++; + //System.out.println("p moves to "+p+" (c='"+(char)data[p]+"')"); + } + } + LA(i) { + if (i === 0) { + return 0; // undefined + } + if (i < 0) { + i++; // e.g., translate LA(-1) to use offset i=0; then data[p+0-1] + if ((this.p + i - 1) < 0) { + return IntStream_1.IntStream.EOF; // invalid; no char before first char + } + } + if ((this.p + i - 1) >= this.n) { + //System.out.println("char LA("+i+")=EOF; p="+p); + return IntStream_1.IntStream.EOF; + } + //System.out.println("char LA("+i+")="+(char)data[p+i-1]+"; p="+p); + //System.out.println("LA("+i+"); p="+p+" n="+n+" data.length="+data.length); + return this.data.charCodeAt(this.p + i - 1); + } + LT(i) { + return this.LA(i); + } + /** Return the current input symbol index 0..n where n indicates the + * last symbol has been read. The index is the index of char to + * be returned from LA(1). + */ + get index() { + return this.p; + } + get size() { + return this.n; + } + /** mark/release do nothing; we have entire buffer */ + mark() { + return -1; + } + release(marker) { + // No default implementation since this stream buffers the entire input + } + /** consume() ahead until p==index; can't just set p=index as we must + * update line and charPositionInLine. If we seek backwards, just set p + */ + seek(index) { + if (index <= this.p) { + this.p = index; // just jump; don't update stream state (line, ...) + return; + } + // seek forward, consume until p hits index or n (whichever comes first) + index = Math.min(index, this.n); + while (this.p < index) { + this.consume(); + } + } + getText(interval) { + let start = interval.a; + let stop = interval.b; + if (stop >= this.n) { + stop = this.n - 1; + } + let count = stop - start + 1; + if (start >= this.n) { + return ""; + } + // System.err.println("data: "+Arrays.toString(data)+", n="+n+ + // ", start="+start+ + // ", stop="+stop); + return this.data.substr(start, count); + } + get sourceName() { + if (!this.name) { + return IntStream_1.IntStream.UNKNOWN_SOURCE_NAME; + } + return this.name; + } + toString() { return this.data; } + }; + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "consume", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "LA", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "index", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "mark", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "release", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "seek", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "getText", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "sourceName", null); + __decorate([ + Decorators_1.Override + ], ANTLRInputStream$1.prototype, "toString", null); + ANTLRInputStream.ANTLRInputStream = ANTLRInputStream$1; + + return ANTLRInputStream; +} + +var BailErrorStrategy = {}; + +var DefaultErrorStrategy = {}; + +var ATNState = {}; + +var hasRequiredATNState; + +function requireATNState () { + if (hasRequiredATNState) return ATNState; + hasRequiredATNState = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNState && ATNState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATNState = void 0; + const Decorators_1 = requireDecorators(); + /** + * The following images show the relation of states and + * {@link ATNState#transitions} for various grammar constructs. + * + * * Solid edges marked with an ε indicate a required + * {@link EpsilonTransition}. + * + * * Dashed edges indicate locations where any transition derived from + * {@link Transition} might appear. + * + * * Dashed nodes are place holders for either a sequence of linked + * {@link BasicState} states or the inclusion of a block representing a nested + * construct in one of the forms below. + * + * * Nodes showing multiple outgoing alternatives with a `...` support + * any number of alternatives (one or more). Nodes without the `...` only + * support the exact number of alternatives shown in the diagram. + * + *

Basic Blocks

+ * + *

Rule

+ * + * + * + *

Block of 1 or more alternatives

+ * + * + * + *

Greedy Loops

+ * + *

Greedy Closure: `(...)*`

+ * + * + * + *

Greedy Positive Closure: `(...)+`

+ * + * + * + *

Greedy Optional: `(...)?`

+ * + * + * + *

Non-Greedy Loops

+ * + *

Non-Greedy Closure: `(...)*?`

+ * + * + * + *

Non-Greedy Positive Closure: `(...)+?`

+ * + * + * + *

Non-Greedy Optional: `(...)??`

+ * + * + */ + let ATNState$1 = class ATNState { + constructor() { + this.stateNumber = ATNState.INVALID_STATE_NUMBER; + this.ruleIndex = 0; // at runtime, we don't have Rule objects + this.epsilonOnlyTransitions = false; + /** Track the transitions emanating from this ATN state. */ + this.transitions = []; + this.optimizedTransitions = this.transitions; + } + /** + * Gets the state number. + * + * @returns the state number + */ + getStateNumber() { + return this.stateNumber; + } + /** + * For all states except {@link RuleStopState}, this returns the state + * number. Returns -1 for stop states. + * + * @returns -1 for {@link RuleStopState}, otherwise the state number + */ + get nonStopStateNumber() { + return this.getStateNumber(); + } + hashCode() { + return this.stateNumber; + } + equals(o) { + // are these states same object? + if (o instanceof ATNState) { + return this.stateNumber === o.stateNumber; + } + return false; + } + get isNonGreedyExitState() { + return false; + } + toString() { + return String(this.stateNumber); + } + getTransitions() { + return this.transitions.slice(0); + } + get numberOfTransitions() { + return this.transitions.length; + } + addTransition(e, index) { + if (this.transitions.length === 0) { + this.epsilonOnlyTransitions = e.isEpsilon; + } + else if (this.epsilonOnlyTransitions !== e.isEpsilon) { + this.epsilonOnlyTransitions = false; + throw new Error("ATN state " + this.stateNumber + " has both epsilon and non-epsilon transitions."); + } + this.transitions.splice(index !== undefined ? index : this.transitions.length, 0, e); + } + transition(i) { + return this.transitions[i]; + } + setTransition(i, e) { + this.transitions[i] = e; + } + removeTransition(index) { + return this.transitions.splice(index, 1)[0]; + } + get onlyHasEpsilonTransitions() { + return this.epsilonOnlyTransitions; + } + setRuleIndex(ruleIndex) { + this.ruleIndex = ruleIndex; + } + get isOptimized() { + return this.optimizedTransitions !== this.transitions; + } + get numberOfOptimizedTransitions() { + return this.optimizedTransitions.length; + } + getOptimizedTransition(i) { + return this.optimizedTransitions[i]; + } + addOptimizedTransition(e) { + if (!this.isOptimized) { + this.optimizedTransitions = new Array(); + } + this.optimizedTransitions.push(e); + } + setOptimizedTransition(i, e) { + if (!this.isOptimized) { + throw new Error("This ATNState is not optimized."); + } + this.optimizedTransitions[i] = e; + } + removeOptimizedTransition(i) { + if (!this.isOptimized) { + throw new Error("This ATNState is not optimized."); + } + this.optimizedTransitions.splice(i, 1); + } + }; + __decorate([ + Decorators_1.Override + ], ATNState$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], ATNState$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], ATNState$1.prototype, "toString", null); + exports.ATNState = ATNState$1; + (function (ATNState) { + ATNState.INVALID_STATE_NUMBER = -1; + })(ATNState$1 = exports.ATNState || (exports.ATNState = {})); + + } (ATNState)); + return ATNState; +} + +var ATNStateType = {}; + +var hasRequiredATNStateType; + +function requireATNStateType () { + if (hasRequiredATNStateType) return ATNStateType; + hasRequiredATNStateType = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATNStateType = void 0; + (function (ATNStateType) { + ATNStateType[ATNStateType["INVALID_TYPE"] = 0] = "INVALID_TYPE"; + ATNStateType[ATNStateType["BASIC"] = 1] = "BASIC"; + ATNStateType[ATNStateType["RULE_START"] = 2] = "RULE_START"; + ATNStateType[ATNStateType["BLOCK_START"] = 3] = "BLOCK_START"; + ATNStateType[ATNStateType["PLUS_BLOCK_START"] = 4] = "PLUS_BLOCK_START"; + ATNStateType[ATNStateType["STAR_BLOCK_START"] = 5] = "STAR_BLOCK_START"; + ATNStateType[ATNStateType["TOKEN_START"] = 6] = "TOKEN_START"; + ATNStateType[ATNStateType["RULE_STOP"] = 7] = "RULE_STOP"; + ATNStateType[ATNStateType["BLOCK_END"] = 8] = "BLOCK_END"; + ATNStateType[ATNStateType["STAR_LOOP_BACK"] = 9] = "STAR_LOOP_BACK"; + ATNStateType[ATNStateType["STAR_LOOP_ENTRY"] = 10] = "STAR_LOOP_ENTRY"; + ATNStateType[ATNStateType["PLUS_LOOP_BACK"] = 11] = "PLUS_LOOP_BACK"; + ATNStateType[ATNStateType["LOOP_END"] = 12] = "LOOP_END"; + })(exports.ATNStateType || (exports.ATNStateType = {})); + + } (ATNStateType)); + return ATNStateType; +} + +var FailedPredicateException = {}; + +var RecognitionException = {}; + +var hasRequiredRecognitionException; + +function requireRecognitionException () { + if (hasRequiredRecognitionException) return RecognitionException; + hasRequiredRecognitionException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(RecognitionException, "__esModule", { value: true }); + RecognitionException.RecognitionException = void 0; + /** The root of the ANTLR exception hierarchy. In general, ANTLR tracks just + * 3 kinds of errors: prediction errors, failed predicate errors, and + * mismatched input errors. In each case, the parser knows where it is + * in the input, where it is in the ATN, the rule invocation stack, + * and what kind of problem occurred. + */ + let RecognitionException$1 = class RecognitionException extends Error { + constructor(recognizer, input, ctx, message) { + super(message); + this._offendingState = -1; + this._recognizer = recognizer; + this.input = input; + this.ctx = ctx; + if (recognizer) { + this._offendingState = recognizer.state; + } + } + /** + * Get the ATN state number the parser was in at the time the error + * occurred. For {@link NoViableAltException} and + * {@link LexerNoViableAltException} exceptions, this is the + * {@link DecisionState} number. For others, it is the state whose outgoing + * edge we couldn't match. + * + * If the state number is not known, this method returns -1. + */ + get offendingState() { + return this._offendingState; + } + setOffendingState(offendingState) { + this._offendingState = offendingState; + } + /** + * Gets the set of input symbols which could potentially follow the + * previously matched symbol at the time this exception was thrown. + * + * If the set of expected tokens is not known and could not be computed, + * this method returns `undefined`. + * + * @returns The set of token types that could potentially follow the current + * state in the ATN, or `undefined` if the information is not available. + */ + get expectedTokens() { + if (this._recognizer) { + return this._recognizer.atn.getExpectedTokens(this._offendingState, this.ctx); + } + return undefined; + } + /** + * Gets the {@link RuleContext} at the time this exception was thrown. + * + * If the context is not available, this method returns `undefined`. + * + * @returns The {@link RuleContext} at the time this exception was thrown. + * If the context is not available, this method returns `undefined`. + */ + get context() { + return this.ctx; + } + /** + * Gets the input stream which is the symbol source for the recognizer where + * this exception was thrown. + * + * If the input stream is not available, this method returns `undefined`. + * + * @returns The input stream which is the symbol source for the recognizer + * where this exception was thrown, or `undefined` if the stream is not + * available. + */ + get inputStream() { + return this.input; + } + getOffendingToken(recognizer) { + if (recognizer && recognizer !== this._recognizer) { + return undefined; + } + return this.offendingToken; + } + setOffendingToken(recognizer, offendingToken) { + if (recognizer === this._recognizer) { + this.offendingToken = offendingToken; + } + } + /** + * Gets the {@link Recognizer} where this exception occurred. + * + * If the recognizer is not available, this method returns `undefined`. + * + * @returns The recognizer where this exception occurred, or `undefined` if + * the recognizer is not available. + */ + get recognizer() { + return this._recognizer; + } + }; + RecognitionException.RecognitionException = RecognitionException$1; + + return RecognitionException; +} + +var PredicateTransition = {}; + +var AbstractPredicateTransition = {}; + +var Transition = {}; + +var hasRequiredTransition; + +function requireTransition () { + if (hasRequiredTransition) return Transition; + hasRequiredTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Transition && Transition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (Transition && Transition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(Transition, "__esModule", { value: true }); + Transition.Transition = void 0; + const Decorators_1 = requireDecorators(); + /** An ATN transition between any two ATN states. Subclasses define + * atom, set, epsilon, action, predicate, rule transitions. + * + * This is a one way link. It emanates from a state (usually via a list of + * transitions) and has a target state. + * + * Since we never have to change the ATN transitions once we construct it, + * we can fix these transitions as specific classes. The DFA transitions + * on the other hand need to update the labels as it adds transitions to + * the states. We'll use the term Edge for the DFA to distinguish them from + * ATN transitions. + */ + let Transition$1 = class Transition { + constructor(target) { + if (target == null) { + throw new Error("target cannot be null."); + } + this.target = target; + } + /** + * Determines if the transition is an "epsilon" transition. + * + * The default implementation returns `false`. + * + * @returns `true` if traversing this transition in the ATN does not + * consume an input symbol; otherwise, `false` if traversing this + * transition consumes (matches) an input symbol. + */ + get isEpsilon() { + return false; + } + get label() { + return undefined; + } + }; + Transition$1.serializationNames = [ + "INVALID", + "EPSILON", + "RANGE", + "RULE", + "PREDICATE", + "ATOM", + "ACTION", + "SET", + "NOT_SET", + "WILDCARD", + "PRECEDENCE", + ]; + __decorate([ + Decorators_1.NotNull + ], Transition$1.prototype, "target", void 0); + Transition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], Transition$1); + Transition.Transition = Transition$1; + + return Transition; +} + +var hasRequiredAbstractPredicateTransition; + +function requireAbstractPredicateTransition () { + if (hasRequiredAbstractPredicateTransition) return AbstractPredicateTransition; + hasRequiredAbstractPredicateTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(AbstractPredicateTransition, "__esModule", { value: true }); + AbstractPredicateTransition.AbstractPredicateTransition = void 0; + const Transition_1 = requireTransition(); + /** + * + * @author Sam Harwell + */ + let AbstractPredicateTransition$1 = class AbstractPredicateTransition extends Transition_1.Transition { + constructor(target) { + super(target); + } + }; + AbstractPredicateTransition.AbstractPredicateTransition = AbstractPredicateTransition$1; + + return AbstractPredicateTransition; +} + +var SemanticContext = {}; + +var Array2DHashSet = {}; + +var DefaultEqualityComparator = {}; + +var MurmurHash = {}; + +var hasRequiredMurmurHash; + +function requireMurmurHash () { + if (hasRequiredMurmurHash) return MurmurHash; + hasRequiredMurmurHash = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MurmurHash = void 0; + (function (MurmurHash) { + const DEFAULT_SEED = 0; + /** + * Initialize the hash using the specified `seed`. + * + * @param seed the seed (optional) + * @returns the intermediate hash value + */ + function initialize(seed = DEFAULT_SEED) { + return seed; + } + MurmurHash.initialize = initialize; + /** + * Update the intermediate hash value for the next input `value`. + * + * @param hash the intermediate hash value + * @param value the value to add to the current hash + * @returns the updated intermediate hash value + */ + function update(hash, value) { + const c1 = 0xCC9E2D51; + const c2 = 0x1B873593; + const r1 = 15; + const r2 = 13; + const m = 5; + const n = 0xE6546B64; + if (value == null) { + value = 0; + } + else if (typeof value === "string") { + value = hashString(value); + } + else if (typeof value === "object") { + value = value.hashCode(); + } + let k = value; + k = Math.imul(k, c1); + k = (k << r1) | (k >>> (32 - r1)); + k = Math.imul(k, c2); + hash = hash ^ k; + hash = (hash << r2) | (hash >>> (32 - r2)); + hash = Math.imul(hash, m) + n; + return hash & 0xFFFFFFFF; + } + MurmurHash.update = update; + /** + * Apply the final computation steps to the intermediate value `hash` + * to form the final result of the MurmurHash 3 hash function. + * + * @param hash the intermediate hash value + * @param numberOfWords the number of integer values added to the hash + * @returns the final hash result + */ + function finish(hash, numberOfWords) { + hash = hash ^ (numberOfWords * 4); + hash = hash ^ (hash >>> 16); + hash = Math.imul(hash, 0x85EBCA6B); + hash = hash ^ (hash >>> 13); + hash = Math.imul(hash, 0xC2B2AE35); + hash = hash ^ (hash >>> 16); + return hash; + } + MurmurHash.finish = finish; + /** + * Utility function to compute the hash code of an array using the + * MurmurHash algorithm. + * + * @param the array element type + * @param data the array data + * @param seed the seed for the MurmurHash algorithm + * @returns the hash code of the data + */ + function hashCode(data, seed = DEFAULT_SEED) { + let hash = initialize(seed); + let length = 0; + for (let value of data) { + hash = update(hash, value); + length++; + } + hash = finish(hash, length); + return hash; + } + MurmurHash.hashCode = hashCode; + /** + * Function to hash a string. Based on the implementation found here: + * http://stackoverflow.com/a/7616484 + */ + function hashString(str) { + let len = str.length; + if (len === 0) { + return 0; + } + let hash = 0; + for (let i = 0; i < len; i++) { + let c = str.charCodeAt(i); + hash = (((hash << 5) >>> 0) - hash) + c; + hash |= 0; + } + return hash; + } + })(exports.MurmurHash || (exports.MurmurHash = {})); + + } (MurmurHash)); + return MurmurHash; +} + +var ObjectEqualityComparator = {}; + +var hasRequiredObjectEqualityComparator; + +function requireObjectEqualityComparator () { + if (hasRequiredObjectEqualityComparator) return ObjectEqualityComparator; + hasRequiredObjectEqualityComparator = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ObjectEqualityComparator && ObjectEqualityComparator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ObjectEqualityComparator, "__esModule", { value: true }); + ObjectEqualityComparator.ObjectEqualityComparator = void 0; + const Decorators_1 = requireDecorators(); + /** + * This default implementation of {@link EqualityComparator} uses object equality + * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. + * + * @author Sam Harwell + */ + let ObjectEqualityComparator$1 = class ObjectEqualityComparator { + /** + * {@inheritDoc} + * + * This implementation returns + * `obj.`{@link Object#hashCode hashCode()}. + */ + hashCode(obj) { + if (obj == null) { + return 0; + } + return obj.hashCode(); + } + /** + * {@inheritDoc} + * + * This implementation relies on object equality. If both objects are + * `undefined` or `null`, this method returns `true`. Otherwise if only + * `a` is `undefined` or `null`, this method returns `false`. Otherwise, + * this method returns the result of + * `a.`{@link Object#equals equals}`(b)`. + */ + equals(a, b) { + if (a == null) { + return b == null; + } + return a.equals(b); + } + }; + ObjectEqualityComparator$1.INSTANCE = new ObjectEqualityComparator$1(); + __decorate([ + Decorators_1.Override + ], ObjectEqualityComparator$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], ObjectEqualityComparator$1.prototype, "equals", null); + ObjectEqualityComparator.ObjectEqualityComparator = ObjectEqualityComparator$1; + + return ObjectEqualityComparator; +} + +var hasRequiredDefaultEqualityComparator; + +function requireDefaultEqualityComparator () { + if (hasRequiredDefaultEqualityComparator) return DefaultEqualityComparator; + hasRequiredDefaultEqualityComparator = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DefaultEqualityComparator && DefaultEqualityComparator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(DefaultEqualityComparator, "__esModule", { value: true }); + DefaultEqualityComparator.DefaultEqualityComparator = void 0; + const Decorators_1 = requireDecorators(); + const MurmurHash_1 = requireMurmurHash(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + /** + * This default implementation of {@link EqualityComparator} uses object equality + * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. + * + * @author Sam Harwell + */ + let DefaultEqualityComparator$1 = class DefaultEqualityComparator { + /** + * {@inheritDoc} + * + * This implementation returns + * `obj.`{@link Object#hashCode hashCode()}. + */ + hashCode(obj) { + if (obj == null) { + return 0; + } + else if (typeof obj === "string" || typeof obj === "number") { + return MurmurHash_1.MurmurHash.hashCode([obj]); + } + else { + return ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE.hashCode(obj); + } + } + /** + * {@inheritDoc} + * + * This implementation relies on object equality. If both objects are + * `undefined` or `null`, this method returns `true`. Otherwise if only + * `a` is `undefined` or `null`, this method returns `false`. Otherwise, + * this method returns the result of + * `a.`{@link Object#equals equals}`(b)`. + */ + equals(a, b) { + if (a == null) { + return b == null; + } + else if (typeof a === "string" || typeof a === "number") { + return a === b; + } + else { + return ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE.equals(a, b); + } + } + }; + DefaultEqualityComparator$1.INSTANCE = new DefaultEqualityComparator$1(); + __decorate([ + Decorators_1.Override + ], DefaultEqualityComparator$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], DefaultEqualityComparator$1.prototype, "equals", null); + DefaultEqualityComparator.DefaultEqualityComparator = DefaultEqualityComparator$1; + + return DefaultEqualityComparator; +} + +var hasRequiredArray2DHashSet; + +function requireArray2DHashSet () { + if (hasRequiredArray2DHashSet) return Array2DHashSet; + hasRequiredArray2DHashSet = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Array2DHashSet && Array2DHashSet.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (Array2DHashSet && Array2DHashSet.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(Array2DHashSet, "__esModule", { value: true }); + Array2DHashSet.Array2DHashSet = void 0; + // ConvertTo-TS run at 2016-10-03T02:09:41.7434086-07:00 + const assert = require$$0$9; + const DefaultEqualityComparator_1 = requireDefaultEqualityComparator(); + const Decorators_1 = requireDecorators(); + const MurmurHash_1 = requireMurmurHash(); + /** {@link Set} implementation with closed hashing (open addressing). */ + // NOTE: JavaScript's Set interface has on significant different diffrence from Java's: + // e.g. the return type of add() differs! + // For this reason I've commented tweaked the implements clause + const INITAL_CAPACITY = 16; // must be power of 2 + const LOAD_FACTOR = 0.75; + let Array2DHashSet$1 = class Array2DHashSet { + constructor(comparatorOrSet, initialCapacity = INITAL_CAPACITY) { + /** How many elements in set */ + this.n = 0; + this.threshold = Math.floor(INITAL_CAPACITY * LOAD_FACTOR); // when to expand + if (comparatorOrSet instanceof Array2DHashSet) { + this.comparator = comparatorOrSet.comparator; + this.buckets = comparatorOrSet.buckets.slice(0); + for (let i = 0; i < this.buckets.length; i++) { + let bucket = this.buckets[i]; + if (bucket) { + this.buckets[i] = bucket.slice(0); + } + } + this.n = comparatorOrSet.n; + this.threshold = comparatorOrSet.threshold; + } + else { + this.comparator = comparatorOrSet || DefaultEqualityComparator_1.DefaultEqualityComparator.INSTANCE; + this.buckets = this.createBuckets(initialCapacity); + } + } + /** + * Add `o` to set if not there; return existing value if already + * there. This method performs the same operation as {@link #add} aside from + * the return value. + */ + getOrAdd(o) { + if (this.n > this.threshold) { + this.expand(); + } + return this.getOrAddImpl(o); + } + getOrAddImpl(o) { + let b = this.getBucket(o); + let bucket = this.buckets[b]; + // NEW BUCKET + if (!bucket) { + bucket = [o]; + this.buckets[b] = bucket; + this.n++; + return o; + } + // LOOK FOR IT IN BUCKET + for (let existing of bucket) { + if (this.comparator.equals(existing, o)) { + return existing; // found existing, quit + } + } + // FULL BUCKET, expand and add to end + bucket.push(o); + this.n++; + return o; + } + get(o) { + if (o == null) { + return o; + } + let b = this.getBucket(o); + let bucket = this.buckets[b]; + if (!bucket) { + // no bucket + return undefined; + } + for (let e of bucket) { + if (this.comparator.equals(e, o)) { + return e; + } + } + return undefined; + } + getBucket(o) { + let hash = this.comparator.hashCode(o); + let b = hash & (this.buckets.length - 1); // assumes len is power of 2 + return b; + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + for (let bucket of this.buckets) { + if (bucket == null) { + continue; + } + for (let o of bucket) { + if (o == null) { + break; + } + hash = MurmurHash_1.MurmurHash.update(hash, this.comparator.hashCode(o)); + } + } + hash = MurmurHash_1.MurmurHash.finish(hash, this.size); + return hash; + } + equals(o) { + if (o === this) { + return true; + } + if (!(o instanceof Array2DHashSet)) { + return false; + } + if (o.size !== this.size) { + return false; + } + let same = this.containsAll(o); + return same; + } + expand() { + let old = this.buckets; + let newCapacity = this.buckets.length * 2; + let newTable = this.createBuckets(newCapacity); + this.buckets = newTable; + this.threshold = Math.floor(newCapacity * LOAD_FACTOR); + // System.out.println("new size="+newCapacity+", thres="+threshold); + // rehash all existing entries + let oldSize = this.size; + for (let bucket of old) { + if (!bucket) { + continue; + } + for (let o of bucket) { + let b = this.getBucket(o); + let newBucket = this.buckets[b]; + if (!newBucket) { + newBucket = []; + this.buckets[b] = newBucket; + } + newBucket.push(o); + } + } + assert(this.n === oldSize); + } + add(t) { + let existing = this.getOrAdd(t); + return existing === t; + } + get size() { + return this.n; + } + get isEmpty() { + return this.n === 0; + } + contains(o) { + return this.containsFast(this.asElementType(o)); + } + containsFast(obj) { + if (obj == null) { + return false; + } + return this.get(obj) != null; + } + *[Symbol.iterator]() { + yield* this.toArray(); + } + toArray() { + const a = new Array(this.size); + // Copy elements from the nested arrays into the destination array + let i = 0; // Position within destination array + for (let bucket of this.buckets) { + if (bucket == null) { + continue; + } + for (let o of bucket) { + if (o == null) { + break; + } + a[i++] = o; + } + } + return a; + } + containsAll(collection) { + if (collection instanceof Array2DHashSet) { + let s = collection; + for (let bucket of s.buckets) { + if (bucket == null) { + continue; + } + for (let o of bucket) { + if (o == null) { + break; + } + if (!this.containsFast(this.asElementType(o))) { + return false; + } + } + } + } + else { + for (let o of collection) { + if (!this.containsFast(this.asElementType(o))) { + return false; + } + } + } + return true; + } + addAll(c) { + let changed = false; + for (let o of c) { + let existing = this.getOrAdd(o); + if (existing !== o) { + changed = true; + } + } + return changed; + } + clear() { + this.buckets = this.createBuckets(INITAL_CAPACITY); + this.n = 0; + this.threshold = Math.floor(INITAL_CAPACITY * LOAD_FACTOR); + } + toString() { + if (this.size === 0) { + return "{}"; + } + let buf = "{"; + let first = true; + for (let bucket of this.buckets) { + if (bucket == null) { + continue; + } + for (let o of bucket) { + if (o == null) { + break; + } + if (first) { + first = false; + } + else { + buf += ", "; + } + buf += o.toString(); + } + } + buf += "}"; + return buf; + } + toTableString() { + let buf = ""; + for (let bucket of this.buckets) { + if (bucket == null) { + buf += "null\n"; + continue; + } + buf += "["; + let first = true; + for (let o of bucket) { + if (first) { + first = false; + } + else { + buf += " "; + } + if (o == null) { + buf += "_"; + } + else { + buf += o.toString(); + } + } + buf += "]\n"; + } + return buf; + } + /** + * Return `o` as an instance of the element type `T`. If + * `o` is non-undefined but known to not be an instance of `T`, this + * method returns `undefined`. The base implementation does not perform any + * type checks; override this method to provide strong type checks for the + * {@link #contains} and {@link #remove} methods to ensure the arguments to + * the {@link EqualityComparator} for the set always have the expected + * types. + * + * @param o the object to try and cast to the element type of the set + * @returns `o` if it could be an instance of `T`, otherwise + * `undefined`. + */ + asElementType(o) { + return o; + } + /** + * Return an array of `T[]` with length `capacity`. + * + * @param capacity the length of the array to return + * @returns the newly constructed array + */ + createBuckets(capacity) { + return new Array(capacity); + } + }; + __decorate([ + Decorators_1.NotNull + ], Array2DHashSet$1.prototype, "comparator", void 0); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "add", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "isEmpty", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "contains", null); + __decorate([ + __param(0, Decorators_1.Nullable) + ], Array2DHashSet$1.prototype, "containsFast", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, Symbol.iterator, null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "toArray", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "containsAll", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "addAll", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "clear", null); + __decorate([ + Decorators_1.Override + ], Array2DHashSet$1.prototype, "toString", null); + __decorate([ + Decorators_1.SuppressWarnings("unchecked") + ], Array2DHashSet$1.prototype, "asElementType", null); + __decorate([ + Decorators_1.SuppressWarnings("unchecked") + ], Array2DHashSet$1.prototype, "createBuckets", null); + Array2DHashSet.Array2DHashSet = Array2DHashSet$1; + + return Array2DHashSet; +} + +var ArrayEqualityComparator = {}; + +var hasRequiredArrayEqualityComparator; + +function requireArrayEqualityComparator () { + if (hasRequiredArrayEqualityComparator) return ArrayEqualityComparator; + hasRequiredArrayEqualityComparator = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ArrayEqualityComparator && ArrayEqualityComparator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ArrayEqualityComparator, "__esModule", { value: true }); + ArrayEqualityComparator.ArrayEqualityComparator = void 0; + const Decorators_1 = requireDecorators(); + const MurmurHash_1 = requireMurmurHash(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + /** + * This default implementation of {@link EqualityComparator} uses object equality + * for comparisons by calling {@link Object#hashCode} and {@link Object#equals}. + * + * @author Sam Harwell + */ + let ArrayEqualityComparator$1 = class ArrayEqualityComparator { + /** + * {@inheritDoc} + * + * This implementation returns + * `obj.`{@link Object#hashCode hashCode()}. + */ + hashCode(obj) { + if (obj == null) { + return 0; + } + return MurmurHash_1.MurmurHash.hashCode(obj, 0); + } + /** + * {@inheritDoc} + * + * This implementation relies on object equality. If both objects are + * `undefined`, this method returns `true`. Otherwise if only + * `a` is `undefined`, this method returns `false`. Otherwise, + * this method returns the result of + * `a.`{@link Object#equals equals}`(b)`. + */ + equals(a, b) { + if (a == null) { + return b == null; + } + else if (b == null) { + return false; + } + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE.equals(a[i], b[i])) { + return false; + } + } + return true; + } + }; + ArrayEqualityComparator$1.INSTANCE = new ArrayEqualityComparator$1(); + __decorate([ + Decorators_1.Override + ], ArrayEqualityComparator$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], ArrayEqualityComparator$1.prototype, "equals", null); + ArrayEqualityComparator.ArrayEqualityComparator = ArrayEqualityComparator$1; + + return ArrayEqualityComparator; +} + +var Utils = {}; + +var hasRequiredUtils; + +function requireUtils () { + if (hasRequiredUtils) return Utils; + hasRequiredUtils = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Utils, "__esModule", { value: true }); + Utils.toCharArray = Utils.toMap = Utils.equals = Utils.join = Utils.escapeWhitespace = void 0; + function escapeWhitespace(s, escapeSpaces) { + return escapeSpaces ? s.replace(/ /, "\u00B7") : s + .replace(/\t/, "\\t") + .replace(/\n/, "\\n") + .replace(/\r/, "\\r"); + } + Utils.escapeWhitespace = escapeWhitespace; + // Seriously: why isn't this built in to java? ugh! + function join(collection, separator) { + let buf = ""; + let first = true; + for (let current of collection) { + if (first) { + first = false; + } + else { + buf += separator; + } + buf += current; + } + return buf; + } + Utils.join = join; + function equals(x, y) { + if (x === y) { + return true; + } + if (x === undefined || y === undefined) { + return false; + } + return x.equals(y); + } + Utils.equals = equals; + // export function numNonnull(data: any[]): number { + // let n: number = 0; + // if ( data == null ) return n; + // for (let o of data) { + // if ( o!=null ) n++; + // } + // return n; + // } + // export function removeAllElements(data: Collection, value: T): void { + // if ( data==null ) return; + // while ( data.contains(value) ) data.remove(value); + // } + // export function writeFile(@NotNull file: File, @NotNull content: Uint8Array): void { + // let fos: FileOutputStream = new FileOutputStream(file); + // try { + // fos.write(content); + // } finally { + // fos.close(); + // } + // } + // export function writeFile(@NotNull fileName: string, @NotNull content: string): void { + // writeFile(fileName, content, null); + // } + // export function writeFile(@NotNull fileName: string, @NotNull content: string, @Nullable encoding: string): void { + // let f: File = new File(fileName); + // let fos: FileOutputStream = new FileOutputStream(f); + // let osw: OutputStreamWriter; + // if (encoding != null) { + // osw = new OutputStreamWriter(fos, encoding); + // } + // else { + // osw = new OutputStreamWriter(fos); + // } + // try { + // osw.write(content); + // } + // finally { + // osw.close(); + // } + // } + // @NotNull + // export function readFile(@NotNull fileName: string): char[] { + // return readFile(fileName, null); + // } + // @NotNull + // export function readFile(@NotNull fileName: string, @Nullable encoding: string): char[] { + // let f: File = new File(fileName); + // let size: number = (int)f.length(); + // let isr: InputStreamReader; + // let fis: FileInputStream = new FileInputStream(fileName); + // if ( encoding!=null ) { + // isr = new InputStreamReader(fis, encoding); + // } + // else { + // isr = new InputStreamReader(fis); + // } + // let data: char[] = null; + // try { + // data = new char[size]; + // let n: number = isr.read(data); + // if (n < data.length) { + // data = Arrays.copyOf(data, n); + // } + // } + // finally { + // isr.close(); + // } + // return data; + // } + // export function removeAll(@NotNull predicate: List list,@NotNull Predicate): void { + // let j: number = 0; + // for (let i = 0; i < list.size; i++) { + // let item: T = list.get(i); + // if (!predicate.eval(item)) { + // if (j != i) { + // list.set(j, item); + // } + // j++; + // } + // } + // if (j < list.size) { + // list.subList(j, list.size).clear(); + // } + // } + // export function removeAll(@NotNull predicate: Iterable iterable,@NotNull Predicate): void { + // if (iterable instanceof List) { + // removeAll((List)iterable, predicate); + // return; + // } + // for (Iterator iterator = iterable.iterator(); iterator.hasNext(); ) { + // let item: T = iterator.next(); + // if (predicate.eval(item)) { + // iterator.remove(); + // } + // } + // } + /** Convert array of strings to string→index map. Useful for + * converting rulenames to name→ruleindex map. + */ + function toMap(keys) { + let m = new Map(); + for (let i = 0; i < keys.length; i++) { + m.set(keys[i], i); + } + return m; + } + Utils.toMap = toMap; + function toCharArray(str) { + if (typeof str === "string") { + let result = new Uint16Array(str.length); + for (let i = 0; i < str.length; i++) { + result[i] = str.charCodeAt(i); + } + return result; + } + else { + return str.toCharArray(); + } + } + Utils.toCharArray = toCharArray; + // /** + // * @since 4.5 + // */ + // @NotNull + // export function toSet(@NotNull bits: BitSet): IntervalSet { + // let s: IntervalSet = new IntervalSet(); + // let i: number = bits.nextSetBit(0); + // while ( i >= 0 ) { + // s.add(i); + // i = bits.nextSetBit(i+1); + // } + // return s; + // } + + return Utils; +} + +var hasRequiredSemanticContext; + +function requireSemanticContext () { + if (hasRequiredSemanticContext) return SemanticContext; + hasRequiredSemanticContext = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (SemanticContext && SemanticContext.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (SemanticContext && SemanticContext.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SemanticContext = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:36.9521478-07:00 + const Array2DHashSet_1 = requireArray2DHashSet(); + const ArrayEqualityComparator_1 = requireArrayEqualityComparator(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const Utils = requireUtils(); + function max(items) { + let result; + for (let current of items) { + if (result === undefined) { + result = current; + continue; + } + let comparison = result.compareTo(current); + if (comparison < 0) { + result = current; + } + } + return result; + } + function min(items) { + let result; + for (let current of items) { + if (result === undefined) { + result = current; + continue; + } + let comparison = result.compareTo(current); + if (comparison > 0) { + result = current; + } + } + return result; + } + /** A tree structure used to record the semantic context in which + * an ATN configuration is valid. It's either a single predicate, + * a conjunction `p1&&p2`, or a sum of products `p1||p2`. + * + * I have scoped the {@link AND}, {@link OR}, and {@link Predicate} subclasses of + * {@link SemanticContext} within the scope of this outer class. + */ + let SemanticContext$1 = class SemanticContext { + /** + * The default {@link SemanticContext}, which is semantically equivalent to + * a predicate of the form `{true}?`. + */ + static get NONE() { + if (SemanticContext._NONE === undefined) { + SemanticContext._NONE = new SemanticContext.Predicate(); + } + return SemanticContext._NONE; + } + /** + * Evaluate the precedence predicates for the context and reduce the result. + * + * @param parser The parser instance. + * @param parserCallStack + * @returns The simplified semantic context after precedence predicates are + * evaluated, which will be one of the following values. + * + * * {@link #NONE}: if the predicate simplifies to `true` after + * precedence predicates are evaluated. + * * `undefined`: if the predicate simplifies to `false` after + * precedence predicates are evaluated. + * * `this`: if the semantic context is not changed as a result of + * precedence predicate evaluation. + * * A non-`undefined` {@link SemanticContext}: the new simplified + * semantic context after precedence predicates are evaluated. + */ + evalPrecedence(parser, parserCallStack) { + return this; + } + static and(a, b) { + if (!a || a === SemanticContext.NONE) { + return b; + } + if (b === SemanticContext.NONE) { + return a; + } + let result = new SemanticContext.AND(a, b); + if (result.opnds.length === 1) { + return result.opnds[0]; + } + return result; + } + /** + * + * @see ParserATNSimulator#getPredsForAmbigAlts + */ + static or(a, b) { + if (!a) { + return b; + } + if (a === SemanticContext.NONE || b === SemanticContext.NONE) { + return SemanticContext.NONE; + } + let result = new SemanticContext.OR(a, b); + if (result.opnds.length === 1) { + return result.opnds[0]; + } + return result; + } + }; + exports.SemanticContext = SemanticContext$1; + (function (SemanticContext) { + /** + * This random 30-bit prime represents the value of `AND.class.hashCode()`. + */ + const AND_HASHCODE = 40363613; + /** + * This random 30-bit prime represents the value of `OR.class.hashCode()`. + */ + const OR_HASHCODE = 486279973; + function filterPrecedencePredicates(collection) { + let result = []; + for (let i = 0; i < collection.length; i++) { + let context = collection[i]; + if (context instanceof SemanticContext.PrecedencePredicate) { + result.push(context); + // Remove the item from 'collection' and move i back so we look at the same index again + collection.splice(i, 1); + i--; + } + } + return result; + } + class Predicate extends SemanticContext { + constructor(ruleIndex = -1, predIndex = -1, isCtxDependent = false) { + super(); + this.ruleIndex = ruleIndex; + this.predIndex = predIndex; + this.isCtxDependent = isCtxDependent; + } + eval(parser, parserCallStack) { + let localctx = this.isCtxDependent ? parserCallStack : undefined; + return parser.sempred(localctx, this.ruleIndex, this.predIndex); + } + hashCode() { + let hashCode = MurmurHash_1.MurmurHash.initialize(); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.ruleIndex); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.predIndex); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.isCtxDependent ? 1 : 0); + hashCode = MurmurHash_1.MurmurHash.finish(hashCode, 3); + return hashCode; + } + equals(obj) { + if (!(obj instanceof Predicate)) { + return false; + } + if (this === obj) { + return true; + } + return this.ruleIndex === obj.ruleIndex && + this.predIndex === obj.predIndex && + this.isCtxDependent === obj.isCtxDependent; + } + toString() { + return "{" + this.ruleIndex + ":" + this.predIndex + "}?"; + } + } + __decorate([ + Decorators_1.Override + ], Predicate.prototype, "eval", null); + __decorate([ + Decorators_1.Override + ], Predicate.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], Predicate.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], Predicate.prototype, "toString", null); + SemanticContext.Predicate = Predicate; + class PrecedencePredicate extends SemanticContext { + constructor(precedence) { + super(); + this.precedence = precedence; + } + eval(parser, parserCallStack) { + return parser.precpred(parserCallStack, this.precedence); + } + evalPrecedence(parser, parserCallStack) { + if (parser.precpred(parserCallStack, this.precedence)) { + return SemanticContext.NONE; + } + else { + return undefined; + } + } + compareTo(o) { + return this.precedence - o.precedence; + } + hashCode() { + let hashCode = 1; + hashCode = 31 * hashCode + this.precedence; + return hashCode; + } + equals(obj) { + if (!(obj instanceof PrecedencePredicate)) { + return false; + } + if (this === obj) { + return true; + } + return this.precedence === obj.precedence; + } + toString() { + return "{" + this.precedence + ">=prec}?"; + } + } + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "eval", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "evalPrecedence", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "compareTo", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicate.prototype, "toString", null); + SemanticContext.PrecedencePredicate = PrecedencePredicate; + /** + * This is the base class for semantic context "operators", which operate on + * a collection of semantic context "operands". + * + * @since 4.3 + */ + class Operator extends SemanticContext { + } + SemanticContext.Operator = Operator; + /** + * A semantic context which is true whenever none of the contained contexts + * is false. + */ + let AND = class AND extends Operator { + constructor(a, b) { + super(); + let operands = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + if (a instanceof AND) { + operands.addAll(a.opnds); + } + else { + operands.add(a); + } + if (b instanceof AND) { + operands.addAll(b.opnds); + } + else { + operands.add(b); + } + this.opnds = operands.toArray(); + let precedencePredicates = filterPrecedencePredicates(this.opnds); + // interested in the transition with the lowest precedence + let reduced = min(precedencePredicates); + if (reduced) { + this.opnds.push(reduced); + } + } + get operands() { + return this.opnds; + } + equals(obj) { + if (this === obj) { + return true; + } + if (!(obj instanceof AND)) { + return false; + } + return ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.equals(this.opnds, obj.opnds); + } + hashCode() { + return MurmurHash_1.MurmurHash.hashCode(this.opnds, AND_HASHCODE); + } + /** + * {@inheritDoc} + * + * The evaluation of predicates by this context is short-circuiting, but + * unordered. + */ + eval(parser, parserCallStack) { + for (let opnd of this.opnds) { + if (!opnd.eval(parser, parserCallStack)) { + return false; + } + } + return true; + } + evalPrecedence(parser, parserCallStack) { + let differs = false; + let operands = []; + for (let context of this.opnds) { + let evaluated = context.evalPrecedence(parser, parserCallStack); + differs = differs || (evaluated !== context); + if (evaluated == null) { + // The AND context is false if any element is false + return undefined; + } + else if (evaluated !== SemanticContext.NONE) { + // Reduce the result by skipping true elements + operands.push(evaluated); + } + } + if (!differs) { + return this; + } + if (operands.length === 0) { + // all elements were true, so the AND context is true + return SemanticContext.NONE; + } + let result = operands[0]; + for (let i = 1; i < operands.length; i++) { + result = SemanticContext.and(result, operands[i]); + } + return result; + } + toString() { + return Utils.join(this.opnds, "&&"); + } + }; + __decorate([ + Decorators_1.Override + ], AND.prototype, "operands", null); + __decorate([ + Decorators_1.Override + ], AND.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], AND.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], AND.prototype, "eval", null); + __decorate([ + Decorators_1.Override + ], AND.prototype, "evalPrecedence", null); + __decorate([ + Decorators_1.Override + ], AND.prototype, "toString", null); + AND = __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], AND); + SemanticContext.AND = AND; + /** + * A semantic context which is true whenever at least one of the contained + * contexts is true. + */ + let OR = class OR extends Operator { + constructor(a, b) { + super(); + let operands = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + if (a instanceof OR) { + operands.addAll(a.opnds); + } + else { + operands.add(a); + } + if (b instanceof OR) { + operands.addAll(b.opnds); + } + else { + operands.add(b); + } + this.opnds = operands.toArray(); + let precedencePredicates = filterPrecedencePredicates(this.opnds); + // interested in the transition with the highest precedence + let reduced = max(precedencePredicates); + if (reduced) { + this.opnds.push(reduced); + } + } + get operands() { + return this.opnds; + } + equals(obj) { + if (this === obj) { + return true; + } + if (!(obj instanceof OR)) { + return false; + } + return ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.equals(this.opnds, obj.opnds); + } + hashCode() { + return MurmurHash_1.MurmurHash.hashCode(this.opnds, OR_HASHCODE); + } + /** + * {@inheritDoc} + * + * The evaluation of predicates by this context is short-circuiting, but + * unordered. + */ + eval(parser, parserCallStack) { + for (let opnd of this.opnds) { + if (opnd.eval(parser, parserCallStack)) { + return true; + } + } + return false; + } + evalPrecedence(parser, parserCallStack) { + let differs = false; + let operands = []; + for (let context of this.opnds) { + let evaluated = context.evalPrecedence(parser, parserCallStack); + differs = differs || (evaluated !== context); + if (evaluated === SemanticContext.NONE) { + // The OR context is true if any element is true + return SemanticContext.NONE; + } + else if (evaluated) { + // Reduce the result by skipping false elements + operands.push(evaluated); + } + } + if (!differs) { + return this; + } + if (operands.length === 0) { + // all elements were false, so the OR context is false + return undefined; + } + let result = operands[0]; + for (let i = 1; i < operands.length; i++) { + result = SemanticContext.or(result, operands[i]); + } + return result; + } + toString() { + return Utils.join(this.opnds, "||"); + } + }; + __decorate([ + Decorators_1.Override + ], OR.prototype, "operands", null); + __decorate([ + Decorators_1.Override + ], OR.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], OR.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], OR.prototype, "eval", null); + __decorate([ + Decorators_1.Override + ], OR.prototype, "evalPrecedence", null); + __decorate([ + Decorators_1.Override + ], OR.prototype, "toString", null); + OR = __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], OR); + SemanticContext.OR = OR; + })(SemanticContext$1 = exports.SemanticContext || (exports.SemanticContext = {})); + + } (SemanticContext)); + return SemanticContext; +} + +var hasRequiredPredicateTransition; + +function requirePredicateTransition () { + if (hasRequiredPredicateTransition) return PredicateTransition; + hasRequiredPredicateTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PredicateTransition && PredicateTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (PredicateTransition && PredicateTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(PredicateTransition, "__esModule", { value: true }); + PredicateTransition.PredicateTransition = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.2826960-07:00 + const AbstractPredicateTransition_1 = requireAbstractPredicateTransition(); + const Decorators_1 = requireDecorators(); + const SemanticContext_1 = requireSemanticContext(); + /** TODO: this is old comment: + * A tree of semantic predicates from the grammar AST if label==SEMPRED. + * In the ATN, labels will always be exactly one predicate, but the DFA + * may have to combine a bunch of them as it collects predicates from + * multiple ATN configurations into a single DFA state. + */ + let PredicateTransition$1 = class PredicateTransition extends AbstractPredicateTransition_1.AbstractPredicateTransition { + constructor(target, ruleIndex, predIndex, isCtxDependent) { + super(target); + this.ruleIndex = ruleIndex; + this.predIndex = predIndex; + this.isCtxDependent = isCtxDependent; + } + get serializationType() { + return 4 /* PREDICATE */; + } + get isEpsilon() { return true; } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return false; + } + get predicate() { + return new SemanticContext_1.SemanticContext.Predicate(this.ruleIndex, this.predIndex, this.isCtxDependent); + } + toString() { + return "pred_" + this.ruleIndex + ":" + this.predIndex; + } + }; + __decorate([ + Decorators_1.Override + ], PredicateTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], PredicateTransition$1.prototype, "isEpsilon", null); + __decorate([ + Decorators_1.Override + ], PredicateTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], PredicateTransition$1.prototype, "toString", null); + PredicateTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], PredicateTransition$1); + PredicateTransition.PredicateTransition = PredicateTransition$1; + + return PredicateTransition; +} + +var hasRequiredFailedPredicateException; + +function requireFailedPredicateException () { + if (hasRequiredFailedPredicateException) return FailedPredicateException; + hasRequiredFailedPredicateException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (FailedPredicateException && FailedPredicateException.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (FailedPredicateException && FailedPredicateException.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(FailedPredicateException, "__esModule", { value: true }); + FailedPredicateException.FailedPredicateException = void 0; + const RecognitionException_1 = requireRecognitionException(); + const Decorators_1 = requireDecorators(); + const PredicateTransition_1 = requirePredicateTransition(); + /** A semantic predicate failed during validation. Validation of predicates + * occurs when normally parsing the alternative just like matching a token. + * Disambiguating predicate evaluation occurs when we test a predicate during + * prediction. + */ + let FailedPredicateException$1 = class FailedPredicateException extends RecognitionException_1.RecognitionException { + constructor(recognizer, predicate, message) { + super(recognizer, recognizer.inputStream, recognizer.context, FailedPredicateException.formatMessage(predicate, message)); + let s = recognizer.interpreter.atn.states[recognizer.state]; + let trans = s.transition(0); + if (trans instanceof PredicateTransition_1.PredicateTransition) { + this._ruleIndex = trans.ruleIndex; + this._predicateIndex = trans.predIndex; + } + else { + this._ruleIndex = 0; + this._predicateIndex = 0; + } + this._predicate = predicate; + super.setOffendingToken(recognizer, recognizer.currentToken); + } + get ruleIndex() { + return this._ruleIndex; + } + get predicateIndex() { + return this._predicateIndex; + } + get predicate() { + return this._predicate; + } + static formatMessage(predicate, message) { + if (message) { + return message; + } + return `failed predicate: {${predicate}}?`; + } + }; + __decorate([ + Decorators_1.NotNull + ], FailedPredicateException$1, "formatMessage", null); + FailedPredicateException$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], FailedPredicateException$1); + FailedPredicateException.FailedPredicateException = FailedPredicateException$1; + + return FailedPredicateException; +} + +var InputMismatchException = {}; + +var hasRequiredInputMismatchException; + +function requireInputMismatchException () { + if (hasRequiredInputMismatchException) return InputMismatchException; + hasRequiredInputMismatchException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (InputMismatchException && InputMismatchException.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (InputMismatchException && InputMismatchException.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(InputMismatchException, "__esModule", { value: true }); + InputMismatchException.InputMismatchException = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:51.5187682-07:00 + const RecognitionException_1 = requireRecognitionException(); + const Decorators_1 = requireDecorators(); + /** This signifies any kind of mismatched input exceptions such as + * when the current input does not match the expected token. + */ + let InputMismatchException$1 = class InputMismatchException extends RecognitionException_1.RecognitionException { + constructor(recognizer, state, context) { + if (context === undefined) { + context = recognizer.context; + } + super(recognizer, recognizer.inputStream, context); + if (state !== undefined) { + this.setOffendingState(state); + } + this.setOffendingToken(recognizer, recognizer.currentToken); + } + }; + InputMismatchException$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], InputMismatchException$1); + InputMismatchException.InputMismatchException = InputMismatchException$1; + + return InputMismatchException; +} + +var IntervalSet = {}; + +var IntegerList = {}; + +var Arrays = {}; + +var hasRequiredArrays; + +function requireArrays () { + if (hasRequiredArrays) return Arrays; + hasRequiredArrays = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Arrays = void 0; + (function (Arrays) { + /** + * Searches the specified array of numbers for the specified value using the binary search algorithm. The array must + * be sorted prior to making this call. If it is not sorted, the results are unspecified. If the array contains + * multiple elements with the specified value, there is no guarantee which one will be found. + * + * @returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The + * insertion point is defined as the point at which the key would be inserted into the array: the index of the first + * element greater than the key, or array.length if all elements in the array are less than the specified key. Note + * that this guarantees that the return value will be >= 0 if and only if the key is found. + */ + function binarySearch(array, key, fromIndex, toIndex) { + return binarySearch0(array, fromIndex !== undefined ? fromIndex : 0, toIndex !== undefined ? toIndex : array.length, key); + } + Arrays.binarySearch = binarySearch; + function binarySearch0(array, fromIndex, toIndex, key) { + let low = fromIndex; + let high = toIndex - 1; + while (low <= high) { + let mid = (low + high) >>> 1; + let midVal = array[mid]; + if (midVal < key) { + low = mid + 1; + } + else if (midVal > key) { + high = mid - 1; + } + else { + // key found + return mid; + } + } + // key not found. + return -(low + 1); + } + function toString(array) { + let result = "["; + let first = true; + for (let element of array) { + if (first) { + first = false; + } + else { + result += ", "; + } + if (element === null) { + result += "null"; + } + else if (element === undefined) { + result += "undefined"; + } + else { + result += element; + } + } + result += "]"; + return result; + } + Arrays.toString = toString; + })(exports.Arrays || (exports.Arrays = {})); + + } (Arrays)); + return Arrays; +} + +var hasRequiredIntegerList; + +function requireIntegerList () { + if (hasRequiredIntegerList) return IntegerList; + hasRequiredIntegerList = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (IntegerList && IntegerList.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(IntegerList, "__esModule", { value: true }); + IntegerList.IntegerList = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:40.5099429-07:00 + const Arrays_1 = requireArrays(); + const Decorators_1 = requireDecorators(); + const EMPTY_DATA = new Int32Array(0); + const INITIAL_SIZE = 4; + const MAX_ARRAY_SIZE = (((1 << 31) >>> 0) - 1) - 8; + /** + * + * @author Sam Harwell + */ + let IntegerList$1 = class IntegerList { + constructor(arg) { + if (!arg) { + this._data = EMPTY_DATA; + this._size = 0; + } + else if (arg instanceof IntegerList) { + this._data = arg._data.slice(0); + this._size = arg._size; + } + else if (typeof arg === "number") { + if (arg === 0) { + this._data = EMPTY_DATA; + this._size = 0; + } + else { + this._data = new Int32Array(arg); + this._size = 0; + } + } + else { + // arg is Iterable + this._data = EMPTY_DATA; + this._size = 0; + for (let value of arg) { + this.add(value); + } + } + } + add(value) { + if (this._data.length === this._size) { + this.ensureCapacity(this._size + 1); + } + this._data[this._size] = value; + this._size++; + } + addAll(list) { + if (Array.isArray(list)) { + this.ensureCapacity(this._size + list.length); + this._data.subarray(this._size, this._size + list.length).set(list); + this._size += list.length; + } + else if (list instanceof IntegerList) { + this.ensureCapacity(this._size + list._size); + this._data.subarray(this._size, this._size + list.size).set(list._data); + this._size += list._size; + } + else { + // list is JavaCollection + this.ensureCapacity(this._size + list.size); + let current = 0; + for (let xi of list) { + this._data[this._size + current] = xi; + current++; + } + this._size += list.size; + } + } + get(index) { + if (index < 0 || index >= this._size) { + throw RangeError(); + } + return this._data[index]; + } + contains(value) { + for (let i = 0; i < this._size; i++) { + if (this._data[i] === value) { + return true; + } + } + return false; + } + set(index, value) { + if (index < 0 || index >= this._size) { + throw RangeError(); + } + let previous = this._data[index]; + this._data[index] = value; + return previous; + } + removeAt(index) { + let value = this.get(index); + this._data.copyWithin(index, index + 1, this._size); + this._data[this._size - 1] = 0; + this._size--; + return value; + } + removeRange(fromIndex, toIndex) { + if (fromIndex < 0 || toIndex < 0 || fromIndex > this._size || toIndex > this._size) { + throw RangeError(); + } + if (fromIndex > toIndex) { + throw RangeError(); + } + this._data.copyWithin(toIndex, fromIndex, this._size); + this._data.fill(0, this._size - (toIndex - fromIndex), this._size); + this._size -= (toIndex - fromIndex); + } + get isEmpty() { + return this._size === 0; + } + get size() { + return this._size; + } + trimToSize() { + if (this._data.length === this._size) { + return; + } + this._data = this._data.slice(0, this._size); + } + clear() { + this._data.fill(0, 0, this._size); + this._size = 0; + } + toArray() { + if (this._size === 0) { + return []; + } + return Array.from(this._data.subarray(0, this._size)); + } + sort() { + this._data.subarray(0, this._size).sort(); + } + /** + * Compares the specified object with this list for equality. Returns + * `true` if and only if the specified object is also an {@link IntegerList}, + * both lists have the same size, and all corresponding pairs of elements in + * the two lists are equal. In other words, two lists are defined to be + * equal if they contain the same elements in the same order. + * + * This implementation first checks if the specified object is this + * list. If so, it returns `true`; if not, it checks if the + * specified object is an {@link IntegerList}. If not, it returns `false`; + * if so, it checks the size of both lists. If the lists are not the same size, + * it returns `false`; otherwise it iterates over both lists, comparing + * corresponding pairs of elements. If any comparison returns `false`, + * this method returns `false`. + * + * @param o the object to be compared for equality with this list + * @returns `true` if the specified object is equal to this list + */ + equals(o) { + if (o === this) { + return true; + } + if (!(o instanceof IntegerList)) { + return false; + } + if (this._size !== o._size) { + return false; + } + for (let i = 0; i < this._size; i++) { + if (this._data[i] !== o._data[i]) { + return false; + } + } + return true; + } + /** + * Returns the hash code value for this list. + * + * This implementation uses exactly the code that is used to define the + * list hash function in the documentation for the {@link List#hashCode} + * method. + * + * @returns the hash code value for this list + */ + hashCode() { + let hashCode = 1; + for (let i = 0; i < this._size; i++) { + hashCode = 31 * hashCode + this._data[i]; + } + return hashCode; + } + /** + * Returns a string representation of this list. + */ + toString() { + return this._data.toString(); + } + binarySearch(key, fromIndex, toIndex) { + if (fromIndex === undefined) { + fromIndex = 0; + } + if (toIndex === undefined) { + toIndex = this._size; + } + if (fromIndex < 0 || toIndex < 0 || fromIndex > this._size || toIndex > this._size) { + throw new RangeError(); + } + if (fromIndex > toIndex) { + throw new RangeError(); + } + return Arrays_1.Arrays.binarySearch(this._data, key, fromIndex, toIndex); + } + ensureCapacity(capacity) { + if (capacity < 0 || capacity > MAX_ARRAY_SIZE) { + throw new RangeError(); + } + let newLength; + if (this._data.length === 0) { + newLength = INITIAL_SIZE; + } + else { + newLength = this._data.length; + } + while (newLength < capacity) { + newLength = newLength * 2; + if (newLength < 0 || newLength > MAX_ARRAY_SIZE) { + newLength = MAX_ARRAY_SIZE; + } + } + let tmp = new Int32Array(newLength); + tmp.set(this._data); + this._data = tmp; + } + /** Convert the list to a UTF-16 encoded char array. If all values are less + * than the 0xFFFF 16-bit code point limit then this is just a char array + * of 16-bit char as usual. For values in the supplementary range, encode + * them as two UTF-16 code units. + */ + toCharArray() { + // Optimize for the common case (all data values are < 0xFFFF) to avoid an extra scan + let resultArray = new Uint16Array(this._size); + let resultIdx = 0; + let calculatedPreciseResultSize = false; + for (let i = 0; i < this._size; i++) { + let codePoint = this._data[i]; + if (codePoint >= 0 && codePoint < 0x10000) { + resultArray[resultIdx] = codePoint; + resultIdx++; + continue; + } + // Calculate the precise result size if we encounter a code point > 0xFFFF + if (!calculatedPreciseResultSize) { + let newResultArray = new Uint16Array(this.charArraySize()); + newResultArray.set(resultArray, 0); + resultArray = newResultArray; + calculatedPreciseResultSize = true; + } + // This will throw RangeError if the code point is not a valid Unicode code point + let pair = String.fromCodePoint(codePoint); + resultArray[resultIdx] = pair.charCodeAt(0); + resultArray[resultIdx + 1] = pair.charCodeAt(1); + resultIdx += 2; + } + return resultArray; + } + charArraySize() { + let result = 0; + for (let i = 0; i < this._size; i++) { + result += this._data[i] >= 0x10000 ? 2 : 1; + } + return result; + } + }; + __decorate([ + Decorators_1.NotNull + ], IntegerList$1.prototype, "_data", void 0); + __decorate([ + Decorators_1.Override + ], IntegerList$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], IntegerList$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], IntegerList$1.prototype, "toString", null); + IntegerList.IntegerList = IntegerList$1; + + return IntegerList; +} + +var Interval = {}; + +var hasRequiredInterval; + +function requireInterval () { + if (hasRequiredInterval) return Interval; + hasRequiredInterval = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Interval && Interval.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(Interval, "__esModule", { value: true }); + Interval.Interval = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:40.7402214-07:00 + const Decorators_1 = requireDecorators(); + const INTERVAL_POOL_MAX_VALUE = 1000; + /** An immutable inclusive interval a..b */ + let Interval$1 = class Interval { + /** + * @param a The start of the interval + * @param b The end of the interval (inclusive) + */ + constructor(a, b) { + this.a = a; + this.b = b; + } + static get INVALID() { + return Interval._INVALID; + } + /** Interval objects are used readonly so share all with the + * same single value a==b up to some max size. Use an array as a perfect hash. + * Return shared object for 0..INTERVAL_POOL_MAX_VALUE or a new + * Interval object with a..a in it. On Java.g4, 218623 IntervalSets + * have a..a (set with 1 element). + */ + static of(a, b) { + // cache just a..a + if (a !== b || a < 0 || a > INTERVAL_POOL_MAX_VALUE) { + return new Interval(a, b); + } + if (Interval.cache[a] == null) { + Interval.cache[a] = new Interval(a, a); + } + return Interval.cache[a]; + } + /** return number of elements between a and b inclusively. x..x is length 1. + * if b < a, then length is 0. 9..10 has length 2. + */ + get length() { + if (this.b < this.a) { + return 0; + } + return this.b - this.a + 1; + } + equals(o) { + if (o === this) { + return true; + } + else if (!(o instanceof Interval)) { + return false; + } + return this.a === o.a && this.b === o.b; + } + hashCode() { + let hash = 23; + hash = hash * 31 + this.a; + hash = hash * 31 + this.b; + return hash; + } + /** Does this start completely before other? Disjoint */ + startsBeforeDisjoint(other) { + return this.a < other.a && this.b < other.a; + } + /** Does this start at or before other? Nondisjoint */ + startsBeforeNonDisjoint(other) { + return this.a <= other.a && this.b >= other.a; + } + /** Does this.a start after other.b? May or may not be disjoint */ + startsAfter(other) { + return this.a > other.a; + } + /** Does this start completely after other? Disjoint */ + startsAfterDisjoint(other) { + return this.a > other.b; + } + /** Does this start after other? NonDisjoint */ + startsAfterNonDisjoint(other) { + return this.a > other.a && this.a <= other.b; // this.b>=other.b implied + } + /** Are both ranges disjoint? I.e., no overlap? */ + disjoint(other) { + return this.startsBeforeDisjoint(other) || this.startsAfterDisjoint(other); + } + /** Are two intervals adjacent such as 0..41 and 42..42? */ + adjacent(other) { + return this.a === other.b + 1 || this.b === other.a - 1; + } + properlyContains(other) { + return other.a >= this.a && other.b <= this.b; + } + /** Return the interval computed from combining this and other */ + union(other) { + return Interval.of(Math.min(this.a, other.a), Math.max(this.b, other.b)); + } + /** Return the interval in common between this and o */ + intersection(other) { + return Interval.of(Math.max(this.a, other.a), Math.min(this.b, other.b)); + } + /** Return the interval with elements from `this` not in `other`; + * `other` must not be totally enclosed (properly contained) + * within `this`, which would result in two disjoint intervals + * instead of the single one returned by this method. + */ + differenceNotProperlyContained(other) { + let diff; + if (other.startsBeforeNonDisjoint(this)) { + // other.a to left of this.a (or same) + diff = Interval.of(Math.max(this.a, other.b + 1), this.b); + } + else if (other.startsAfterNonDisjoint(this)) { + // other.a to right of this.a + diff = Interval.of(this.a, other.a - 1); + } + return diff; + } + toString() { + return this.a + ".." + this.b; + } + }; + Interval$1._INVALID = new Interval$1(-1, -2); + Interval$1.cache = new Array(INTERVAL_POOL_MAX_VALUE + 1); + __decorate([ + Decorators_1.Override + ], Interval$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], Interval$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], Interval$1.prototype, "toString", null); + Interval.Interval = Interval$1; + + return Interval; +} + +var Lexer = {}; + +var CommonTokenFactory = {}; + +var CommonToken = {}; + +var Token = {}; + +var hasRequiredToken; + +function requireToken () { + if (hasRequiredToken) return Token; + hasRequiredToken = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Token = void 0; + const IntStream_1 = requireIntStream(); + (function (Token) { + Token.INVALID_TYPE = 0; + /** During lookahead operations, this "token" signifies we hit rule end ATN state + * and did not follow it despite needing to. + */ + Token.EPSILON = -2; + Token.MIN_USER_TOKEN_TYPE = 1; + Token.EOF = IntStream_1.IntStream.EOF; + /** All tokens go to the parser (unless skip() is called in that rule) + * on a particular "channel". The parser tunes to a particular channel + * so that whitespace etc... can go to the parser on a "hidden" channel. + */ + Token.DEFAULT_CHANNEL = 0; + /** Anything on different channel than DEFAULT_CHANNEL is not parsed + * by parser. + */ + Token.HIDDEN_CHANNEL = 1; + /** + * This is the minimum constant value which can be assigned to a + * user-defined token channel. + * + * The non-negative numbers less than {@link #MIN_USER_CHANNEL_VALUE} are + * assigned to the predefined channels {@link #DEFAULT_CHANNEL} and + * {@link #HIDDEN_CHANNEL}. + * + * @see `Token.channel` + */ + Token.MIN_USER_CHANNEL_VALUE = 2; + })(exports.Token || (exports.Token = {})); + + } (Token)); + return Token; +} + +var hasRequiredCommonToken; + +function requireCommonToken () { + if (hasRequiredCommonToken) return CommonToken; + hasRequiredCommonToken = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (CommonToken && CommonToken.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (CommonToken && CommonToken.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(CommonToken, "__esModule", { value: true }); + CommonToken.CommonToken = void 0; + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + let CommonToken$1 = class CommonToken { + constructor(type, text, source = CommonToken.EMPTY_SOURCE, channel = Token_1.Token.DEFAULT_CHANNEL, start = 0, stop = 0) { + /** + * This is the backing field for {@link #getLine} and {@link #setLine}. + */ + this._line = 0; + /** + * This is the backing field for {@link #getCharPositionInLine} and + * {@link #setCharPositionInLine}. + */ + this._charPositionInLine = -1; // set to invalid position + /** + * This is the backing field for {@link #getChannel} and + * {@link #setChannel}. + */ + this._channel = Token_1.Token.DEFAULT_CHANNEL; + /** + * This is the backing field for `tokenIndex`. + */ + this.index = -1; + this._text = text; + this._type = type; + this.source = source; + this._channel = channel; + this.start = start; + this.stop = stop; + if (source.source != null) { + this._line = source.source.line; + this._charPositionInLine = source.source.charPositionInLine; + } + } + /** + * Constructs a new {@link CommonToken} as a copy of another {@link Token}. + * + * If `oldToken` is also a {@link CommonToken} instance, the newly + * constructed token will share a reference to the {@link #text} field and + * the {@link Tuple2} stored in {@link #source}. Otherwise, {@link #text} will + * be assigned the result of calling {@link #getText}, and {@link #source} + * will be constructed from the result of {@link Token#getTokenSource} and + * {@link Token#getInputStream}. + * + * @param oldToken The token to copy. + */ + static fromToken(oldToken) { + let result = new CommonToken(oldToken.type, undefined, CommonToken.EMPTY_SOURCE, oldToken.channel, oldToken.startIndex, oldToken.stopIndex); + result._line = oldToken.line; + result.index = oldToken.tokenIndex; + result._charPositionInLine = oldToken.charPositionInLine; + if (oldToken instanceof CommonToken) { + result._text = oldToken._text; + result.source = oldToken.source; + } + else { + result._text = oldToken.text; + result.source = { source: oldToken.tokenSource, stream: oldToken.inputStream }; + } + return result; + } + get type() { + return this._type; + } + // @Override + set type(type) { + this._type = type; + } + get line() { + return this._line; + } + // @Override + set line(line) { + this._line = line; + } + get text() { + if (this._text != null) { + return this._text; + } + let input = this.inputStream; + if (input == null) { + return undefined; + } + let n = input.size; + if (this.start < n && this.stop < n) { + return input.getText(Interval_1.Interval.of(this.start, this.stop)); + } + else { + return ""; + } + } + /** + * Explicitly set the text for this token. If {code text} is not + * `undefined`, then {@link #getText} will return this value rather than + * extracting the text from the input. + * + * @param text The explicit text of the token, or `undefined` if the text + * should be obtained from the input along with the start and stop indexes + * of the token. + */ + // @Override + set text(text) { + this._text = text; + } + get charPositionInLine() { + return this._charPositionInLine; + } + // @Override + set charPositionInLine(charPositionInLine) { + this._charPositionInLine = charPositionInLine; + } + get channel() { + return this._channel; + } + // @Override + set channel(channel) { + this._channel = channel; + } + get startIndex() { + return this.start; + } + set startIndex(start) { + this.start = start; + } + get stopIndex() { + return this.stop; + } + set stopIndex(stop) { + this.stop = stop; + } + get tokenIndex() { + return this.index; + } + // @Override + set tokenIndex(index) { + this.index = index; + } + get tokenSource() { + return this.source.source; + } + get inputStream() { + return this.source.stream; + } + toString(recognizer) { + let channelStr = ""; + if (this._channel > 0) { + channelStr = ",channel=" + this._channel; + } + let txt = this.text; + if (txt != null) { + txt = txt.replace(/\n/g, "\\n"); + txt = txt.replace(/\r/g, "\\r"); + txt = txt.replace(/\t/g, "\\t"); + } + else { + txt = ""; + } + let typeString = String(this._type); + if (recognizer) { + typeString = recognizer.vocabulary.getDisplayName(this._type); + } + return "[@" + this.tokenIndex + "," + this.start + ":" + this.stop + "='" + txt + "',<" + typeString + ">" + channelStr + "," + this._line + ":" + this.charPositionInLine + "]"; + } + }; + /** + * An empty {@link Tuple2} which is used as the default value of + * {@link #source} for tokens that do not have a source. + */ + CommonToken$1.EMPTY_SOURCE = { source: undefined, stream: undefined }; + __decorate([ + Decorators_1.NotNull + ], CommonToken$1.prototype, "source", void 0); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "type", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "line", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "charPositionInLine", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "channel", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "startIndex", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "stopIndex", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "tokenIndex", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "tokenSource", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.Override + ], CommonToken$1.prototype, "toString", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], CommonToken$1, "fromToken", null); + CommonToken$1 = __decorate([ + __param(2, Decorators_1.NotNull) + ], CommonToken$1); + CommonToken.CommonToken = CommonToken$1; + + return CommonToken; +} + +var hasRequiredCommonTokenFactory; + +function requireCommonTokenFactory () { + if (hasRequiredCommonTokenFactory) return CommonTokenFactory; + hasRequiredCommonTokenFactory = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (CommonTokenFactory && CommonTokenFactory.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CommonTokenFactory = void 0; + const CommonToken_1 = requireCommonToken(); + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + /** + * This default implementation of {@link TokenFactory} creates + * {@link CommonToken} objects. + */ + let CommonTokenFactory$1 = class CommonTokenFactory { + /** + * Constructs a {@link CommonTokenFactory} with the specified value for + * {@link #copyText}. + * + * When `copyText` is `false`, the {@link #DEFAULT} instance + * should be used instead of constructing a new instance. + * + * @param copyText The value for {@link #copyText}. + */ + constructor(copyText = false) { + this.copyText = copyText; + } + create(source, type, text, channel, start, stop, line, charPositionInLine) { + let t = new CommonToken_1.CommonToken(type, text, source, channel, start, stop); + t.line = line; + t.charPositionInLine = charPositionInLine; + if (text == null && this.copyText && source.stream != null) { + t.text = source.stream.getText(Interval_1.Interval.of(start, stop)); + } + return t; + } + createSimple(type, text) { + return new CommonToken_1.CommonToken(type, text); + } + }; + __decorate([ + Decorators_1.Override + ], CommonTokenFactory$1.prototype, "create", null); + __decorate([ + Decorators_1.Override + ], CommonTokenFactory$1.prototype, "createSimple", null); + exports.CommonTokenFactory = CommonTokenFactory$1; + (function (CommonTokenFactory) { + /** + * The default {@link CommonTokenFactory} instance. + * + * This token factory does not explicitly copy token text when constructing + * tokens. + */ + CommonTokenFactory.DEFAULT = new CommonTokenFactory(); + })(CommonTokenFactory$1 = exports.CommonTokenFactory || (exports.CommonTokenFactory = {})); + + } (CommonTokenFactory)); + return CommonTokenFactory; +} + +var IntegerStack = {}; + +var hasRequiredIntegerStack; + +function requireIntegerStack () { + if (hasRequiredIntegerStack) return IntegerStack; + hasRequiredIntegerStack = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(IntegerStack, "__esModule", { value: true }); + IntegerStack.IntegerStack = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:40.6647101-07:00 + const IntegerList_1 = requireIntegerList(); + /** + * + * @author Sam Harwell + */ + let IntegerStack$1 = class IntegerStack extends IntegerList_1.IntegerList { + constructor(arg) { + super(arg); + } + push(value) { + this.add(value); + } + pop() { + return this.removeAt(this.size - 1); + } + peek() { + return this.get(this.size - 1); + } + }; + IntegerStack.IntegerStack = IntegerStack$1; + + return IntegerStack; +} + +var LexerATNSimulator = {}; + +var AcceptStateInfo = {}; + +var hasRequiredAcceptStateInfo; + +function requireAcceptStateInfo () { + if (hasRequiredAcceptStateInfo) return AcceptStateInfo; + hasRequiredAcceptStateInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(AcceptStateInfo, "__esModule", { value: true }); + AcceptStateInfo.AcceptStateInfo = void 0; + /** + * Stores information about a {@link DFAState} which is an accept state under + * some condition. Certain settings, such as + * {@link ParserATNSimulator#getPredictionMode()}, may be used in addition to + * this information to determine whether or not a particular state is an accept + * state. + * + * @author Sam Harwell + */ + let AcceptStateInfo$1 = class AcceptStateInfo { + constructor(prediction, lexerActionExecutor) { + this._prediction = prediction; + this._lexerActionExecutor = lexerActionExecutor; + } + /** + * Gets the prediction made by this accept state. Note that this value + * assumes the predicates, if any, in the {@link DFAState} evaluate to + * `true`. If predicate evaluation is enabled, the final prediction of + * the accept state will be determined by the result of predicate + * evaluation. + */ + get prediction() { + return this._prediction; + } + /** + * Gets the {@link LexerActionExecutor} which can be used to execute actions + * and/or commands after the lexer matches a token. + */ + get lexerActionExecutor() { + return this._lexerActionExecutor; + } + }; + AcceptStateInfo.AcceptStateInfo = AcceptStateInfo$1; + + return AcceptStateInfo; +} + +var ATN = {}; + +var Array2DHashMap = {}; + +var hasRequiredArray2DHashMap; + +function requireArray2DHashMap () { + if (hasRequiredArray2DHashMap) return Array2DHashMap; + hasRequiredArray2DHashMap = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Array2DHashMap, "__esModule", { value: true }); + Array2DHashMap.Array2DHashMap = void 0; + const Array2DHashSet_1 = requireArray2DHashSet(); + class MapKeyEqualityComparator { + constructor(keyComparator) { + this.keyComparator = keyComparator; + } + hashCode(obj) { + return this.keyComparator.hashCode(obj.key); + } + equals(a, b) { + return this.keyComparator.equals(a.key, b.key); + } + } + let Array2DHashMap$1 = class Array2DHashMap { + constructor(keyComparer) { + if (keyComparer instanceof Array2DHashMap) { + this.backingStore = new Array2DHashSet_1.Array2DHashSet(keyComparer.backingStore); + } + else { + this.backingStore = new Array2DHashSet_1.Array2DHashSet(new MapKeyEqualityComparator(keyComparer)); + } + } + clear() { + this.backingStore.clear(); + } + containsKey(key) { + return this.backingStore.contains({ key }); + } + get(key) { + let bucket = this.backingStore.get({ key }); + if (!bucket) { + return undefined; + } + return bucket.value; + } + get isEmpty() { + return this.backingStore.isEmpty; + } + put(key, value) { + let element = this.backingStore.get({ key, value }); + let result; + if (!element) { + this.backingStore.add({ key, value }); + } + else { + result = element.value; + element.value = value; + } + return result; + } + putIfAbsent(key, value) { + let element = this.backingStore.get({ key, value }); + let result; + if (!element) { + this.backingStore.add({ key, value }); + } + else { + result = element.value; + } + return result; + } + get size() { + return this.backingStore.size; + } + hashCode() { + return this.backingStore.hashCode(); + } + equals(o) { + if (!(o instanceof Array2DHashMap)) { + return false; + } + return this.backingStore.equals(o.backingStore); + } + }; + Array2DHashMap.Array2DHashMap = Array2DHashMap$1; + + return Array2DHashMap; +} + +var DFA = {}; + +var ATNConfigSet = {}; + +var ATNConfig = {}; + +var DecisionState = {}; + +var hasRequiredDecisionState; + +function requireDecisionState () { + if (hasRequiredDecisionState) return DecisionState; + hasRequiredDecisionState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(DecisionState, "__esModule", { value: true }); + DecisionState.DecisionState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:28.4381103-07:00 + const ATNState_1 = requireATNState(); + let DecisionState$1 = class DecisionState extends ATNState_1.ATNState { + constructor() { + super(...arguments); + this.decision = -1; + this.nonGreedy = false; + this.sll = false; + } + }; + DecisionState.DecisionState = DecisionState$1; + + return DecisionState; +} + +var PredictionContext = {}; + +var PredictionContextCache = {}; + +var hasRequiredPredictionContextCache; + +function requirePredictionContextCache () { + if (hasRequiredPredictionContextCache) return PredictionContextCache; + hasRequiredPredictionContextCache = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PredictionContextCache && PredictionContextCache.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PredictionContextCache = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.6390614-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const PredictionContext_1 = requirePredictionContext(); + const assert = require$$0$9; + /** Used to cache {@link PredictionContext} objects. Its used for the shared + * context cash associated with contexts in DFA states. This cache + * can be used for both lexers and parsers. + * + * @author Sam Harwell + */ + let PredictionContextCache$1 = class PredictionContextCache { + constructor(enableCache = true) { + this.contexts = new Array2DHashMap_1.Array2DHashMap(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + this.childContexts = new Array2DHashMap_1.Array2DHashMap(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + this.joinContexts = new Array2DHashMap_1.Array2DHashMap(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + this.enableCache = enableCache; + } + getAsCached(context) { + if (!this.enableCache) { + return context; + } + let result = this.contexts.get(context); + if (!result) { + result = context; + this.contexts.put(context, context); + } + return result; + } + getChild(context, invokingState) { + if (!this.enableCache) { + return context.getChild(invokingState); + } + let operands = new PredictionContextCache.PredictionContextAndInt(context, invokingState); + let result = this.childContexts.get(operands); + if (!result) { + result = context.getChild(invokingState); + result = this.getAsCached(result); + this.childContexts.put(operands, result); + } + return result; + } + join(x, y) { + if (!this.enableCache) { + return PredictionContext_1.PredictionContext.join(x, y, this); + } + let operands = new PredictionContextCache.IdentityCommutativePredictionContextOperands(x, y); + let result = this.joinContexts.get(operands); + if (result) { + return result; + } + result = PredictionContext_1.PredictionContext.join(x, y, this); + result = this.getAsCached(result); + this.joinContexts.put(operands, result); + return result; + } + }; + exports.PredictionContextCache = PredictionContextCache$1; + PredictionContextCache$1.UNCACHED = new PredictionContextCache$1(false); + (function (PredictionContextCache) { + class PredictionContextAndInt { + constructor(obj, value) { + this.obj = obj; + this.value = value; + } + equals(obj) { + if (!(obj instanceof PredictionContextAndInt)) { + return false; + } + else if (obj === this) { + return true; + } + let other = obj; + return this.value === other.value + && (this.obj === other.obj || (this.obj != null && this.obj.equals(other.obj))); + } + hashCode() { + let hashCode = 5; + hashCode = 7 * hashCode + (this.obj != null ? this.obj.hashCode() : 0); + hashCode = 7 * hashCode + this.value; + return hashCode; + } + } + __decorate([ + Decorators_1.Override + ], PredictionContextAndInt.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], PredictionContextAndInt.prototype, "hashCode", null); + PredictionContextCache.PredictionContextAndInt = PredictionContextAndInt; + class IdentityCommutativePredictionContextOperands { + constructor(x, y) { + assert(x != null); + assert(y != null); + this._x = x; + this._y = y; + } + get x() { + return this._x; + } + get y() { + return this._y; + } + equals(o) { + if (!(o instanceof IdentityCommutativePredictionContextOperands)) { + return false; + } + else if (this === o) { + return true; + } + let other = o; + return (this._x === other._x && this._y === other._y) || (this._x === other._y && this._y === other._x); + } + hashCode() { + return this._x.hashCode() ^ this._y.hashCode(); + } + } + __decorate([ + Decorators_1.Override + ], IdentityCommutativePredictionContextOperands.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], IdentityCommutativePredictionContextOperands.prototype, "hashCode", null); + PredictionContextCache.IdentityCommutativePredictionContextOperands = IdentityCommutativePredictionContextOperands; + })(PredictionContextCache$1 = exports.PredictionContextCache || (exports.PredictionContextCache = {})); + + } (PredictionContextCache)); + return PredictionContextCache; +} + +var hasRequiredPredictionContext; + +function requirePredictionContext () { + if (hasRequiredPredictionContext) return PredictionContext; + hasRequiredPredictionContext = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PredictionContext && PredictionContext.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (PredictionContext && PredictionContext.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SingletonPredictionContext = exports.PredictionContext = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.3812636-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const Array2DHashSet_1 = requireArray2DHashSet(); + const Arrays_1 = requireArrays(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const PredictionContextCache_1 = requirePredictionContextCache(); + const assert = require$$0$9; + const INITIAL_HASH = 1; + let PredictionContext$1 = class PredictionContext { + constructor(cachedHashCode) { + this.cachedHashCode = cachedHashCode; + } + static calculateEmptyHashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(INITIAL_HASH); + hash = MurmurHash_1.MurmurHash.finish(hash, 0); + return hash; + } + static calculateSingleHashCode(parent, returnState) { + let hash = MurmurHash_1.MurmurHash.initialize(INITIAL_HASH); + hash = MurmurHash_1.MurmurHash.update(hash, parent); + hash = MurmurHash_1.MurmurHash.update(hash, returnState); + hash = MurmurHash_1.MurmurHash.finish(hash, 2); + return hash; + } + static calculateHashCode(parents, returnStates) { + let hash = MurmurHash_1.MurmurHash.initialize(INITIAL_HASH); + for (let parent of parents) { + hash = MurmurHash_1.MurmurHash.update(hash, parent); + } + for (let returnState of returnStates) { + hash = MurmurHash_1.MurmurHash.update(hash, returnState); + } + hash = MurmurHash_1.MurmurHash.finish(hash, 2 * parents.length); + return hash; + } + static fromRuleContext(atn, outerContext, fullContext = true) { + if (outerContext.isEmpty) { + return fullContext ? PredictionContext.EMPTY_FULL : PredictionContext.EMPTY_LOCAL; + } + let parent; + if (outerContext._parent) { + parent = PredictionContext.fromRuleContext(atn, outerContext._parent, fullContext); + } + else { + parent = fullContext ? PredictionContext.EMPTY_FULL : PredictionContext.EMPTY_LOCAL; + } + let state = atn.states[outerContext.invokingState]; + let transition = state.transition(0); + return parent.getChild(transition.followState.stateNumber); + } + static addEmptyContext(context) { + return context.addEmptyContext(); + } + static removeEmptyContext(context) { + return context.removeEmptyContext(); + } + static join(context0, context1, contextCache = PredictionContextCache_1.PredictionContextCache.UNCACHED) { + if (context0 === context1) { + return context0; + } + if (context0.isEmpty) { + return PredictionContext.isEmptyLocal(context0) ? context0 : PredictionContext.addEmptyContext(context1); + } + else if (context1.isEmpty) { + return PredictionContext.isEmptyLocal(context1) ? context1 : PredictionContext.addEmptyContext(context0); + } + let context0size = context0.size; + let context1size = context1.size; + if (context0size === 1 && context1size === 1 && context0.getReturnState(0) === context1.getReturnState(0)) { + let merged = contextCache.join(context0.getParent(0), context1.getParent(0)); + if (merged === context0.getParent(0)) { + return context0; + } + else if (merged === context1.getParent(0)) { + return context1; + } + else { + return merged.getChild(context0.getReturnState(0)); + } + } + let count = 0; + let parentsList = new Array(context0size + context1size); + let returnStatesList = new Array(parentsList.length); + let leftIndex = 0; + let rightIndex = 0; + let canReturnLeft = true; + let canReturnRight = true; + while (leftIndex < context0size && rightIndex < context1size) { + if (context0.getReturnState(leftIndex) === context1.getReturnState(rightIndex)) { + parentsList[count] = contextCache.join(context0.getParent(leftIndex), context1.getParent(rightIndex)); + returnStatesList[count] = context0.getReturnState(leftIndex); + canReturnLeft = canReturnLeft && parentsList[count] === context0.getParent(leftIndex); + canReturnRight = canReturnRight && parentsList[count] === context1.getParent(rightIndex); + leftIndex++; + rightIndex++; + } + else if (context0.getReturnState(leftIndex) < context1.getReturnState(rightIndex)) { + parentsList[count] = context0.getParent(leftIndex); + returnStatesList[count] = context0.getReturnState(leftIndex); + canReturnRight = false; + leftIndex++; + } + else { + assert(context1.getReturnState(rightIndex) < context0.getReturnState(leftIndex)); + parentsList[count] = context1.getParent(rightIndex); + returnStatesList[count] = context1.getReturnState(rightIndex); + canReturnLeft = false; + rightIndex++; + } + count++; + } + while (leftIndex < context0size) { + parentsList[count] = context0.getParent(leftIndex); + returnStatesList[count] = context0.getReturnState(leftIndex); + leftIndex++; + canReturnRight = false; + count++; + } + while (rightIndex < context1size) { + parentsList[count] = context1.getParent(rightIndex); + returnStatesList[count] = context1.getReturnState(rightIndex); + rightIndex++; + canReturnLeft = false; + count++; + } + if (canReturnLeft) { + return context0; + } + else if (canReturnRight) { + return context1; + } + if (count < parentsList.length) { + parentsList = parentsList.slice(0, count); + returnStatesList = returnStatesList.slice(0, count); + } + if (parentsList.length === 0) { + // if one of them was EMPTY_LOCAL, it would be empty and handled at the beginning of the method + return PredictionContext.EMPTY_FULL; + } + else if (parentsList.length === 1) { + return new SingletonPredictionContext(parentsList[0], returnStatesList[0]); + } + else { + return new ArrayPredictionContext(parentsList, returnStatesList); + } + } + static isEmptyLocal(context) { + return context === PredictionContext.EMPTY_LOCAL; + } + static getCachedContext(context, contextCache, visited) { + if (context.isEmpty) { + return context; + } + let existing = visited.get(context); + if (existing) { + return existing; + } + existing = contextCache.get(context); + if (existing) { + visited.put(context, existing); + return existing; + } + let changed = false; + let parents = new Array(context.size); + for (let i = 0; i < parents.length; i++) { + let parent = PredictionContext.getCachedContext(context.getParent(i), contextCache, visited); + if (changed || parent !== context.getParent(i)) { + if (!changed) { + parents = new Array(context.size); + for (let j = 0; j < context.size; j++) { + parents[j] = context.getParent(j); + } + changed = true; + } + parents[i] = parent; + } + } + if (!changed) { + existing = contextCache.putIfAbsent(context, context); + visited.put(context, existing != null ? existing : context); + return context; + } + // We know parents.length>0 because context.isEmpty is checked at the beginning of the method. + let updated; + if (parents.length === 1) { + updated = new SingletonPredictionContext(parents[0], context.getReturnState(0)); + } + else { + let returnStates = new Array(context.size); + for (let i = 0; i < context.size; i++) { + returnStates[i] = context.getReturnState(i); + } + updated = new ArrayPredictionContext(parents, returnStates, context.hashCode()); + } + existing = contextCache.putIfAbsent(updated, updated); + visited.put(updated, existing || updated); + visited.put(context, existing || updated); + return updated; + } + appendSingleContext(returnContext, contextCache) { + return this.appendContext(PredictionContext.EMPTY_FULL.getChild(returnContext), contextCache); + } + getChild(returnState) { + return new SingletonPredictionContext(this, returnState); + } + hashCode() { + return this.cachedHashCode; + } + toStrings(recognizer, currentState, stop = PredictionContext.EMPTY_FULL) { + let result = []; + outer: for (let perm = 0;; perm++) { + let offset = 0; + let last = true; + let p = this; + let stateNumber = currentState; + let localBuffer = ""; + localBuffer += "["; + while (!p.isEmpty && p !== stop) { + let index = 0; + if (p.size > 0) { + let bits = 1; + while (((1 << bits) >>> 0) < p.size) { + bits++; + } + let mask = ((1 << bits) >>> 0) - 1; + index = (perm >> offset) & mask; + last = last && index >= p.size - 1; + if (index >= p.size) { + continue outer; + } + offset += bits; + } + if (recognizer) { + if (localBuffer.length > 1) { + // first char is '[', if more than that this isn't the first rule + localBuffer += " "; + } + let atn = recognizer.atn; + let s = atn.states[stateNumber]; + let ruleName = recognizer.ruleNames[s.ruleIndex]; + localBuffer += ruleName; + } + else if (p.getReturnState(index) !== PredictionContext.EMPTY_FULL_STATE_KEY) { + if (!p.isEmpty) { + if (localBuffer.length > 1) { + // first char is '[', if more than that this isn't the first rule + localBuffer += " "; + } + localBuffer += p.getReturnState(index); + } + } + stateNumber = p.getReturnState(index); + p = p.getParent(index); + } + localBuffer += "]"; + result.push(localBuffer); + if (last) { + break; + } + } + return result; + } + }; + __decorate([ + Decorators_1.Override + ], PredictionContext$1.prototype, "hashCode", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], PredictionContext$1, "join", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], PredictionContext$1, "getCachedContext", null); + exports.PredictionContext = PredictionContext$1; + class EmptyPredictionContext extends PredictionContext$1 { + constructor(fullContext) { + super(PredictionContext$1.calculateEmptyHashCode()); + this.fullContext = fullContext; + } + get isFullContext() { + return this.fullContext; + } + addEmptyContext() { + return this; + } + removeEmptyContext() { + throw new Error("Cannot remove the empty context from itself."); + } + getParent(index) { + throw new Error("index out of bounds"); + } + getReturnState(index) { + throw new Error("index out of bounds"); + } + findReturnState(returnState) { + return -1; + } + get size() { + return 0; + } + appendSingleContext(returnContext, contextCache) { + return contextCache.getChild(this, returnContext); + } + appendContext(suffix, contextCache) { + return suffix; + } + get isEmpty() { + return true; + } + get hasEmpty() { + return true; + } + equals(o) { + return this === o; + } + toStrings(recognizer, currentState, stop) { + return ["[]"]; + } + } + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "addEmptyContext", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "removeEmptyContext", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "getParent", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "getReturnState", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "findReturnState", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "appendSingleContext", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "appendContext", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "isEmpty", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "hasEmpty", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], EmptyPredictionContext.prototype, "toStrings", null); + let ArrayPredictionContext = class ArrayPredictionContext extends PredictionContext$1 { + constructor(parents, returnStates, hashCode) { + super(hashCode || PredictionContext$1.calculateHashCode(parents, returnStates)); + assert(parents.length === returnStates.length); + assert(returnStates.length > 1 || returnStates[0] !== PredictionContext$1.EMPTY_FULL_STATE_KEY, "Should be using PredictionContext.EMPTY instead."); + this.parents = parents; + this.returnStates = returnStates; + } + getParent(index) { + return this.parents[index]; + } + getReturnState(index) { + return this.returnStates[index]; + } + findReturnState(returnState) { + return Arrays_1.Arrays.binarySearch(this.returnStates, returnState); + } + get size() { + return this.returnStates.length; + } + get isEmpty() { + return false; + } + get hasEmpty() { + return this.returnStates[this.returnStates.length - 1] === PredictionContext$1.EMPTY_FULL_STATE_KEY; + } + addEmptyContext() { + if (this.hasEmpty) { + return this; + } + let parents2 = this.parents.slice(0); + let returnStates2 = this.returnStates.slice(0); + parents2.push(PredictionContext$1.EMPTY_FULL); + returnStates2.push(PredictionContext$1.EMPTY_FULL_STATE_KEY); + return new ArrayPredictionContext(parents2, returnStates2); + } + removeEmptyContext() { + if (!this.hasEmpty) { + return this; + } + if (this.returnStates.length === 2) { + return new SingletonPredictionContext(this.parents[0], this.returnStates[0]); + } + else { + let parents2 = this.parents.slice(0, this.parents.length - 1); + let returnStates2 = this.returnStates.slice(0, this.returnStates.length - 1); + return new ArrayPredictionContext(parents2, returnStates2); + } + } + appendContext(suffix, contextCache) { + return ArrayPredictionContext.appendContextImpl(this, suffix, new PredictionContext$1.IdentityHashMap()); + } + static appendContextImpl(context, suffix, visited) { + if (suffix.isEmpty) { + if (PredictionContext$1.isEmptyLocal(suffix)) { + if (context.hasEmpty) { + return PredictionContext$1.EMPTY_LOCAL; + } + throw new Error("what to do here?"); + } + return context; + } + if (suffix.size !== 1) { + throw new Error("Appending a tree suffix is not yet supported."); + } + let result = visited.get(context); + if (!result) { + if (context.isEmpty) { + result = suffix; + } + else { + let parentCount = context.size; + if (context.hasEmpty) { + parentCount--; + } + let updatedParents = new Array(parentCount); + let updatedReturnStates = new Array(parentCount); + for (let i = 0; i < parentCount; i++) { + updatedReturnStates[i] = context.getReturnState(i); + } + for (let i = 0; i < parentCount; i++) { + updatedParents[i] = ArrayPredictionContext.appendContextImpl(context.getParent(i), suffix, visited); + } + if (updatedParents.length === 1) { + result = new SingletonPredictionContext(updatedParents[0], updatedReturnStates[0]); + } + else { + assert(updatedParents.length > 1); + result = new ArrayPredictionContext(updatedParents, updatedReturnStates); + } + if (context.hasEmpty) { + result = PredictionContext$1.join(result, suffix); + } + } + visited.put(context, result); + } + return result; + } + equals(o) { + if (this === o) { + return true; + } + else if (!(o instanceof ArrayPredictionContext)) { + return false; + } + if (this.hashCode() !== o.hashCode()) { + // can't be same if hash is different + return false; + } + let other = o; + return this.equalsImpl(other, new Array2DHashSet_1.Array2DHashSet()); + } + equalsImpl(other, visited) { + let selfWorkList = []; + let otherWorkList = []; + selfWorkList.push(this); + otherWorkList.push(other); + while (true) { + let currentSelf = selfWorkList.pop(); + let currentOther = otherWorkList.pop(); + if (!currentSelf || !currentOther) { + break; + } + let operands = new PredictionContextCache_1.PredictionContextCache.IdentityCommutativePredictionContextOperands(currentSelf, currentOther); + if (!visited.add(operands)) { + continue; + } + let selfSize = operands.x.size; + if (selfSize === 0) { + if (!operands.x.equals(operands.y)) { + return false; + } + continue; + } + let otherSize = operands.y.size; + if (selfSize !== otherSize) { + return false; + } + for (let i = 0; i < selfSize; i++) { + if (operands.x.getReturnState(i) !== operands.y.getReturnState(i)) { + return false; + } + let selfParent = operands.x.getParent(i); + let otherParent = operands.y.getParent(i); + if (selfParent.hashCode() !== otherParent.hashCode()) { + return false; + } + if (selfParent !== otherParent) { + selfWorkList.push(selfParent); + otherWorkList.push(otherParent); + } + } + } + return true; + } + }; + __decorate([ + Decorators_1.NotNull + ], ArrayPredictionContext.prototype, "parents", void 0); + __decorate([ + Decorators_1.NotNull + ], ArrayPredictionContext.prototype, "returnStates", void 0); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "getParent", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "getReturnState", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "findReturnState", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "isEmpty", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "hasEmpty", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "addEmptyContext", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "removeEmptyContext", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "appendContext", null); + __decorate([ + Decorators_1.Override + ], ArrayPredictionContext.prototype, "equals", null); + ArrayPredictionContext = __decorate([ + __param(0, Decorators_1.NotNull) + ], ArrayPredictionContext); + let SingletonPredictionContext = class SingletonPredictionContext extends PredictionContext$1 { + constructor(parent, returnState) { + super(PredictionContext$1.calculateSingleHashCode(parent, returnState)); + // assert(returnState != PredictionContext.EMPTY_FULL_STATE_KEY && returnState != PredictionContext.EMPTY_LOCAL_STATE_KEY); + this.parent = parent; + this.returnState = returnState; + } + getParent(index) { + // assert(index == 0); + return this.parent; + } + getReturnState(index) { + // assert(index == 0); + return this.returnState; + } + findReturnState(returnState) { + return this.returnState === returnState ? 0 : -1; + } + get size() { + return 1; + } + get isEmpty() { + return false; + } + get hasEmpty() { + return false; + } + appendContext(suffix, contextCache) { + return contextCache.getChild(this.parent.appendContext(suffix, contextCache), this.returnState); + } + addEmptyContext() { + let parents = [this.parent, PredictionContext$1.EMPTY_FULL]; + let returnStates = [this.returnState, PredictionContext$1.EMPTY_FULL_STATE_KEY]; + return new ArrayPredictionContext(parents, returnStates); + } + removeEmptyContext() { + return this; + } + equals(o) { + if (o === this) { + return true; + } + else if (!(o instanceof SingletonPredictionContext)) { + return false; + } + let other = o; + if (this.hashCode() !== other.hashCode()) { + return false; + } + return this.returnState === other.returnState + && this.parent.equals(other.parent); + } + }; + __decorate([ + Decorators_1.NotNull + ], SingletonPredictionContext.prototype, "parent", void 0); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "getParent", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "getReturnState", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "findReturnState", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "isEmpty", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "hasEmpty", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "appendContext", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "addEmptyContext", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "removeEmptyContext", null); + __decorate([ + Decorators_1.Override + ], SingletonPredictionContext.prototype, "equals", null); + SingletonPredictionContext = __decorate([ + __param(0, Decorators_1.NotNull) + ], SingletonPredictionContext); + exports.SingletonPredictionContext = SingletonPredictionContext; + (function (PredictionContext) { + PredictionContext.EMPTY_LOCAL = new EmptyPredictionContext(false); + PredictionContext.EMPTY_FULL = new EmptyPredictionContext(true); + PredictionContext.EMPTY_LOCAL_STATE_KEY = -2147483648; + PredictionContext.EMPTY_FULL_STATE_KEY = ((1 << 31) >>> 0) - 1; + class IdentityHashMap extends Array2DHashMap_1.Array2DHashMap { + constructor() { + super(IdentityEqualityComparator.INSTANCE); + } + } + PredictionContext.IdentityHashMap = IdentityHashMap; + class IdentityEqualityComparator { + IdentityEqualityComparator() { + // intentionally empty + } + hashCode(obj) { + return obj.hashCode(); + } + equals(a, b) { + return a === b; + } + } + IdentityEqualityComparator.INSTANCE = new IdentityEqualityComparator(); + __decorate([ + Decorators_1.Override + ], IdentityEqualityComparator.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], IdentityEqualityComparator.prototype, "equals", null); + PredictionContext.IdentityEqualityComparator = IdentityEqualityComparator; + })(PredictionContext$1 = exports.PredictionContext || (exports.PredictionContext = {})); + + } (PredictionContext)); + return PredictionContext; +} + +var hasRequiredATNConfig; + +function requireATNConfig () { + if (hasRequiredATNConfig) return ATNConfig; + hasRequiredATNConfig = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNConfig && ATNConfig.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ATNConfig && ATNConfig.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ATNConfig, "__esModule", { value: true }); + ATNConfig.ATNConfig = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:25.2796692-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const DecisionState_1 = requireDecisionState(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const PredictionContext_1 = requirePredictionContext(); + const SemanticContext_1 = requireSemanticContext(); + const assert = require$$0$9; + /** + * This field stores the bit mask for implementing the + * {@link #isPrecedenceFilterSuppressed} property as a bit within the + * existing {@link #altAndOuterContextDepth} field. + */ + const SUPPRESS_PRECEDENCE_FILTER = 0x80000000; + /** + * Represents a location with context in an ATN. The location is identified by the following values: + * + * * The current ATN state + * * The predicted alternative + * * The semantic context which must be true for this configuration to be enabled + * * The syntactic context, which is represented as a graph-structured stack whose path(s) lead to the root of the rule + * invocations leading to this state + * + * In addition to these values, `ATNConfig` stores several properties about paths taken to get to the location which + * were added over time to help with performance, correctness, and/or debugging. + * + * * `reachesIntoOuterContext`:: Used to ensure semantic predicates are not evaluated in the wrong context. + * * `hasPassedThroughNonGreedyDecision`: Used for enabling first-match-wins instead of longest-match-wins after + * crossing a non-greedy decision. + * * `lexerActionExecutor`: Used for tracking the lexer action(s) to execute should this instance be selected during + * lexing. + * * `isPrecedenceFilterSuppressed`: A state variable for one of the dynamic disambiguation strategies employed by + * `ParserATNSimulator.applyPrecedenceFilter`. + * + * Due to the use of a graph-structured stack, a single `ATNConfig` is capable of representing many individual ATN + * configurations which reached the same location in an ATN by following different paths. + * + * PERF: To conserve memory, `ATNConfig` is split into several different concrete types. `ATNConfig` itself stores the + * minimum amount of information typically used to define an `ATNConfig` instance. Various derived types provide + * additional storage space for cases where a non-default value is used for some of the object properties. The + * `ATNConfig.create` and `ATNConfig.transform` methods automatically select the smallest concrete type capable of + * representing the unique information for any given `ATNConfig`. + */ + let ATNConfig$1 = class ATNConfig { + constructor(state, altOrConfig, context) { + if (typeof altOrConfig === "number") { + assert((altOrConfig & 0xFFFFFF) === altOrConfig); + this._state = state; + this.altAndOuterContextDepth = altOrConfig; + this._context = context; + } + else { + this._state = state; + this.altAndOuterContextDepth = altOrConfig.altAndOuterContextDepth; + this._context = context; + } + } + static create(state, alt, context, semanticContext = SemanticContext_1.SemanticContext.NONE, lexerActionExecutor) { + if (semanticContext !== SemanticContext_1.SemanticContext.NONE) { + if (lexerActionExecutor != null) { + return new ActionSemanticContextATNConfig(lexerActionExecutor, semanticContext, state, alt, context, false); + } + else { + return new SemanticContextATNConfig(semanticContext, state, alt, context); + } + } + else if (lexerActionExecutor != null) { + return new ActionATNConfig(lexerActionExecutor, state, alt, context, false); + } + else { + return new ATNConfig(state, alt, context); + } + } + /** Gets the ATN state associated with this configuration */ + get state() { + return this._state; + } + /** What alt (or lexer rule) is predicted by this configuration */ + get alt() { + return this.altAndOuterContextDepth & 0x00FFFFFF; + } + get context() { + return this._context; + } + set context(context) { + this._context = context; + } + get reachesIntoOuterContext() { + return this.outerContextDepth !== 0; + } + /** + * We cannot execute predicates dependent upon local context unless + * we know for sure we are in the correct context. Because there is + * no way to do this efficiently, we simply cannot evaluate + * dependent predicates unless we are in the rule that initially + * invokes the ATN simulator. + * + * closure() tracks the depth of how far we dip into the outer context: + * depth > 0. Note that it may not be totally accurate depth since I + * don't ever decrement. TODO: make it a boolean then + */ + get outerContextDepth() { + return (this.altAndOuterContextDepth >>> 24) & 0x7F; + } + set outerContextDepth(outerContextDepth) { + assert(outerContextDepth >= 0); + // saturate at 0x7F - everything but zero/positive is only used for debug information anyway + outerContextDepth = Math.min(outerContextDepth, 0x7F); + this.altAndOuterContextDepth = ((outerContextDepth << 24) | (this.altAndOuterContextDepth & -2130706433) >>> 0); + } + get lexerActionExecutor() { + return undefined; + } + get semanticContext() { + return SemanticContext_1.SemanticContext.NONE; + } + get hasPassedThroughNonGreedyDecision() { + return false; + } + clone() { + return this.transform(this.state, false); + } + transform(/*@NotNull*/ state, checkNonGreedy, arg2) { + if (arg2 == null) { + return this.transformImpl(state, this._context, this.semanticContext, checkNonGreedy, this.lexerActionExecutor); + } + else if (arg2 instanceof PredictionContext_1.PredictionContext) { + return this.transformImpl(state, arg2, this.semanticContext, checkNonGreedy, this.lexerActionExecutor); + } + else if (arg2 instanceof SemanticContext_1.SemanticContext) { + return this.transformImpl(state, this._context, arg2, checkNonGreedy, this.lexerActionExecutor); + } + else { + return this.transformImpl(state, this._context, this.semanticContext, checkNonGreedy, arg2); + } + } + transformImpl(state, context, semanticContext, checkNonGreedy, lexerActionExecutor) { + let passedThroughNonGreedy = checkNonGreedy && ATNConfig.checkNonGreedyDecision(this, state); + if (semanticContext !== SemanticContext_1.SemanticContext.NONE) { + if (lexerActionExecutor != null || passedThroughNonGreedy) { + return new ActionSemanticContextATNConfig(lexerActionExecutor, semanticContext, state, this, context, passedThroughNonGreedy); + } + else { + return new SemanticContextATNConfig(semanticContext, state, this, context); + } + } + else if (lexerActionExecutor != null || passedThroughNonGreedy) { + return new ActionATNConfig(lexerActionExecutor, state, this, context, passedThroughNonGreedy); + } + else { + return new ATNConfig(state, this, context); + } + } + static checkNonGreedyDecision(source, target) { + return source.hasPassedThroughNonGreedyDecision + || target instanceof DecisionState_1.DecisionState && target.nonGreedy; + } + appendContext(context, contextCache) { + if (typeof context === "number") { + let appendedContext = this.context.appendSingleContext(context, contextCache); + let result = this.transform(this.state, false, appendedContext); + return result; + } + else { + let appendedContext = this.context.appendContext(context, contextCache); + let result = this.transform(this.state, false, appendedContext); + return result; + } + } + /** + * Determines if this `ATNConfig` fully contains another `ATNConfig`. + * + * An ATN configuration represents a position (including context) in an ATN during parsing. Since `ATNConfig` stores + * the context as a graph, a single `ATNConfig` instance is capable of representing many ATN configurations which + * are all in the same "location" but have different contexts. These `ATNConfig` instances are again merged when + * they are added to an `ATNConfigSet`. This method supports `ATNConfigSet.contains` by evaluating whether a + * particular `ATNConfig` contains all of the ATN configurations represented by another `ATNConfig`. + * + * An `ATNConfig` _a_ contains another `ATNConfig` _b_ if all of the following conditions are met: + * + * * The configurations are in the same state (`state`) + * * The configurations predict the same alternative (`alt`) + * * The semantic context of _a_ implies the semantic context of _b_ (this method performs a weaker equality check) + * * Joining the prediction contexts of _a_ and _b_ results in the prediction context of _a_ + * + * This method implements a conservative approximation of containment. As a result, when this method returns `true` + * it is known that parsing from `subconfig` can only recognize a subset of the inputs which can be recognized + * starting at the current `ATNConfig`. However, due to the imprecise evaluation of implication for the semantic + * contexts, no assumptions can be made about the relationship between the configurations when this method returns + * `false`. + * + * @param subconfig The sub configuration. + * @returns `true` if this configuration contains `subconfig`; otherwise, `false`. + */ + contains(subconfig) { + if (this.state.stateNumber !== subconfig.state.stateNumber + || this.alt !== subconfig.alt + || !this.semanticContext.equals(subconfig.semanticContext)) { + return false; + } + let leftWorkList = []; + let rightWorkList = []; + leftWorkList.push(this.context); + rightWorkList.push(subconfig.context); + while (true) { + let left = leftWorkList.pop(); + let right = rightWorkList.pop(); + if (!left || !right) { + break; + } + if (left === right) { + return true; + } + if (left.size < right.size) { + return false; + } + if (right.isEmpty) { + return left.hasEmpty; + } + else { + for (let i = 0; i < right.size; i++) { + let index = left.findReturnState(right.getReturnState(i)); + if (index < 0) { + // assumes invokingStates has no duplicate entries + return false; + } + leftWorkList.push(left.getParent(index)); + rightWorkList.push(right.getParent(i)); + } + } + } + return false; + } + get isPrecedenceFilterSuppressed() { + return (this.altAndOuterContextDepth & SUPPRESS_PRECEDENCE_FILTER) !== 0; + } + set isPrecedenceFilterSuppressed(value) { + if (value) { + this.altAndOuterContextDepth |= SUPPRESS_PRECEDENCE_FILTER; + } + else { + this.altAndOuterContextDepth &= ~SUPPRESS_PRECEDENCE_FILTER; + } + } + /** An ATN configuration is equal to another if both have + * the same state, they predict the same alternative, and + * syntactic/semantic contexts are the same. + */ + equals(o) { + if (this === o) { + return true; + } + else if (!(o instanceof ATNConfig)) { + return false; + } + return this.state.stateNumber === o.state.stateNumber + && this.alt === o.alt + && this.reachesIntoOuterContext === o.reachesIntoOuterContext + && this.context.equals(o.context) + && this.semanticContext.equals(o.semanticContext) + && this.isPrecedenceFilterSuppressed === o.isPrecedenceFilterSuppressed + && this.hasPassedThroughNonGreedyDecision === o.hasPassedThroughNonGreedyDecision + && ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE.equals(this.lexerActionExecutor, o.lexerActionExecutor); + } + hashCode() { + let hashCode = MurmurHash_1.MurmurHash.initialize(7); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.state.stateNumber); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.alt); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.reachesIntoOuterContext ? 1 : 0); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.context); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.semanticContext); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.hasPassedThroughNonGreedyDecision ? 1 : 0); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, this.lexerActionExecutor); + hashCode = MurmurHash_1.MurmurHash.finish(hashCode, 7); + return hashCode; + } + /** + * Returns a graphical representation of the current `ATNConfig` in Graphviz format. The graph can be stored to a + * **.dot** file and then rendered to an image using Graphviz. + * + * @returns A Graphviz graph representing the current `ATNConfig`. + * + * @see http://www.graphviz.org/ + */ + toDotString() { + let builder = ""; + builder += ("digraph G {\n"); + builder += ("rankdir=LR;\n"); + let visited = new Array2DHashMap_1.Array2DHashMap(PredictionContext_1.PredictionContext.IdentityEqualityComparator.INSTANCE); + let workList = []; + function getOrAddContext(context) { + let newNumber = visited.size; + let result = visited.putIfAbsent(context, newNumber); + if (result != null) { + // Already saw this context + return result; + } + workList.push(context); + return newNumber; + } + workList.push(this.context); + visited.put(this.context, 0); + while (true) { + let current = workList.pop(); + if (!current) { + break; + } + for (let i = 0; i < current.size; i++) { + builder += (" s") + (getOrAddContext(current)); + builder += ("->"); + builder += ("s") + (getOrAddContext(current.getParent(i))); + builder += ("[label=\"") + (current.getReturnState(i)) + ("\"];\n"); + } + } + builder += ("}\n"); + return builder.toString(); + } + toString(recog, showAlt, showContext) { + // Must check showContext before showAlt to preserve original overload behavior + if (showContext == null) { + showContext = showAlt != null; + } + if (showAlt == null) { + showAlt = true; + } + let buf = ""; + // if (this.state.ruleIndex >= 0) { + // if (recog != null) { + // buf += (recog.ruleNames[this.state.ruleIndex] + ":"); + // } else { + // buf += (this.state.ruleIndex + ":"); + // } + // } + let contexts; + if (showContext) { + contexts = this.context.toStrings(recog, this.state.stateNumber); + } + else { + contexts = ["?"]; + } + let first = true; + for (let contextDesc of contexts) { + if (first) { + first = false; + } + else { + buf += (", "); + } + buf += ("("); + buf += (this.state); + if (showAlt) { + buf += (","); + buf += (this.alt); + } + if (this.context) { + buf += (","); + buf += (contextDesc); + } + if (this.semanticContext !== SemanticContext_1.SemanticContext.NONE) { + buf += (","); + buf += (this.semanticContext); + } + if (this.reachesIntoOuterContext) { + buf += (",up=") + (this.outerContextDepth); + } + buf += (")"); + } + return buf.toString(); + } + }; + __decorate([ + Decorators_1.NotNull + ], ATNConfig$1.prototype, "_state", void 0); + __decorate([ + Decorators_1.NotNull + ], ATNConfig$1.prototype, "_context", void 0); + __decorate([ + Decorators_1.NotNull + ], ATNConfig$1.prototype, "state", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ATNConfig$1.prototype, "context", null); + __decorate([ + Decorators_1.NotNull + ], ATNConfig$1.prototype, "semanticContext", null); + __decorate([ + Decorators_1.Override + ], ATNConfig$1.prototype, "clone", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ATNConfig$1.prototype, "transformImpl", null); + __decorate([ + Decorators_1.Override + ], ATNConfig$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], ATNConfig$1.prototype, "hashCode", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(3, Decorators_1.NotNull) + ], ATNConfig$1, "create", null); + ATNConfig$1 = __decorate([ + __param(0, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ATNConfig$1); + ATNConfig.ATNConfig = ATNConfig$1; + /** + * This class was derived from `ATNConfig` purely as a memory optimization. It allows for the creation of an `ATNConfig` + * with a non-default semantic context. + * + * See the `ATNConfig` documentation for more information about conserving memory through the use of several concrete + * types. + */ + let SemanticContextATNConfig = class SemanticContextATNConfig extends ATNConfig$1 { + constructor(semanticContext, state, altOrConfig, context) { + if (typeof altOrConfig === "number") { + super(state, altOrConfig, context); + } + else { + super(state, altOrConfig, context); + } + this._semanticContext = semanticContext; + } + get semanticContext() { + return this._semanticContext; + } + }; + __decorate([ + Decorators_1.NotNull + ], SemanticContextATNConfig.prototype, "_semanticContext", void 0); + __decorate([ + Decorators_1.Override + ], SemanticContextATNConfig.prototype, "semanticContext", null); + SemanticContextATNConfig = __decorate([ + __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], SemanticContextATNConfig); + /** + * This class was derived from `ATNConfig` purely as a memory optimization. It allows for the creation of an `ATNConfig` + * with a lexer action. + * + * See the `ATNConfig` documentation for more information about conserving memory through the use of several concrete + * types. + */ + let ActionATNConfig = class ActionATNConfig extends ATNConfig$1 { + constructor(lexerActionExecutor, state, altOrConfig, context, passedThroughNonGreedyDecision) { + if (typeof altOrConfig === "number") { + super(state, altOrConfig, context); + } + else { + super(state, altOrConfig, context); + if (altOrConfig.semanticContext !== SemanticContext_1.SemanticContext.NONE) { + throw new Error("Not supported"); + } + } + this._lexerActionExecutor = lexerActionExecutor; + this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; + } + get lexerActionExecutor() { + return this._lexerActionExecutor; + } + get hasPassedThroughNonGreedyDecision() { + return this.passedThroughNonGreedyDecision; + } + }; + __decorate([ + Decorators_1.Override + ], ActionATNConfig.prototype, "lexerActionExecutor", null); + __decorate([ + Decorators_1.Override + ], ActionATNConfig.prototype, "hasPassedThroughNonGreedyDecision", null); + ActionATNConfig = __decorate([ + __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ActionATNConfig); + /** + * This class was derived from `SemanticContextATNConfig` purely as a memory optimization. It allows for the creation of + * an `ATNConfig` with both a lexer action and a non-default semantic context. + * + * See the `ATNConfig` documentation for more information about conserving memory through the use of several concrete + * types. + */ + let ActionSemanticContextATNConfig = class ActionSemanticContextATNConfig extends SemanticContextATNConfig { + constructor(lexerActionExecutor, semanticContext, state, altOrConfig, context, passedThroughNonGreedyDecision) { + if (typeof altOrConfig === "number") { + super(semanticContext, state, altOrConfig, context); + } + else { + super(semanticContext, state, altOrConfig, context); + } + this._lexerActionExecutor = lexerActionExecutor; + this.passedThroughNonGreedyDecision = passedThroughNonGreedyDecision; + } + get lexerActionExecutor() { + return this._lexerActionExecutor; + } + get hasPassedThroughNonGreedyDecision() { + return this.passedThroughNonGreedyDecision; + } + }; + __decorate([ + Decorators_1.Override + ], ActionSemanticContextATNConfig.prototype, "lexerActionExecutor", null); + __decorate([ + Decorators_1.Override + ], ActionSemanticContextATNConfig.prototype, "hasPassedThroughNonGreedyDecision", null); + ActionSemanticContextATNConfig = __decorate([ + __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ActionSemanticContextATNConfig); + + return ATNConfig; +} + +var BitSet = {}; + +var hasRequiredBitSet; + +function requireBitSet () { + if (hasRequiredBitSet) return BitSet; + hasRequiredBitSet = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(BitSet, "__esModule", { value: true }); + BitSet.BitSet = void 0; + const util = require$$6; + const MurmurHash_1 = requireMurmurHash(); + /** + * Private empty array used to construct empty BitSets + */ + const EMPTY_DATA = new Uint16Array(0); + /** + * Gets the word index of the `UInt16` element in `BitSet.data` containing the bit with the specified index. + */ + function getIndex(bitNumber) { + return bitNumber >>> 4; + } + /** + * Convert a word index into the bit index of the LSB of that word + */ + function unIndex(n) { + return n * 16; + } + /** + * Get's the bit number of the least signficant bit set LSB which is set in a word non-zero word; + * Bit numbers run from LSB to MSB starting with 0. + */ + function findLSBSet(word) { + let bit = 1; + for (let i = 0; i < 16; i++) { + if ((word & bit) !== 0) { + return i; + } + bit = (bit << 1) >>> 0; + } + throw new RangeError("No specified bit found"); + } + function findMSBSet(word) { + let bit = (1 << 15) >>> 0; + for (let i = 15; i >= 0; i--) { + if ((word & bit) !== 0) { + return i; + } + bit = bit >>> 1; + } + throw new RangeError("No specified bit found"); + } + /** + * Gets a 16-bit mask with bit numbers fromBit to toBit (inclusive) set. + * Bit numbers run from LSB to MSB starting with 0. + */ + function bitsFor(fromBit, toBit) { + fromBit &= 0xF; + toBit &= 0xF; + if (fromBit === toBit) { + return (1 << fromBit) >>> 0; + } + return ((0xFFFF >>> (15 - toBit)) ^ (0xFFFF >>> (16 - fromBit))); + } + /** + * A lookup table for number of set bits in a 16-bit integer. This is used to quickly count the cardinality (number of unique elements) of a BitSet. + */ + const POP_CNT = new Uint8Array(65536); + for (let i = 0; i < 16; i++) { + const stride = (1 << i) >>> 0; + let index = 0; + while (index < POP_CNT.length) { + // skip the numbers where the bit isn't set + index += stride; + // increment the ones where the bit is set + for (let j = 0; j < stride; j++) { + POP_CNT[index]++; + index++; + } + } + } + let BitSet$1 = class BitSet { + /* + ** constructor implementation + */ + constructor(arg) { + if (!arg) { + // covering the case of unspecified and nbits===0 + this.data = EMPTY_DATA; + } + else if (typeof arg === "number") { + if (arg < 0) { + throw new RangeError("nbits cannot be negative"); + } + else { + this.data = new Uint16Array(getIndex(arg - 1) + 1); + } + } + else { + if (arg instanceof BitSet) { + this.data = arg.data.slice(0); // Clone the data + } + else { + let max = -1; + for (let v of arg) { + if (max < v) { + max = v; + } + } + this.data = new Uint16Array(getIndex(max - 1) + 1); + for (let v of arg) { + this.set(v); + } + } + } + } + /** + * Performs a logical **AND** of this target bit set with the argument bit set. This bit set is modified so that + * each bit in it has the value `true` if and only if it both initially had the value `true` and the corresponding + * bit in the bit set argument also had the value `true`. + */ + and(set) { + const data = this.data; + const other = set.data; + const words = Math.min(data.length, other.length); + let lastWord = -1; // Keep track of index of last non-zero word + for (let i = 0; i < words; i++) { + let value = data[i] &= other[i]; + if (value !== 0) { + lastWord = i; + } + } + if (lastWord === -1) { + this.data = EMPTY_DATA; + } + if (lastWord < data.length - 1) { + this.data = data.slice(0, lastWord + 1); + } + } + /** + * Clears all of the bits in this `BitSet` whose corresponding bit is set in the specified `BitSet`. + */ + andNot(set) { + const data = this.data; + const other = set.data; + const words = Math.min(data.length, other.length); + let lastWord = -1; // Keep track of index of last non-zero word + for (let i = 0; i < words; i++) { + let value = data[i] &= (other[i] ^ 0xFFFF); + if (value !== 0) { + lastWord = i; + } + } + if (lastWord === -1) { + this.data = EMPTY_DATA; + } + if (lastWord < data.length - 1) { + this.data = data.slice(0, lastWord + 1); + } + } + /** + * Returns the number of bits set to `true` in this `BitSet`. + */ + cardinality() { + if (this.isEmpty) { + return 0; + } + const data = this.data; + const length = data.length; + let result = 0; + for (let i = 0; i < length; i++) { + result += POP_CNT[data[i]]; + } + return result; + } + clear(fromIndex, toIndex) { + if (fromIndex == null) { + this.data.fill(0); + } + else if (toIndex == null) { + this.set(fromIndex, false); + } + else { + this.set(fromIndex, toIndex, false); + } + } + flip(fromIndex, toIndex) { + if (toIndex == null) { + toIndex = fromIndex; + } + if (fromIndex < 0 || toIndex < fromIndex) { + throw new RangeError(); + } + let word = getIndex(fromIndex); + const lastWord = getIndex(toIndex); + if (word === lastWord) { + this.data[word] ^= bitsFor(fromIndex, toIndex); + } + else { + this.data[word++] ^= bitsFor(fromIndex, 15); + while (word < lastWord) { + this.data[word++] ^= 0xFFFF; + } + this.data[word++] ^= bitsFor(0, toIndex); + } + } + get(fromIndex, toIndex) { + if (toIndex === undefined) { + return !!(this.data[getIndex(fromIndex)] & bitsFor(fromIndex, fromIndex)); + } + else { + // return a BitSet + let result = new BitSet(toIndex + 1); + for (let i = fromIndex; i <= toIndex; i++) { + result.set(i, this.get(i)); + } + return result; + } + } + /** + * Returns true if the specified `BitSet` has any bits set to `true` that are also set to `true` in this `BitSet`. + * + * @param set `BitSet` to intersect with + */ + intersects(set) { + let smallerLength = Math.min(this.length(), set.length()); + if (smallerLength === 0) { + return false; + } + let bound = getIndex(smallerLength - 1); + for (let i = 0; i <= bound; i++) { + if ((this.data[i] & set.data[i]) !== 0) { + return true; + } + } + return false; + } + /** + * Returns true if this `BitSet` contains no bits that are set to `true`. + */ + get isEmpty() { + return this.length() === 0; + } + /** + * Returns the "logical size" of this `BitSet`: the index of the highest set bit in the `BitSet` plus one. Returns + * zero if the `BitSet` contains no set bits. + */ + length() { + if (!this.data.length) { + return 0; + } + return this.previousSetBit(unIndex(this.data.length) - 1) + 1; + } + /** + * Returns the index of the first bit that is set to `false` that occurs on or after the specified starting index, + * If no such bit exists then `-1` is returned. + * + * @param fromIndex the index to start checking from (inclusive) + * + * @throws RangeError if the specified index is negative + */ + nextClearBit(fromIndex) { + if (fromIndex < 0) { + throw new RangeError("fromIndex cannot be negative"); + } + const data = this.data; + const length = data.length; + let word = getIndex(fromIndex); + if (word > length) { + return -1; + } + let ignore = 0xFFFF ^ bitsFor(fromIndex, 15); + if ((data[word] | ignore) === 0xFFFF) { + word++; + ignore = 0; + for (; word < length; word++) { + if (data[word] !== 0xFFFF) { + break; + } + } + if (word === length) { + // Hit the end + return -1; + } + } + return unIndex(word) + findLSBSet((data[word] | ignore) ^ 0xFFFF); + } + /** + * Returns the index of the first bit that is set to `true` that occurs on or after the specified starting index. + * If no such bit exists then `-1` is returned. + * + * To iterate over the `true` bits in a `BitSet`, use the following loop: + * + * ``` + * for (let i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { + * // operate on index i here + * } + * ``` + * + * @param fromIndex the index to start checking from (inclusive) + * + * @throws RangeError if the specified index is negative + */ + nextSetBit(fromIndex) { + if (fromIndex < 0) { + throw new RangeError("fromIndex cannot be negative"); + } + const data = this.data; + const length = data.length; + let word = getIndex(fromIndex); + if (word > length) { + return -1; + } + let mask = bitsFor(fromIndex, 15); + if ((data[word] & mask) === 0) { + word++; + mask = 0xFFFF; + for (; word < length; word++) { + if (data[word] !== 0) { + break; + } + } + if (word >= length) { + return -1; + } + } + return unIndex(word) + findLSBSet(data[word] & mask); + } + /** + * Performs a logical **OR** of this bit set with the bit set argument. This bit set is modified so that a bit in it + * has the value `true` if and only if it either already had the value `true` or the corresponding bit in the bit + * set argument has the value `true`. + */ + or(set) { + const data = this.data; + const other = set.data; + const minWords = Math.min(data.length, other.length); + const words = Math.max(data.length, other.length); + const dest = data.length === words ? data : new Uint16Array(words); + let lastWord = -1; + // Or those words both sets have in common + for (let i = 0; i < minWords; i++) { + let value = dest[i] = data[i] | other[i]; + if (value !== 0) { + lastWord = i; + } + } + // Copy words from larger set (if there is one) + const longer = data.length > other.length ? data : other; + for (let i = minWords; i < words; i++) { + let value = dest[i] = longer[i]; + if (value !== 0) { + lastWord = i; + } + } + if (lastWord === -1) { + this.data = EMPTY_DATA; + } + else if (dest.length === lastWord + 1) { + this.data = dest; + } + else { + this.data = dest.slice(0, lastWord); + } + } + /** + * Returns the index of the nearest bit that is set to `false` that occurs on or before the specified starting + * index. If no such bit exists, or if `-1` is given as the starting index, then `-1` is returned. + * + * @param fromIndex the index to start checking from (inclusive) + * + * @throws RangeError if the specified index is less than `-1` + */ + previousClearBit(fromIndex) { + if (fromIndex < 0) { + throw new RangeError("fromIndex cannot be negative"); + } + const data = this.data; + const length = data.length; + let word = getIndex(fromIndex); + if (word >= length) { + word = length - 1; + } + let ignore = 0xFFFF ^ bitsFor(0, fromIndex); + if ((data[word] | ignore) === 0xFFFF) { + ignore = 0; + word--; + for (; word >= 0; word--) { + if (data[word] !== 0xFFFF) { + break; + } + } + if (word < 0) { + // Hit the end + return -1; + } + } + return unIndex(word) + findMSBSet((data[word] | ignore) ^ 0xFFFF); + } + /** + * Returns the index of the nearest bit that is set to `true` that occurs on or before the specified starting index. + * If no such bit exists, or if `-1` is given as the starting index, then `-1` is returned. + * + * To iterate over the `true` bits in a `BitSet`, use the following loop: + * + * ``` + * for (let i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) { + * // operate on index i here + * } + * ``` + * + * @param fromIndex the index to start checking from (inclusive) + * + * @throws RangeError if the specified index is less than `-1` + */ + previousSetBit(fromIndex) { + if (fromIndex < 0) { + throw new RangeError("fromIndex cannot be negative"); + } + const data = this.data; + const length = data.length; + let word = getIndex(fromIndex); + if (word >= length) { + word = length - 1; + } + let mask = bitsFor(0, fromIndex); + if ((data[word] & mask) === 0) { + word--; + mask = 0xFFFF; + for (; word >= 0; word--) { + if (data[word] !== 0) { + break; + } + } + if (word < 0) { + return -1; + } + } + return unIndex(word) + findMSBSet(data[word] & mask); + } + set(fromIndex, toIndex, value) { + if (toIndex === undefined) { + toIndex = fromIndex; + value = true; + } + else if (typeof toIndex === "boolean") { + value = toIndex; + toIndex = fromIndex; + } + if (value === undefined) { + value = true; + } + if (fromIndex < 0 || fromIndex > toIndex) { + throw new RangeError(); + } + let word = getIndex(fromIndex); + let lastWord = getIndex(toIndex); + if (value && lastWord >= this.data.length) { + // Grow array "just enough" for bits we need to set + let temp = new Uint16Array(lastWord + 1); + this.data.forEach((value, index) => temp[index] = value); + this.data = temp; + } + else if (!value) { + // But there is no need to grow array to clear bits. + if (word >= this.data.length) { + // Early exit + return; + } + if (lastWord >= this.data.length) { + // Adjust work to fit array + lastWord = this.data.length - 1; + toIndex = this.data.length * 16 - 1; + } + } + if (word === lastWord) { + this._setBits(word, value, bitsFor(fromIndex, toIndex)); + } + else { + this._setBits(word++, value, bitsFor(fromIndex, 15)); + while (word < lastWord) { + this.data[word++] = value ? 0xFFFF : 0; + } + this._setBits(word, value, bitsFor(0, toIndex)); + } + } + _setBits(word, value, mask) { + if (value) { + this.data[word] |= mask; + } + else { + this.data[word] &= 0xFFFF ^ mask; + } + } + /** + * Returns the number of bits of space actually in use by this `BitSet` to represent bit values. The maximum element + * in the set is the size - 1st element. + */ + get size() { + return this.data.byteLength * 8; + } + /** + * Returns a new byte array containing all the bits in this bit set. + * + * More precisely, if + * `let bytes = s.toByteArray();` + * then `bytes.length === (s.length()+7)/8` and `s.get(n) === ((bytes[n/8] & (1<<(n%8))) != 0)` for all + * `n < 8 * bytes.length`. + */ + // toByteArray(): Int8Array { + // throw new Error("NOT IMPLEMENTED"); + // } + /** + * Returns a new integer array containing all the bits in this bit set. + * + * More precisely, if + * `let integers = s.toIntegerArray();` + * then `integers.length === (s.length()+31)/32` and `s.get(n) === ((integers[n/32] & (1<<(n%32))) != 0)` for all + * `n < 32 * integers.length`. + */ + // toIntegerArray(): Int32Array { + // throw new Error("NOT IMPLEMENTED"); + // } + hashCode() { + return MurmurHash_1.MurmurHash.hashCode(this.data, 22); + } + /** + * Compares this object against the specified object. The result is `true` if and only if the argument is not + * `undefined` and is a `Bitset` object that has exactly the same set of bits set to `true` as this bit set. That + * is, for every nonnegative index `k`, + * + * ``` + * ((BitSet)obj).get(k) == this.get(k) + * ``` + * + * must be true. The current sizes of the two bit sets are not compared. + */ + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof BitSet)) { + return false; + } + const len = this.length(); + if (len !== obj.length()) { + return false; + } + if (len === 0) { + return true; + } + let bound = getIndex(len - 1); + for (let i = 0; i <= bound; i++) { + if (this.data[i] !== obj.data[i]) { + return false; + } + } + return true; + } + /** + * Returns a string representation of this bit set. For every index for which this `BitSet` contains a bit in the + * set state, the decimal representation of that index is included in the result. Such indices are listed in order + * from lowest to highest, separated by ", " (a comma and a space) and surrounded by braces, resulting in the usual + * mathematical notation for a set of integers. + * + * Example: + * + * BitSet drPepper = new BitSet(); + * + * Now `drPepper.toString()` returns `"{}"`. + * + * drPepper.set(2); + * + * Now `drPepper.toString()` returns `"{2}"`. + * + * drPepper.set(4); + * drPepper.set(10); + * + * Now `drPepper.toString()` returns `"{2, 4, 10}"`. + */ + toString() { + let result = "{"; + let first = true; + for (let i = this.nextSetBit(0); i >= 0; i = this.nextSetBit(i + 1)) { + if (first) { + first = false; + } + else { + result += ", "; + } + result += i; + } + result += "}"; + return result; + } + // static valueOf(bytes: Int8Array): BitSet; + // static valueOf(buffer: ArrayBuffer): BitSet; + // static valueOf(integers: Int32Array): BitSet; + // static valueOf(data: Int8Array | Int32Array | ArrayBuffer): BitSet { + // throw new Error("NOT IMPLEMENTED"); + // } + /** + * Performs a logical **XOR** of this bit set with the bit set argument. This bit set is modified so that a bit in + * it has the value `true` if and only if one of the following statements holds: + * + * * The bit initially has the value `true`, and the corresponding bit in the argument has the value `false`. + * * The bit initially has the value `false`, and the corresponding bit in the argument has the value `true`. + */ + xor(set) { + const data = this.data; + const other = set.data; + const minWords = Math.min(data.length, other.length); + const words = Math.max(data.length, other.length); + const dest = data.length === words ? data : new Uint16Array(words); + let lastWord = -1; + // Xor those words both sets have in common + for (let i = 0; i < minWords; i++) { + let value = dest[i] = data[i] ^ other[i]; + if (value !== 0) { + lastWord = i; + } + } + // Copy words from larger set (if there is one) + const longer = data.length > other.length ? data : other; + for (let i = minWords; i < words; i++) { + let value = dest[i] = longer[i]; + if (value !== 0) { + lastWord = i; + } + } + if (lastWord === -1) { + this.data = EMPTY_DATA; + } + else if (dest.length === lastWord + 1) { + this.data = dest; + } + else { + this.data = dest.slice(0, lastWord + 1); + } + } + clone() { + return new BitSet(this); + } + [Symbol.iterator]() { + return new BitSetIterator(this.data); + } + // Overrides formatting for nodejs assert etc. + [util.inspect.custom]() { + return "BitSet " + this.toString(); + } + }; + BitSet.BitSet = BitSet$1; + class BitSetIterator { + constructor(data) { + this.data = data; + this.index = 0; + this.mask = 0xFFFF; + } + next() { + while (this.index < this.data.length) { + const bits = this.data[this.index] & this.mask; + if (bits !== 0) { + const bitNumber = unIndex(this.index) + findLSBSet(bits); + this.mask = bitsFor(bitNumber + 1, 15); + return { done: false, value: bitNumber }; + } + this.index++; + this.mask = 0xFFFF; + } + return { done: true, value: -1 }; + } + [Symbol.iterator]() { return this; } + } + + return BitSet; +} + +var hasRequiredATNConfigSet; + +function requireATNConfigSet () { + if (hasRequiredATNConfigSet) return ATNConfigSet; + hasRequiredATNConfigSet = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNConfigSet && ATNConfigSet.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ATNConfigSet, "__esModule", { value: true }); + ATNConfigSet.ATNConfigSet = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:25.5488013-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const Array2DHashSet_1 = requireArray2DHashSet(); + const ArrayEqualityComparator_1 = requireArrayEqualityComparator(); + const ATN_1 = requireATN(); + const ATNConfig_1 = requireATNConfig(); + const BitSet_1 = requireBitSet(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const PredictionContext_1 = requirePredictionContext(); + const PredictionContextCache_1 = requirePredictionContextCache(); + const SemanticContext_1 = requireSemanticContext(); + const assert = require$$0$9; + const Utils = requireUtils(); + class KeyTypeEqualityComparer { + hashCode(key) { + return key.state ^ key.alt; + } + equals(a, b) { + return a.state === b.state && a.alt === b.alt; + } + } + KeyTypeEqualityComparer.INSTANCE = new KeyTypeEqualityComparer(); + function NewKeyedConfigMap(map) { + if (map) { + return new Array2DHashMap_1.Array2DHashMap(map); + } + else { + return new Array2DHashMap_1.Array2DHashMap(KeyTypeEqualityComparer.INSTANCE); + } + } + /** + * Represents a set of ATN configurations (see `ATNConfig`). As configurations are added to the set, they are merged + * with other `ATNConfig` instances already in the set when possible using the graph-structured stack. + * + * An instance of this class represents the complete set of positions (with context) in an ATN which would be associated + * with a single DFA state. Its internal representation is more complex than traditional state used for NFA to DFA + * conversion due to performance requirements (both improving speed and reducing memory overhead) as well as supporting + * features such as semantic predicates and non-greedy operators in a form to support ANTLR's prediction algorithm. + * + * @author Sam Harwell + */ + let ATNConfigSet$1 = class ATNConfigSet { + constructor(set, readonly) { + this._uniqueAlt = 0; + // Used in parser and lexer. In lexer, it indicates we hit a pred + // while computing a closure operation. Don't make a DFA state from this. + this._hasSemanticContext = false; + this._dipsIntoOuterContext = false; + /** + * When `true`, this config set represents configurations where the entire + * outer context has been consumed by the ATN interpreter. This prevents the + * {@link ParserATNSimulator#closure} from pursuing the global FOLLOW when a + * rule stop state is reached with an empty prediction context. + * + * Note: `outermostConfigSet` and {@link #dipsIntoOuterContext} should never + * be true at the same time. + */ + this.outermostConfigSet = false; + this.cachedHashCode = -1; + if (!set) { + this.mergedConfigs = NewKeyedConfigMap(); + this.unmerged = []; + this.configs = []; + this._uniqueAlt = ATN_1.ATN.INVALID_ALT_NUMBER; + } + else { + if (readonly) { + this.mergedConfigs = undefined; + this.unmerged = undefined; + } + else if (!set.isReadOnly) { + this.mergedConfigs = NewKeyedConfigMap(set.mergedConfigs); + this.unmerged = set.unmerged.slice(0); + } + else { + this.mergedConfigs = NewKeyedConfigMap(); + this.unmerged = []; + } + this.configs = set.configs.slice(0); + this._dipsIntoOuterContext = set._dipsIntoOuterContext; + this._hasSemanticContext = set._hasSemanticContext; + this.outermostConfigSet = set.outermostConfigSet; + if (readonly || !set.isReadOnly) { + this._uniqueAlt = set._uniqueAlt; + this._conflictInfo = set._conflictInfo; + } + // if (!readonly && set.isReadOnly) -> addAll is called from clone() + } + } + /** + * Get the set of all alternatives represented by configurations in this + * set. + */ + getRepresentedAlternatives() { + if (this._conflictInfo != null) { + return this._conflictInfo.conflictedAlts.clone(); + } + let alts = new BitSet_1.BitSet(); + for (let config of this) { + alts.set(config.alt); + } + return alts; + } + get isReadOnly() { + return this.mergedConfigs == null; + } + get isOutermostConfigSet() { + return this.outermostConfigSet; + } + set isOutermostConfigSet(outermostConfigSet) { + if (this.outermostConfigSet && !outermostConfigSet) { + throw new Error("IllegalStateException"); + } + assert(!outermostConfigSet || !this._dipsIntoOuterContext); + this.outermostConfigSet = outermostConfigSet; + } + getStates() { + let states = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + for (let c of this.configs) { + states.add(c.state); + } + return states; + } + optimizeConfigs(interpreter) { + if (this.configs.length === 0) { + return; + } + for (let config of this.configs) { + config.context = interpreter.atn.getCachedContext(config.context); + } + } + clone(readonly) { + let copy = new ATNConfigSet(this, readonly); + if (!readonly && this.isReadOnly) { + copy.addAll(this.configs); + } + return copy; + } + get size() { + return this.configs.length; + } + get isEmpty() { + return this.configs.length === 0; + } + contains(o) { + if (!(o instanceof ATNConfig_1.ATNConfig)) { + return false; + } + if (this.mergedConfigs && this.unmerged) { + let config = o; + let configKey = this.getKey(config); + let mergedConfig = this.mergedConfigs.get(configKey); + if (mergedConfig != null && this.canMerge(config, configKey, mergedConfig)) { + return mergedConfig.contains(config); + } + for (let c of this.unmerged) { + if (c.contains(o)) { + return true; + } + } + } + else { + for (let c of this.configs) { + if (c.contains(o)) { + return true; + } + } + } + return false; + } + *[Symbol.iterator]() { + yield* this.configs; + } + toArray() { + return this.configs; + } + add(e, contextCache) { + this.ensureWritable(); + if (!this.mergedConfigs || !this.unmerged) { + throw new Error("Covered by ensureWritable but duplicated here for strict null check limitation"); + } + assert(!this.outermostConfigSet || !e.reachesIntoOuterContext); + if (contextCache == null) { + contextCache = PredictionContextCache_1.PredictionContextCache.UNCACHED; + } + let addKey; + let key = this.getKey(e); + let mergedConfig = this.mergedConfigs.get(key); + addKey = (mergedConfig == null); + if (mergedConfig != null && this.canMerge(e, key, mergedConfig)) { + mergedConfig.outerContextDepth = Math.max(mergedConfig.outerContextDepth, e.outerContextDepth); + if (e.isPrecedenceFilterSuppressed) { + mergedConfig.isPrecedenceFilterSuppressed = true; + } + let joined = PredictionContext_1.PredictionContext.join(mergedConfig.context, e.context, contextCache); + this.updatePropertiesForMergedConfig(e); + if (mergedConfig.context === joined) { + return false; + } + mergedConfig.context = joined; + return true; + } + for (let i = 0; i < this.unmerged.length; i++) { + let unmergedConfig = this.unmerged[i]; + if (this.canMerge(e, key, unmergedConfig)) { + unmergedConfig.outerContextDepth = Math.max(unmergedConfig.outerContextDepth, e.outerContextDepth); + if (e.isPrecedenceFilterSuppressed) { + unmergedConfig.isPrecedenceFilterSuppressed = true; + } + let joined = PredictionContext_1.PredictionContext.join(unmergedConfig.context, e.context, contextCache); + this.updatePropertiesForMergedConfig(e); + if (unmergedConfig.context === joined) { + return false; + } + unmergedConfig.context = joined; + if (addKey) { + this.mergedConfigs.put(key, unmergedConfig); + this.unmerged.splice(i, 1); + } + return true; + } + } + this.configs.push(e); + if (addKey) { + this.mergedConfigs.put(key, e); + } + else { + this.unmerged.push(e); + } + this.updatePropertiesForAddedConfig(e); + return true; + } + updatePropertiesForMergedConfig(config) { + // merged configs can't change the alt or semantic context + this._dipsIntoOuterContext = this._dipsIntoOuterContext || config.reachesIntoOuterContext; + assert(!this.outermostConfigSet || !this._dipsIntoOuterContext); + } + updatePropertiesForAddedConfig(config) { + if (this.configs.length === 1) { + this._uniqueAlt = config.alt; + } + else if (this._uniqueAlt !== config.alt) { + this._uniqueAlt = ATN_1.ATN.INVALID_ALT_NUMBER; + } + this._hasSemanticContext = this._hasSemanticContext || !SemanticContext_1.SemanticContext.NONE.equals(config.semanticContext); + this._dipsIntoOuterContext = this._dipsIntoOuterContext || config.reachesIntoOuterContext; + assert(!this.outermostConfigSet || !this._dipsIntoOuterContext); + } + canMerge(left, leftKey, right) { + if (left.state.stateNumber !== right.state.stateNumber) { + return false; + } + if (leftKey.alt !== right.alt) { + return false; + } + return left.semanticContext.equals(right.semanticContext); + } + getKey(e) { + return { state: e.state.stateNumber, alt: e.alt }; + } + containsAll(c) { + for (let o of c) { + if (!(o instanceof ATNConfig_1.ATNConfig)) { + return false; + } + if (!this.contains(o)) { + return false; + } + } + return true; + } + addAll(c, contextCache) { + this.ensureWritable(); + let changed = false; + for (let group of c) { + if (this.add(group, contextCache)) { + changed = true; + } + } + return changed; + } + clear() { + this.ensureWritable(); + if (!this.mergedConfigs || !this.unmerged) { + throw new Error("Covered by ensureWritable but duplicated here for strict null check limitation"); + } + this.mergedConfigs.clear(); + this.unmerged.length = 0; + this.configs.length = 0; + this._dipsIntoOuterContext = false; + this._hasSemanticContext = false; + this._uniqueAlt = ATN_1.ATN.INVALID_ALT_NUMBER; + this._conflictInfo = undefined; + } + equals(obj) { + if (this === obj) { + return true; + } + if (!(obj instanceof ATNConfigSet)) { + return false; + } + return this.outermostConfigSet === obj.outermostConfigSet + && Utils.equals(this._conflictInfo, obj._conflictInfo) + && ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.equals(this.configs, obj.configs); + } + hashCode() { + if (this.isReadOnly && this.cachedHashCode !== -1) { + return this.cachedHashCode; + } + let hashCode = 1; + hashCode = 5 * hashCode ^ (this.outermostConfigSet ? 1 : 0); + hashCode = 5 * hashCode ^ ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.hashCode(this.configs); + if (this.isReadOnly) { + this.cachedHashCode = hashCode; + } + return hashCode; + } + toString(showContext) { + if (showContext == null) { + showContext = false; + } + let buf = ""; + let sortedConfigs = this.configs.slice(0); + sortedConfigs.sort((o1, o2) => { + if (o1.alt !== o2.alt) { + return o1.alt - o2.alt; + } + else if (o1.state.stateNumber !== o2.state.stateNumber) { + return o1.state.stateNumber - o2.state.stateNumber; + } + else { + return o1.semanticContext.toString().localeCompare(o2.semanticContext.toString()); + } + }); + buf += ("["); + for (let i = 0; i < sortedConfigs.length; i++) { + if (i > 0) { + buf += (", "); + } + buf += (sortedConfigs[i].toString(undefined, true, showContext)); + } + buf += ("]"); + if (this._hasSemanticContext) { + buf += (",hasSemanticContext=") + (this._hasSemanticContext); + } + if (this._uniqueAlt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + buf += (",uniqueAlt=") + (this._uniqueAlt); + } + if (this._conflictInfo != null) { + buf += (",conflictingAlts=") + (this._conflictInfo.conflictedAlts); + if (!this._conflictInfo.isExact) { + buf += ("*"); + } + } + if (this._dipsIntoOuterContext) { + buf += (",dipsIntoOuterContext"); + } + return buf.toString(); + } + get uniqueAlt() { + return this._uniqueAlt; + } + get hasSemanticContext() { + return this._hasSemanticContext; + } + set hasSemanticContext(value) { + this.ensureWritable(); + this._hasSemanticContext = value; + } + get conflictInfo() { + return this._conflictInfo; + } + set conflictInfo(conflictInfo) { + this.ensureWritable(); + this._conflictInfo = conflictInfo; + } + get conflictingAlts() { + if (this._conflictInfo == null) { + return undefined; + } + return this._conflictInfo.conflictedAlts; + } + get isExactConflict() { + if (this._conflictInfo == null) { + return false; + } + return this._conflictInfo.isExact; + } + get dipsIntoOuterContext() { + return this._dipsIntoOuterContext; + } + get(index) { + return this.configs[index]; + } + ensureWritable() { + if (this.isReadOnly) { + throw new Error("This ATNConfigSet is read only."); + } + } + }; + __decorate([ + Decorators_1.NotNull + ], ATNConfigSet$1.prototype, "getRepresentedAlternatives", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "isEmpty", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "contains", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, Symbol.iterator, null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "toArray", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "containsAll", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "clear", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], ATNConfigSet$1.prototype, "hashCode", null); + ATNConfigSet.ATNConfigSet = ATNConfigSet$1; + + return ATNConfigSet; +} + +var DFASerializer = {}; + +var ATNSimulator = {}; + +var DFAState = {}; + +var hasRequiredDFAState; + +function requireDFAState () { + if (hasRequiredDFAState) return DFAState; + hasRequiredDFAState = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DFAState && DFAState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (DFAState && DFAState.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DFAState = void 0; + const ATN_1 = requireATN(); + const BitSet_1 = requireBitSet(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const PredictionContext_1 = requirePredictionContext(); + const assert = require$$0$9; + /** A DFA state represents a set of possible ATN configurations. + * As Aho, Sethi, Ullman p. 117 says "The DFA uses its state + * to keep track of all possible states the ATN can be in after + * reading each input symbol. That is to say, after reading + * input a1a2..an, the DFA is in a state that represents the + * subset T of the states of the ATN that are reachable from the + * ATN's start state along some path labeled a1a2..an." + * In conventional NFA→DFA conversion, therefore, the subset T + * would be a bitset representing the set of states the + * ATN could be in. We need to track the alt predicted by each + * state as well, however. More importantly, we need to maintain + * a stack of states, tracking the closure operations as they + * jump from rule to rule, emulating rule invocations (method calls). + * I have to add a stack to simulate the proper lookahead sequences for + * the underlying LL grammar from which the ATN was derived. + * + * I use a set of ATNConfig objects not simple states. An ATNConfig + * is both a state (ala normal conversion) and a RuleContext describing + * the chain of rules (if any) followed to arrive at that state. + * + * A DFA state may have multiple references to a particular state, + * but with different ATN contexts (with same or different alts) + * meaning that state was reached via a different set of rule invocations. + */ + let DFAState$1 = class DFAState { + /** + * Constructs a new `DFAState`. + * + * @param configs The set of ATN configurations defining this state. + */ + constructor(configs) { + this.stateNumber = -1; + this.configs = configs; + this.edges = new Map(); + this.contextEdges = new Map(); + } + get isContextSensitive() { + return !!this.contextSymbols; + } + isContextSymbol(symbol) { + if (!this.isContextSensitive) { + return false; + } + return this.contextSymbols.get(symbol); + } + setContextSymbol(symbol) { + assert(this.isContextSensitive); + this.contextSymbols.set(symbol); + } + setContextSensitive(atn) { + assert(!this.configs.isOutermostConfigSet); + if (this.isContextSensitive) { + return; + } + if (!this.contextSymbols) { + this.contextSymbols = new BitSet_1.BitSet(); + } + } + get acceptStateInfo() { + return this._acceptStateInfo; + } + set acceptStateInfo(acceptStateInfo) { + this._acceptStateInfo = acceptStateInfo; + } + get isAcceptState() { + return !!this._acceptStateInfo; + } + get prediction() { + if (!this._acceptStateInfo) { + return ATN_1.ATN.INVALID_ALT_NUMBER; + } + return this._acceptStateInfo.prediction; + } + get lexerActionExecutor() { + if (!this._acceptStateInfo) { + return undefined; + } + return this._acceptStateInfo.lexerActionExecutor; + } + getTarget(symbol) { + return this.edges.get(symbol); + } + setTarget(symbol, target) { + this.edges.set(symbol, target); + } + getEdgeMap() { + return this.edges; + } + getContextTarget(invokingState) { + if (invokingState === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + invokingState = -1; + } + return this.contextEdges.get(invokingState); + } + setContextTarget(invokingState, target) { + if (!this.isContextSensitive) { + throw new Error("The state is not context sensitive."); + } + if (invokingState === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + invokingState = -1; + } + this.contextEdges.set(invokingState, target); + } + getContextEdgeMap() { + let map = new Map(this.contextEdges); + let existing = map.get(-1); + if (existing !== undefined) { + if (map.size === 1) { + let result = new Map(); + result.set(PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY, existing); + return result; + } + else { + map.delete(-1); + map.set(PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY, existing); + } + } + return map; + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(7); + hash = MurmurHash_1.MurmurHash.update(hash, this.configs.hashCode()); + hash = MurmurHash_1.MurmurHash.finish(hash, 1); + return hash; + } + /** + * Two {@link DFAState} instances are equal if their ATN configuration sets + * are the same. This method is used to see if a state already exists. + * + * Because the number of alternatives and number of ATN configurations are + * finite, there is a finite number of DFA states that can be processed. + * This is necessary to show that the algorithm terminates. + * + * Cannot test the DFA state numbers here because in + * {@link ParserATNSimulator#addDFAState} we need to know if any other state + * exists that has this exact set of ATN configurations. The + * {@link #stateNumber} is irrelevant. + */ + equals(o) { + // compare set of ATN configurations in this set with other + if (this === o) { + return true; + } + if (!(o instanceof DFAState)) { + return false; + } + let other = o; + let sameSet = this.configs.equals(other.configs); + // System.out.println("DFAState.equals: "+configs+(sameSet?"==":"!=")+other.configs); + return sameSet; + } + toString() { + let buf = ""; + buf += (this.stateNumber) + (":") + (this.configs); + if (this.isAcceptState) { + buf += ("=>"); + if (this.predicates) { + buf += this.predicates; + } + else { + buf += (this.prediction); + } + } + return buf.toString(); + } + }; + __decorate([ + Decorators_1.NotNull + ], DFAState$1.prototype, "configs", void 0); + __decorate([ + Decorators_1.NotNull + ], DFAState$1.prototype, "edges", void 0); + __decorate([ + Decorators_1.NotNull + ], DFAState$1.prototype, "contextEdges", void 0); + __decorate([ + Decorators_1.Override + ], DFAState$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], DFAState$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], DFAState$1.prototype, "toString", null); + exports.DFAState = DFAState$1; + (function (DFAState) { + /** Map a predicate to a predicted alternative. */ + let PredPrediction = class PredPrediction { + constructor(pred, alt) { + this.alt = alt; + this.pred = pred; + } + toString() { + return "(" + this.pred + ", " + this.alt + ")"; + } + }; + __decorate([ + Decorators_1.NotNull + ], PredPrediction.prototype, "pred", void 0); + __decorate([ + Decorators_1.Override + ], PredPrediction.prototype, "toString", null); + PredPrediction = __decorate([ + __param(0, Decorators_1.NotNull) + ], PredPrediction); + DFAState.PredPrediction = PredPrediction; + })(DFAState$1 = exports.DFAState || (exports.DFAState = {})); + + } (DFAState)); + return DFAState; +} + +var hasRequiredATNSimulator; + +function requireATNSimulator () { + if (hasRequiredATNSimulator) return ATNSimulator; + hasRequiredATNSimulator = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNSimulator && ATNSimulator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ATNSimulator && ATNSimulator.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATNSimulator = void 0; + const ATNConfigSet_1 = requireATNConfigSet(); + const DFAState_1 = requireDFAState(); + const Decorators_1 = requireDecorators(); + const PredictionContext_1 = requirePredictionContext(); + let ATNSimulator$1 = class ATNSimulator { + constructor(atn) { + this.atn = atn; + } + static get ERROR() { + if (!ATNSimulator._ERROR) { + ATNSimulator._ERROR = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet()); + ATNSimulator._ERROR.stateNumber = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY; + } + return ATNSimulator._ERROR; + } + /** + * Clear the DFA cache used by the current instance. Since the DFA cache may + * be shared by multiple ATN simulators, this method may affect the + * performance (but not accuracy) of other parsers which are being used + * concurrently. + * + * @ if the current instance does not + * support clearing the DFA. + * + * @since 4.3 + */ + clearDFA() { + this.atn.clearDFA(); + } + }; + __decorate([ + Decorators_1.NotNull + ], ATNSimulator$1.prototype, "atn", void 0); + __decorate([ + Decorators_1.NotNull + ], ATNSimulator$1, "ERROR", null); + ATNSimulator$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ATNSimulator$1); + exports.ATNSimulator = ATNSimulator$1; + (function (ATNSimulator) { + })(ATNSimulator$1 = exports.ATNSimulator || (exports.ATNSimulator = {})); + exports.ATNSimulator = ATNSimulator$1; + + } (ATNSimulator)); + return ATNSimulator; +} + +var Recognizer = {}; + +var ConsoleErrorListener = {}; + +var hasRequiredConsoleErrorListener; + +function requireConsoleErrorListener () { + if (hasRequiredConsoleErrorListener) return ConsoleErrorListener; + hasRequiredConsoleErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ConsoleErrorListener, "__esModule", { value: true }); + ConsoleErrorListener.ConsoleErrorListener = void 0; + /** + * + * @author Sam Harwell + */ + let ConsoleErrorListener$1 = class ConsoleErrorListener { + /** + * {@inheritDoc} + * + * This implementation prints messages to {@link System#err} containing the + * values of `line`, `charPositionInLine`, and `msg` using + * the following format. + * + *
+	     * line *line*:*charPositionInLine* *msg*
+	     * 
+ */ + syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) { + console.error(`line ${line}:${charPositionInLine} ${msg}`); + } + }; + ConsoleErrorListener.ConsoleErrorListener = ConsoleErrorListener$1; + /** + * Provides a default instance of {@link ConsoleErrorListener}. + */ + ConsoleErrorListener$1.INSTANCE = new ConsoleErrorListener$1(); + + return ConsoleErrorListener; +} + +var ProxyErrorListener = {}; + +var hasRequiredProxyErrorListener; + +function requireProxyErrorListener () { + if (hasRequiredProxyErrorListener) return ProxyErrorListener; + hasRequiredProxyErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ProxyErrorListener && ProxyErrorListener.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ProxyErrorListener && ProxyErrorListener.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ProxyErrorListener, "__esModule", { value: true }); + ProxyErrorListener.ProxyErrorListener = void 0; + const Decorators_1 = requireDecorators(); + /** + * This implementation of {@link ANTLRErrorListener} dispatches all calls to a + * collection of delegate listeners. This reduces the effort required to support multiple + * listeners. + * + * @author Sam Harwell + */ + let ProxyErrorListener$1 = class ProxyErrorListener { + constructor(delegates) { + this.delegates = delegates; + if (!delegates) { + throw new Error("Invalid delegates"); + } + } + getDelegates() { + return this.delegates; + } + syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) { + this.delegates.forEach((listener) => { + if (listener.syntaxError) { + listener.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e); + } + }); + } + }; + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull), + __param(4, Decorators_1.NotNull) + ], ProxyErrorListener$1.prototype, "syntaxError", null); + ProxyErrorListener.ProxyErrorListener = ProxyErrorListener$1; + + return ProxyErrorListener; +} + +var hasRequiredRecognizer; + +function requireRecognizer () { + if (hasRequiredRecognizer) return Recognizer; + hasRequiredRecognizer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Recognizer && Recognizer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (Recognizer && Recognizer.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(Recognizer, "__esModule", { value: true }); + Recognizer.Recognizer = void 0; + const ConsoleErrorListener_1 = requireConsoleErrorListener(); + const ProxyErrorListener_1 = requireProxyErrorListener(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + const Utils = requireUtils(); + let Recognizer$1 = class Recognizer { + constructor() { + this._listeners = [ConsoleErrorListener_1.ConsoleErrorListener.INSTANCE]; + this._stateNumber = -1; + } + /** + * Get a map from token names to token types. + * + * Used for XPath and tree pattern compilation. + */ + getTokenTypeMap() { + let vocabulary = this.vocabulary; + let result = Recognizer.tokenTypeMapCache.get(vocabulary); + if (result == null) { + let intermediateResult = new Map(); + for (let i = 0; i <= this.atn.maxTokenType; i++) { + let literalName = vocabulary.getLiteralName(i); + if (literalName != null) { + intermediateResult.set(literalName, i); + } + let symbolicName = vocabulary.getSymbolicName(i); + if (symbolicName != null) { + intermediateResult.set(symbolicName, i); + } + } + intermediateResult.set("EOF", Token_1.Token.EOF); + result = intermediateResult; + Recognizer.tokenTypeMapCache.set(vocabulary, result); + } + return result; + } + /** + * Get a map from rule names to rule indexes. + * + * Used for XPath and tree pattern compilation. + */ + getRuleIndexMap() { + let ruleNames = this.ruleNames; + if (ruleNames == null) { + throw new Error("The current recognizer does not provide a list of rule names."); + } + let result = Recognizer.ruleIndexMapCache.get(ruleNames); + if (result == null) { + result = Utils.toMap(ruleNames); + Recognizer.ruleIndexMapCache.set(ruleNames, result); + } + return result; + } + getTokenType(tokenName) { + let ttype = this.getTokenTypeMap().get(tokenName); + if (ttype != null) { + return ttype; + } + return Token_1.Token.INVALID_TYPE; + } + /** + * If this recognizer was generated, it will have a serialized ATN + * representation of the grammar. + * + * For interpreters, we don't know their serialized ATN despite having + * created the interpreter from it. + */ + get serializedATN() { + throw new Error("there is no serialized ATN"); + } + /** + * Get the {@link ATN} used by the recognizer for prediction. + * + * @returns The {@link ATN} used by the recognizer for prediction. + */ + get atn() { + return this._interp.atn; + } + /** + * Get the ATN interpreter used by the recognizer for prediction. + * + * @returns The ATN interpreter used by the recognizer for prediction. + */ + get interpreter() { + return this._interp; + } + /** + * Set the ATN interpreter used by the recognizer for prediction. + * + * @param interpreter The ATN interpreter used by the recognizer for + * prediction. + */ + set interpreter(interpreter) { + this._interp = interpreter; + } + /** If profiling during the parse/lex, this will return DecisionInfo records + * for each decision in recognizer in a ParseInfo object. + * + * @since 4.3 + */ + get parseInfo() { + return Promise.resolve(undefined); + } + /** What is the error header, normally line/character position information? */ + getErrorHeader(e) { + let token = e.getOffendingToken(); + if (!token) { + return ""; + } + let line = token.line; + let charPositionInLine = token.charPositionInLine; + return "line " + line + ":" + charPositionInLine; + } + /** + * @exception NullPointerException if `listener` is `undefined`. + */ + addErrorListener(listener) { + if (!listener) { + throw new TypeError("listener must not be null"); + } + this._listeners.push(listener); + } + removeErrorListener(listener) { + let position = this._listeners.indexOf(listener); + if (position !== -1) { + this._listeners.splice(position, 1); + } + } + removeErrorListeners() { + this._listeners.length = 0; + } + getErrorListeners() { + return this._listeners.slice(0); + } + getErrorListenerDispatch() { + return new ProxyErrorListener_1.ProxyErrorListener(this.getErrorListeners()); + } + // subclass needs to override these if there are sempreds or actions + // that the ATN interp needs to execute + sempred(_localctx, ruleIndex, actionIndex) { + return true; + } + precpred(localctx, precedence) { + return true; + } + action(_localctx, ruleIndex, actionIndex) { + // intentionally empty + } + get state() { + return this._stateNumber; + } + /** Indicate that the recognizer has changed internal state that is + * consistent with the ATN state passed in. This way we always know + * where we are in the ATN as the parser goes along. The rule + * context objects form a stack that lets us see the stack of + * invoking rules. Combine this and we have complete ATN + * configuration information. + */ + set state(atnState) { + // System.err.println("setState "+atnState); + this._stateNumber = atnState; + // if ( traceATNStates ) _ctx.trace(atnState); + } + }; + Recognizer$1.EOF = -1; + Recognizer$1.tokenTypeMapCache = new WeakMap(); + Recognizer$1.ruleIndexMapCache = new WeakMap(); + __decorate([ + Decorators_1.SuppressWarnings("serial"), + Decorators_1.NotNull + ], Recognizer$1.prototype, "_listeners", void 0); + __decorate([ + Decorators_1.NotNull + ], Recognizer$1.prototype, "getTokenTypeMap", null); + __decorate([ + Decorators_1.NotNull + ], Recognizer$1.prototype, "getRuleIndexMap", null); + __decorate([ + Decorators_1.NotNull + ], Recognizer$1.prototype, "serializedATN", null); + __decorate([ + Decorators_1.NotNull + ], Recognizer$1.prototype, "atn", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], Recognizer$1.prototype, "interpreter", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], Recognizer$1.prototype, "getErrorHeader", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], Recognizer$1.prototype, "addErrorListener", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], Recognizer$1.prototype, "removeErrorListener", null); + __decorate([ + Decorators_1.NotNull + ], Recognizer$1.prototype, "getErrorListeners", null); + Recognizer.Recognizer = Recognizer$1; + + return Recognizer; +} + +var VocabularyImpl = {}; + +var hasRequiredVocabularyImpl; + +function requireVocabularyImpl () { + if (hasRequiredVocabularyImpl) return VocabularyImpl; + hasRequiredVocabularyImpl = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (VocabularyImpl && VocabularyImpl.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(VocabularyImpl, "__esModule", { value: true }); + VocabularyImpl.VocabularyImpl = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:59.5829654-07:00 + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * This class provides a default implementation of the {@link Vocabulary} + * interface. + * + * @author Sam Harwell + */ + let VocabularyImpl$1 = class VocabularyImpl { + /** + * Constructs a new instance of {@link VocabularyImpl} from the specified + * literal, symbolic, and display token names. + * + * @param literalNames The literal names assigned to tokens, or an empty array + * if no literal names are assigned. + * @param symbolicNames The symbolic names assigned to tokens, or + * an empty array if no symbolic names are assigned. + * @param displayNames The display names assigned to tokens, or an empty array + * to use the values in `literalNames` and `symbolicNames` as + * the source of display names, as described in + * {@link #getDisplayName(int)}. + * + * @see #getLiteralName(int) + * @see #getSymbolicName(int) + * @see #getDisplayName(int) + */ + constructor(literalNames, symbolicNames, displayNames) { + this.literalNames = literalNames; + this.symbolicNames = symbolicNames; + this.displayNames = displayNames; + // See note here on -1 part: https://github.com/antlr/antlr4/pull/1146 + this._maxTokenType = + Math.max(this.displayNames.length, Math.max(this.literalNames.length, this.symbolicNames.length)) - 1; + } + get maxTokenType() { + return this._maxTokenType; + } + getLiteralName(tokenType) { + if (tokenType >= 0 && tokenType < this.literalNames.length) { + return this.literalNames[tokenType]; + } + return undefined; + } + getSymbolicName(tokenType) { + if (tokenType >= 0 && tokenType < this.symbolicNames.length) { + return this.symbolicNames[tokenType]; + } + if (tokenType === Token_1.Token.EOF) { + return "EOF"; + } + return undefined; + } + getDisplayName(tokenType) { + if (tokenType >= 0 && tokenType < this.displayNames.length) { + let displayName = this.displayNames[tokenType]; + if (displayName) { + return displayName; + } + } + let literalName = this.getLiteralName(tokenType); + if (literalName) { + return literalName; + } + let symbolicName = this.getSymbolicName(tokenType); + if (symbolicName) { + return symbolicName; + } + return String(tokenType); + } + }; + /** + * Gets an empty {@link Vocabulary} instance. + * + * No literal or symbol names are assigned to token types, so + * {@link #getDisplayName(int)} returns the numeric value for all tokens + * except {@link Token#EOF}. + */ + VocabularyImpl$1.EMPTY_VOCABULARY = new VocabularyImpl$1([], [], []); + __decorate([ + Decorators_1.NotNull + ], VocabularyImpl$1.prototype, "literalNames", void 0); + __decorate([ + Decorators_1.NotNull + ], VocabularyImpl$1.prototype, "symbolicNames", void 0); + __decorate([ + Decorators_1.NotNull + ], VocabularyImpl$1.prototype, "displayNames", void 0); + __decorate([ + Decorators_1.Override + ], VocabularyImpl$1.prototype, "maxTokenType", null); + __decorate([ + Decorators_1.Override + ], VocabularyImpl$1.prototype, "getLiteralName", null); + __decorate([ + Decorators_1.Override + ], VocabularyImpl$1.prototype, "getSymbolicName", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], VocabularyImpl$1.prototype, "getDisplayName", null); + __decorate([ + Decorators_1.NotNull + ], VocabularyImpl$1, "EMPTY_VOCABULARY", void 0); + VocabularyImpl.VocabularyImpl = VocabularyImpl$1; + + return VocabularyImpl; +} + +var hasRequiredDFASerializer; + +function requireDFASerializer () { + if (hasRequiredDFASerializer) return DFASerializer; + hasRequiredDFASerializer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DFASerializer && DFASerializer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(DFASerializer, "__esModule", { value: true }); + DFASerializer.DFASerializer = void 0; + const ATNSimulator_1 = requireATNSimulator(); + const Decorators_1 = requireDecorators(); + const PredictionContext_1 = requirePredictionContext(); + const Recognizer_1 = requireRecognizer(); + const VocabularyImpl_1 = requireVocabularyImpl(); + /** A DFA walker that knows how to dump them to serialized strings. */ + let DFASerializer$1 = class DFASerializer { + constructor(dfa, vocabulary, ruleNames, atn) { + if (vocabulary instanceof Recognizer_1.Recognizer) { + ruleNames = vocabulary.ruleNames; + atn = vocabulary.atn; + vocabulary = vocabulary.vocabulary; + } + else if (!vocabulary) { + vocabulary = VocabularyImpl_1.VocabularyImpl.EMPTY_VOCABULARY; + } + this.dfa = dfa; + this.vocabulary = vocabulary; + this.ruleNames = ruleNames; + this.atn = atn; + } + toString() { + if (!this.dfa.s0) { + return ""; + } + let buf = ""; + if (this.dfa.states) { + let states = new Array(...this.dfa.states.toArray()); + states.sort((o1, o2) => o1.stateNumber - o2.stateNumber); + for (let s of states) { + let edges = s.getEdgeMap(); + let edgeKeys = [...edges.keys()].sort((a, b) => a - b); + let contextEdges = s.getContextEdgeMap(); + let contextEdgeKeys = [...contextEdges.keys()].sort((a, b) => a - b); + for (let entry of edgeKeys) { + let value = edges.get(entry); + if ((value == null || value === ATNSimulator_1.ATNSimulator.ERROR) && !s.isContextSymbol(entry)) { + continue; + } + let contextSymbol = false; + buf += (this.getStateString(s)) + ("-") + (this.getEdgeLabel(entry)) + ("->"); + if (s.isContextSymbol(entry)) { + buf += ("!"); + contextSymbol = true; + } + let t = value; + if (t && t.stateNumber !== ATNSimulator_1.ATNSimulator.ERROR.stateNumber) { + buf += (this.getStateString(t)) + ("\n"); + } + else if (contextSymbol) { + buf += ("ctx\n"); + } + } + if (s.isContextSensitive) { + for (let entry of contextEdgeKeys) { + buf += (this.getStateString(s)) + + ("-") + + (this.getContextLabel(entry)) + + ("->") + + (this.getStateString(contextEdges.get(entry))) + + ("\n"); + } + } + } + } + let output = buf; + if (output.length === 0) { + return ""; + } + //return Utils.sortLinesInString(output); + return output; + } + getContextLabel(i) { + if (i === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + return "ctx:EMPTY_FULL"; + } + else if (i === PredictionContext_1.PredictionContext.EMPTY_LOCAL_STATE_KEY) { + return "ctx:EMPTY_LOCAL"; + } + if (this.atn && i > 0 && i <= this.atn.states.length) { + let state = this.atn.states[i]; + let ruleIndex = state.ruleIndex; + if (this.ruleNames && ruleIndex >= 0 && ruleIndex < this.ruleNames.length) { + return "ctx:" + String(i) + "(" + this.ruleNames[ruleIndex] + ")"; + } + } + return "ctx:" + String(i); + } + getEdgeLabel(i) { + return this.vocabulary.getDisplayName(i); + } + getStateString(s) { + if (s === ATNSimulator_1.ATNSimulator.ERROR) { + return "ERROR"; + } + let n = s.stateNumber; + let stateStr = "s" + n; + if (s.isAcceptState) { + if (s.predicates) { + stateStr = ":s" + n + "=>" + s.predicates; + } + else { + stateStr = ":s" + n + "=>" + s.prediction; + } + } + if (s.isContextSensitive) { + stateStr += "*"; + for (let config of s.configs) { + if (config.reachesIntoOuterContext) { + stateStr += "*"; + break; + } + } + } + return stateStr; + } + }; + __decorate([ + Decorators_1.NotNull + ], DFASerializer$1.prototype, "dfa", void 0); + __decorate([ + Decorators_1.NotNull + ], DFASerializer$1.prototype, "vocabulary", void 0); + __decorate([ + Decorators_1.Override + ], DFASerializer$1.prototype, "toString", null); + DFASerializer.DFASerializer = DFASerializer$1; + + return DFASerializer; +} + +var LexerDFASerializer = {}; + +var hasRequiredLexerDFASerializer; + +function requireLexerDFASerializer () { + if (hasRequiredLexerDFASerializer) return LexerDFASerializer; + hasRequiredLexerDFASerializer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerDFASerializer && LexerDFASerializer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerDFASerializer && LexerDFASerializer.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerDFASerializer, "__esModule", { value: true }); + LexerDFASerializer.LexerDFASerializer = void 0; + const DFASerializer_1 = requireDFASerializer(); + const Decorators_1 = requireDecorators(); + const VocabularyImpl_1 = requireVocabularyImpl(); + let LexerDFASerializer$1 = class LexerDFASerializer extends DFASerializer_1.DFASerializer { + constructor(dfa) { + super(dfa, VocabularyImpl_1.VocabularyImpl.EMPTY_VOCABULARY); + } + getEdgeLabel(i) { + return "'" + String.fromCodePoint(i) + "'"; + } + }; + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], LexerDFASerializer$1.prototype, "getEdgeLabel", null); + LexerDFASerializer$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerDFASerializer$1); + LexerDFASerializer.LexerDFASerializer = LexerDFASerializer$1; + + return LexerDFASerializer; +} + +var StarLoopEntryState = {}; + +var hasRequiredStarLoopEntryState; + +function requireStarLoopEntryState () { + if (hasRequiredStarLoopEntryState) return StarLoopEntryState; + hasRequiredStarLoopEntryState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (StarLoopEntryState && StarLoopEntryState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(StarLoopEntryState, "__esModule", { value: true }); + StarLoopEntryState.StarLoopEntryState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:37.7099201-07:00 + const ATNStateType_1 = requireATNStateType(); + const BitSet_1 = requireBitSet(); + const DecisionState_1 = requireDecisionState(); + const Decorators_1 = requireDecorators(); + let StarLoopEntryState$1 = class StarLoopEntryState extends DecisionState_1.DecisionState { + constructor() { + super(...arguments); + /** + * Indicates whether this state can benefit from a precedence DFA during SLL + * decision making. + * + * This is a computed property that is calculated during ATN deserialization + * and stored for use in {@link ParserATNSimulator} and + * {@link ParserInterpreter}. + * + * @see `DFA.isPrecedenceDfa` + */ + this.precedenceRuleDecision = false; + /** + * For precedence decisions, this set marks states *S* which have all + * of the following characteristics: + * + * * One or more invocation sites of the current rule returns to + * *S*. + * * The closure from *S* includes the current decision without + * passing through any rule invocations or stepping out of the current + * rule. + * + * This field is not used when {@link #precedenceRuleDecision} is + * `false`. + */ + this.precedenceLoopbackStates = new BitSet_1.BitSet(); + } + get stateType() { + return ATNStateType_1.ATNStateType.STAR_LOOP_ENTRY; + } + }; + __decorate([ + Decorators_1.Override + ], StarLoopEntryState$1.prototype, "stateType", null); + StarLoopEntryState.StarLoopEntryState = StarLoopEntryState$1; + + return StarLoopEntryState; +} + +var hasRequiredDFA; + +function requireDFA () { + if (hasRequiredDFA) return DFA; + hasRequiredDFA = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DFA && DFA.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (DFA && DFA.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(DFA, "__esModule", { value: true }); + DFA.DFA = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:38.3567094-07:00 + const Array2DHashSet_1 = requireArray2DHashSet(); + const ATNConfigSet_1 = requireATNConfigSet(); + const DFASerializer_1 = requireDFASerializer(); + const DFAState_1 = requireDFAState(); + const LexerDFASerializer_1 = requireLexerDFASerializer(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const StarLoopEntryState_1 = requireStarLoopEntryState(); + const VocabularyImpl_1 = requireVocabularyImpl(); + let DFA$1 = class DFA { + constructor(atnStartState, decision = 0) { + /** + * A set of all states in the `DFA`. + * + * Note that this collection of states holds the DFA states for both SLL and LL prediction. Only the start state + * needs to be differentiated for these cases, which is tracked by the `s0` and `s0full` fields. + */ + this.states = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + this.nextStateNumber = 0; + if (!atnStartState.atn) { + throw new Error("The ATNState must be associated with an ATN"); + } + this.atnStartState = atnStartState; + this.atn = atnStartState.atn; + this.decision = decision; + // Precedence DFAs are associated with the special precedence decision created for left-recursive rules which + // evaluate their alternatives using a precedence hierarchy. When such a decision is encountered, we mark this + // DFA instance as a precedence DFA and initialize the initial states s0 and s0full to special DFAState + // instances which use outgoing edges to link to the actual start state used for each precedence level. + let isPrecedenceDfa = false; + if (atnStartState instanceof StarLoopEntryState_1.StarLoopEntryState) { + if (atnStartState.precedenceRuleDecision) { + isPrecedenceDfa = true; + this.s0 = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet()); + this.s0full = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet()); + } + } + this.precedenceDfa = isPrecedenceDfa; + } + /** + * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special + * start state {@link #s0} which is not stored in {@link #states}. The + * {@link DFAState#edges} array for this start state contains outgoing edges + * supplying individual start states corresponding to specific precedence + * values. + * + * @returns `true` if this is a precedence DFA; otherwise, + * `false`. + * @see Parser.precedence + */ + get isPrecedenceDfa() { + return this.precedenceDfa; + } + /** + * Get the start state for a specific precedence value. + * + * @param precedence The current precedence. + * @returns The start state corresponding to the specified precedence, or + * `undefined` if no start state exists for the specified precedence. + * + * @ if this is not a precedence DFA. + * @see `isPrecedenceDfa` + */ + getPrecedenceStartState(precedence, fullContext) { + if (!this.isPrecedenceDfa) { + throw new Error("Only precedence DFAs may contain a precedence start state."); + } + // s0 and s0full are never null for a precedence DFA + if (fullContext) { + return this.s0full.getTarget(precedence); + } + else { + return this.s0.getTarget(precedence); + } + } + /** + * Set the start state for a specific precedence value. + * + * @param precedence The current precedence. + * @param startState The start state corresponding to the specified + * precedence. + * + * @ if this is not a precedence DFA. + * @see `isPrecedenceDfa` + */ + setPrecedenceStartState(precedence, fullContext, startState) { + if (!this.isPrecedenceDfa) { + throw new Error("Only precedence DFAs may contain a precedence start state."); + } + if (precedence < 0) { + return; + } + if (fullContext) { + // s0full is never null for a precedence DFA + this.s0full.setTarget(precedence, startState); + } + else { + // s0 is never null for a precedence DFA + this.s0.setTarget(precedence, startState); + } + } + get isEmpty() { + if (this.isPrecedenceDfa) { + // s0 and s0full are never null for a precedence DFA + return this.s0.getEdgeMap().size === 0 && this.s0full.getEdgeMap().size === 0; + } + return this.s0 == null && this.s0full == null; + } + get isContextSensitive() { + if (this.isPrecedenceDfa) { + // s0full is never null for a precedence DFA + return this.s0full.getEdgeMap().size > 0; + } + return this.s0full != null; + } + addState(state) { + state.stateNumber = this.nextStateNumber++; + return this.states.getOrAdd(state); + } + toString(vocabulary, ruleNames) { + if (!vocabulary) { + vocabulary = VocabularyImpl_1.VocabularyImpl.EMPTY_VOCABULARY; + } + if (!this.s0) { + return ""; + } + let serializer; + if (ruleNames) { + serializer = new DFASerializer_1.DFASerializer(this, vocabulary, ruleNames, this.atnStartState.atn); + } + else { + serializer = new DFASerializer_1.DFASerializer(this, vocabulary); + } + return serializer.toString(); + } + toLexerString() { + if (!this.s0) { + return ""; + } + let serializer = new LexerDFASerializer_1.LexerDFASerializer(this); + return serializer.toString(); + } + }; + __decorate([ + Decorators_1.NotNull + ], DFA$1.prototype, "states", void 0); + __decorate([ + Decorators_1.NotNull + ], DFA$1.prototype, "atnStartState", void 0); + __decorate([ + Decorators_1.NotNull + ], DFA$1.prototype, "atn", void 0); + DFA$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], DFA$1); + DFA.DFA = DFA$1; + + return DFA; +} + +var InvalidState = {}; + +var BasicState = {}; + +var hasRequiredBasicState; + +function requireBasicState () { + if (hasRequiredBasicState) return BasicState; + hasRequiredBasicState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (BasicState && BasicState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(BasicState, "__esModule", { value: true }); + BasicState.BasicState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:27.8389930-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + /** + * + * @author Sam Harwell + */ + let BasicState$1 = class BasicState extends ATNState_1.ATNState { + get stateType() { + return ATNStateType_1.ATNStateType.BASIC; + } + }; + __decorate([ + Decorators_1.Override + ], BasicState$1.prototype, "stateType", null); + BasicState.BasicState = BasicState$1; + + return BasicState; +} + +var hasRequiredInvalidState; + +function requireInvalidState () { + if (hasRequiredInvalidState) return InvalidState; + hasRequiredInvalidState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (InvalidState && InvalidState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(InvalidState, "__esModule", { value: true }); + InvalidState.InvalidState = void 0; + const ATNStateType_1 = requireATNStateType(); + const BasicState_1 = requireBasicState(); + const Decorators_1 = requireDecorators(); + /** + * + * @author Sam Harwell + */ + let InvalidState$1 = class InvalidState extends BasicState_1.BasicState { + get stateType() { + return ATNStateType_1.ATNStateType.INVALID_TYPE; + } + }; + __decorate([ + Decorators_1.Override + ], InvalidState$1.prototype, "stateType", null); + InvalidState.InvalidState = InvalidState$1; + + return InvalidState; +} + +var LL1Analyzer = {}; + +var NotSetTransition = {}; + +var SetTransition = {}; + +var hasRequiredSetTransition; + +function requireSetTransition () { + if (hasRequiredSetTransition) return SetTransition; + hasRequiredSetTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (SetTransition && SetTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (SetTransition && SetTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(SetTransition, "__esModule", { value: true }); + SetTransition.SetTransition = void 0; + const IntervalSet_1 = requireIntervalSet(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + const Transition_1 = requireTransition(); + /** A transition containing a set of values. */ + let SetTransition$1 = class SetTransition extends Transition_1.Transition { + // TODO (sam): should we really allow undefined here? + constructor(target, set) { + super(target); + if (set == null) { + set = IntervalSet_1.IntervalSet.of(Token_1.Token.INVALID_TYPE); + } + this.set = set; + } + get serializationType() { + return 7 /* SET */; + } + get label() { + return this.set; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return this.set.contains(symbol); + } + toString() { + return this.set.toString(); + } + }; + __decorate([ + Decorators_1.NotNull + ], SetTransition$1.prototype, "set", void 0); + __decorate([ + Decorators_1.Override + ], SetTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], SetTransition$1.prototype, "label", null); + __decorate([ + Decorators_1.Override + ], SetTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], SetTransition$1.prototype, "toString", null); + SetTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.Nullable) + ], SetTransition$1); + SetTransition.SetTransition = SetTransition$1; + + return SetTransition; +} + +var hasRequiredNotSetTransition; + +function requireNotSetTransition () { + if (hasRequiredNotSetTransition) return NotSetTransition; + hasRequiredNotSetTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (NotSetTransition && NotSetTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (NotSetTransition && NotSetTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(NotSetTransition, "__esModule", { value: true }); + NotSetTransition.NotSetTransition = void 0; + const Decorators_1 = requireDecorators(); + const SetTransition_1 = requireSetTransition(); + let NotSetTransition$1 = class NotSetTransition extends SetTransition_1.SetTransition { + constructor(target, set) { + super(target, set); + } + get serializationType() { + return 8 /* NOT_SET */; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return symbol >= minVocabSymbol + && symbol <= maxVocabSymbol + && !super.matches(symbol, minVocabSymbol, maxVocabSymbol); + } + toString() { + return "~" + super.toString(); + } + }; + __decorate([ + Decorators_1.Override + ], NotSetTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], NotSetTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override + ], NotSetTransition$1.prototype, "toString", null); + NotSetTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.Nullable) + ], NotSetTransition$1); + NotSetTransition.NotSetTransition = NotSetTransition$1; + + return NotSetTransition; +} + +var RuleStopState = {}; + +var hasRequiredRuleStopState; + +function requireRuleStopState () { + if (hasRequiredRuleStopState) return RuleStopState; + hasRequiredRuleStopState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleStopState && RuleStopState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(RuleStopState, "__esModule", { value: true }); + RuleStopState.RuleStopState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:36.7513856-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + /** The last node in the ATN for a rule, unless that rule is the start symbol. + * In that case, there is one transition to EOF. Later, we might encode + * references to all calls to this rule to compute FOLLOW sets for + * error handling. + */ + let RuleStopState$1 = class RuleStopState extends ATNState_1.ATNState { + get nonStopStateNumber() { + return -1; + } + get stateType() { + return ATNStateType_1.ATNStateType.RULE_STOP; + } + }; + __decorate([ + Decorators_1.Override + ], RuleStopState$1.prototype, "nonStopStateNumber", null); + __decorate([ + Decorators_1.Override + ], RuleStopState$1.prototype, "stateType", null); + RuleStopState.RuleStopState = RuleStopState$1; + + return RuleStopState; +} + +var RuleTransition = {}; + +var hasRequiredRuleTransition; + +function requireRuleTransition () { + if (hasRequiredRuleTransition) return RuleTransition; + hasRequiredRuleTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleTransition && RuleTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (RuleTransition && RuleTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(RuleTransition, "__esModule", { value: true }); + RuleTransition.RuleTransition = void 0; + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + /** */ + let RuleTransition$1 = class RuleTransition extends Transition_1.Transition { + constructor(ruleStart, ruleIndex, precedence, followState) { + super(ruleStart); + this.tailCall = false; + this.optimizedTailCall = false; + this.ruleIndex = ruleIndex; + this.precedence = precedence; + this.followState = followState; + } + get serializationType() { + return 3 /* RULE */; + } + get isEpsilon() { + return true; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return false; + } + }; + __decorate([ + Decorators_1.NotNull + ], RuleTransition$1.prototype, "followState", void 0); + __decorate([ + Decorators_1.Override + ], RuleTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], RuleTransition$1.prototype, "isEpsilon", null); + __decorate([ + Decorators_1.Override + ], RuleTransition$1.prototype, "matches", null); + RuleTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull), __param(3, Decorators_1.NotNull) + ], RuleTransition$1); + RuleTransition.RuleTransition = RuleTransition$1; + + return RuleTransition; +} + +var WildcardTransition = {}; + +var hasRequiredWildcardTransition; + +function requireWildcardTransition () { + if (hasRequiredWildcardTransition) return WildcardTransition; + hasRequiredWildcardTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (WildcardTransition && WildcardTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (WildcardTransition && WildcardTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(WildcardTransition, "__esModule", { value: true }); + WildcardTransition.WildcardTransition = void 0; + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + let WildcardTransition$1 = class WildcardTransition extends Transition_1.Transition { + constructor(target) { + super(target); + } + get serializationType() { + return 9 /* WILDCARD */; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return symbol >= minVocabSymbol && symbol <= maxVocabSymbol; + } + toString() { + return "."; + } + }; + __decorate([ + Decorators_1.Override + ], WildcardTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], WildcardTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], WildcardTransition$1.prototype, "toString", null); + WildcardTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], WildcardTransition$1); + WildcardTransition.WildcardTransition = WildcardTransition$1; + + return WildcardTransition; +} + +var hasRequiredLL1Analyzer; + +function requireLL1Analyzer () { + if (hasRequiredLL1Analyzer) return LL1Analyzer; + hasRequiredLL1Analyzer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LL1Analyzer && LL1Analyzer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LL1Analyzer && LL1Analyzer.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LL1Analyzer, "__esModule", { value: true }); + LL1Analyzer.LL1Analyzer = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:30.4445360-07:00 + const AbstractPredicateTransition_1 = requireAbstractPredicateTransition(); + const Array2DHashSet_1 = requireArray2DHashSet(); + const ATNConfig_1 = requireATNConfig(); + const BitSet_1 = requireBitSet(); + const IntervalSet_1 = requireIntervalSet(); + const Decorators_1 = requireDecorators(); + const NotSetTransition_1 = requireNotSetTransition(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const PredictionContext_1 = requirePredictionContext(); + const RuleStopState_1 = requireRuleStopState(); + const RuleTransition_1 = requireRuleTransition(); + const Token_1 = requireToken(); + const WildcardTransition_1 = requireWildcardTransition(); + let LL1Analyzer$1 = class LL1Analyzer { + constructor(atn) { this.atn = atn; } + /** + * Calculates the SLL(1) expected lookahead set for each outgoing transition + * of an {@link ATNState}. The returned array has one element for each + * outgoing transition in `s`. If the closure from transition + * *i* leads to a semantic predicate before matching a symbol, the + * element at index *i* of the result will be `undefined`. + * + * @param s the ATN state + * @returns the expected symbols for each outgoing transition of `s`. + */ + getDecisionLookahead(s) { + // System.out.println("LOOK("+s.stateNumber+")"); + if (s == null) { + return undefined; + } + let look = new Array(s.numberOfTransitions); + for (let alt = 0; alt < s.numberOfTransitions; alt++) { + let current = new IntervalSet_1.IntervalSet(); + look[alt] = current; + let lookBusy = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + let seeThruPreds = false; // fail to get lookahead upon pred + this._LOOK(s.transition(alt).target, undefined, PredictionContext_1.PredictionContext.EMPTY_LOCAL, current, lookBusy, new BitSet_1.BitSet(), seeThruPreds, false); + // Wipe out lookahead for this alternative if we found nothing + // or we had a predicate when we !seeThruPreds + if (current.size === 0 || current.contains(LL1Analyzer.HIT_PRED)) { + current = undefined; + look[alt] = current; + } + } + return look; + } + LOOK(s, ctx, stopState) { + if (stopState === undefined) { + if (s.atn == null) { + throw new Error("Illegal state"); + } + stopState = s.atn.ruleToStopState[s.ruleIndex]; + } + else if (stopState === null) { + // This is an explicit request to pass undefined as the stopState to _LOOK. Used to distinguish an overload + // from the method which simply omits the stopState parameter. + stopState = undefined; + } + let r = new IntervalSet_1.IntervalSet(); + let seeThruPreds = true; // ignore preds; get all lookahead + let addEOF = true; + this._LOOK(s, stopState, ctx, r, new Array2DHashSet_1.Array2DHashSet(), new BitSet_1.BitSet(), seeThruPreds, addEOF); + return r; + } + /** + * Compute set of tokens that can follow `s` in the ATN in the + * specified `ctx`. + *

+ * If `ctx` is {@link PredictionContext#EMPTY_LOCAL} and + * `stopState` or the end of the rule containing `s` is reached, + * {@link Token#EPSILON} is added to the result set. If `ctx` is not + * {@link PredictionContext#EMPTY_LOCAL} and `addEOF` is `true` + * and `stopState` or the end of the outermost rule is reached, + * {@link Token#EOF} is added to the result set. + * + * @param s the ATN state. + * @param stopState the ATN state to stop at. This can be a + * {@link BlockEndState} to detect epsilon paths through a closure. + * @param ctx The outer context, or {@link PredictionContext#EMPTY_LOCAL} if + * the outer context should not be used. + * @param look The result lookahead set. + * @param lookBusy A set used for preventing epsilon closures in the ATN + * from causing a stack overflow. Outside code should pass + * `new HashSet` for this argument. + * @param calledRuleStack A set used for preventing left recursion in the + * ATN from causing a stack overflow. Outside code should pass + * `new BitSet()` for this argument. + * @param seeThruPreds `true` to true semantic predicates as + * implicitly `true` and "see through them", otherwise `false` + * to treat semantic predicates as opaque and add {@link #HIT_PRED} to the + * result if one is encountered. + * @param addEOF Add {@link Token#EOF} to the result if the end of the + * outermost context is reached. This parameter has no effect if `ctx` + * is {@link PredictionContext#EMPTY_LOCAL}. + */ + _LOOK(s, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) { + // System.out.println("_LOOK("+s.stateNumber+", ctx="+ctx); + let c = ATNConfig_1.ATNConfig.create(s, 0, ctx); + if (!lookBusy.add(c)) { + return; + } + if (s === stopState) { + if (PredictionContext_1.PredictionContext.isEmptyLocal(ctx)) { + look.add(Token_1.Token.EPSILON); + return; + } + else if (ctx.isEmpty) { + if (addEOF) { + look.add(Token_1.Token.EOF); + } + return; + } + } + if (s instanceof RuleStopState_1.RuleStopState) { + if (ctx.isEmpty && !PredictionContext_1.PredictionContext.isEmptyLocal(ctx)) { + if (addEOF) { + look.add(Token_1.Token.EOF); + } + return; + } + let removed = calledRuleStack.get(s.ruleIndex); + try { + calledRuleStack.clear(s.ruleIndex); + for (let i = 0; i < ctx.size; i++) { + if (ctx.getReturnState(i) === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + continue; + } + let returnState = this.atn.states[ctx.getReturnState(i)]; + // System.out.println("popping back to "+retState); + this._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF); + } + } + finally { + if (removed) { + calledRuleStack.set(s.ruleIndex); + } + } + } + let n = s.numberOfTransitions; + for (let i = 0; i < n; i++) { + let t = s.transition(i); + if (t instanceof RuleTransition_1.RuleTransition) { + if (calledRuleStack.get(t.ruleIndex)) { + continue; + } + let newContext = ctx.getChild(t.followState.stateNumber); + try { + calledRuleStack.set(t.ruleIndex); + this._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF); + } + finally { + calledRuleStack.clear(t.ruleIndex); + } + } + else if (t instanceof AbstractPredicateTransition_1.AbstractPredicateTransition) { + if (seeThruPreds) { + this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF); + } + else { + look.add(LL1Analyzer.HIT_PRED); + } + } + else if (t.isEpsilon) { + this._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF); + } + else if (t instanceof WildcardTransition_1.WildcardTransition) { + look.addAll(IntervalSet_1.IntervalSet.of(Token_1.Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType)); + } + else { + // System.out.println("adding "+ t); + let set = t.label; + if (set != null) { + if (t instanceof NotSetTransition_1.NotSetTransition) { + set = set.complement(IntervalSet_1.IntervalSet.of(Token_1.Token.MIN_USER_TOKEN_TYPE, this.atn.maxTokenType)); + } + look.addAll(set); + } + } + } + } + }; + /** Special value added to the lookahead sets to indicate that we hit + * a predicate during analysis if `seeThruPreds==false`. + */ + LL1Analyzer$1.HIT_PRED = Token_1.Token.INVALID_TYPE; + __decorate([ + Decorators_1.NotNull + ], LL1Analyzer$1.prototype, "atn", void 0); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], LL1Analyzer$1.prototype, "LOOK", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull), + __param(4, Decorators_1.NotNull), + __param(5, Decorators_1.NotNull) + ], LL1Analyzer$1.prototype, "_LOOK", null); + LL1Analyzer$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], LL1Analyzer$1); + LL1Analyzer.LL1Analyzer = LL1Analyzer$1; + + return LL1Analyzer; +} + +var hasRequiredATN; + +function requireATN () { + if (hasRequiredATN) return ATN; + hasRequiredATN = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATN && ATN.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ATN && ATN.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATN = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:25.1063510-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const DFA_1 = requireDFA(); + const IntervalSet_1 = requireIntervalSet(); + const InvalidState_1 = requireInvalidState(); + const LL1Analyzer_1 = requireLL1Analyzer(); + const Decorators_1 = requireDecorators(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const PredictionContext_1 = requirePredictionContext(); + const Token_1 = requireToken(); + const assert = require$$0$9; + /** */ + let ATN$1 = class ATN { + /** Used for runtime deserialization of ATNs from strings */ + constructor(grammarType, maxTokenType) { + this.states = []; + /** Each subrule/rule is a decision point and we must track them so we + * can go back later and build DFA predictors for them. This includes + * all the rules, subrules, optional blocks, ()+, ()* etc... + */ + this.decisionToState = []; + this.modeNameToStartState = new Map(); + this.modeToStartState = []; + this.contextCache = new Array2DHashMap_1.Array2DHashMap(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + this.decisionToDFA = []; + this.modeToDFA = []; + this.LL1Table = new Map(); + this.grammarType = grammarType; + this.maxTokenType = maxTokenType; + } + clearDFA() { + this.decisionToDFA = new Array(this.decisionToState.length); + for (let i = 0; i < this.decisionToDFA.length; i++) { + this.decisionToDFA[i] = new DFA_1.DFA(this.decisionToState[i], i); + } + this.modeToDFA = new Array(this.modeToStartState.length); + for (let i = 0; i < this.modeToDFA.length; i++) { + this.modeToDFA[i] = new DFA_1.DFA(this.modeToStartState[i]); + } + this.contextCache.clear(); + this.LL1Table.clear(); + } + get contextCacheSize() { + return this.contextCache.size; + } + getCachedContext(context) { + return PredictionContext_1.PredictionContext.getCachedContext(context, this.contextCache, new PredictionContext_1.PredictionContext.IdentityHashMap()); + } + getDecisionToDFA() { + assert(this.decisionToDFA != null && this.decisionToDFA.length === this.decisionToState.length); + return this.decisionToDFA; + } + nextTokens(s, ctx) { + if (ctx) { + let anal = new LL1Analyzer_1.LL1Analyzer(this); + let next = anal.LOOK(s, ctx); + return next; + } + else { + if (s.nextTokenWithinRule) { + return s.nextTokenWithinRule; + } + s.nextTokenWithinRule = this.nextTokens(s, PredictionContext_1.PredictionContext.EMPTY_LOCAL); + s.nextTokenWithinRule.setReadonly(true); + return s.nextTokenWithinRule; + } + } + addState(state) { + state.atn = this; + state.stateNumber = this.states.length; + this.states.push(state); + } + removeState(state) { + // just replace the state, don't shift states in list + let invalidState = new InvalidState_1.InvalidState(); + invalidState.atn = this; + invalidState.stateNumber = state.stateNumber; + this.states[state.stateNumber] = invalidState; + } + defineMode(name, s) { + this.modeNameToStartState.set(name, s); + this.modeToStartState.push(s); + this.modeToDFA.push(new DFA_1.DFA(s)); + this.defineDecisionState(s); + } + defineDecisionState(s) { + this.decisionToState.push(s); + s.decision = this.decisionToState.length - 1; + this.decisionToDFA.push(new DFA_1.DFA(s, s.decision)); + return s.decision; + } + getDecisionState(decision) { + if (this.decisionToState.length > 0) { + return this.decisionToState[decision]; + } + return undefined; + } + get numberOfDecisions() { + return this.decisionToState.length; + } + /** + * Computes the set of input symbols which could follow ATN state number + * `stateNumber` in the specified full `context`. This method + * considers the complete parser context, but does not evaluate semantic + * predicates (i.e. all predicates encountered during the calculation are + * assumed true). If a path in the ATN exists from the starting state to the + * {@link RuleStopState} of the outermost context without matching any + * symbols, {@link Token#EOF} is added to the returned set. + * + * If `context` is `undefined`, it is treated as + * {@link ParserRuleContext#EMPTY}. + * + * Note that this does NOT give you the set of all tokens that could + * appear at a given token position in the input phrase. In other words, it + * does not answer: + * + * > Given a specific partial input phrase, return the set of all + * > tokens that can follow the last token in the input phrase. + * + * The big difference is that with just the input, the parser could land + * right in the middle of a lookahead decision. Getting all + * *possible* tokens given a partial input stream is a separate + * computation. See https://github.com/antlr/antlr4/issues/1428 + * + * For this function, we are specifying an ATN state and call stack to + * compute what token(s) can come next and specifically: outside of a + * lookahead decision. That is what you want for error reporting and + * recovery upon parse error. + * + * @param stateNumber the ATN state number + * @param context the full parse context + * @returns The set of potentially valid input symbols which could follow the + * specified state in the specified context. + * @ if the ATN does not contain a state with + * number `stateNumber` + */ + getExpectedTokens(stateNumber, context) { + if (stateNumber < 0 || stateNumber >= this.states.length) { + throw new RangeError("Invalid state number."); + } + let ctx = context; + let s = this.states[stateNumber]; + let following = this.nextTokens(s); + if (!following.contains(Token_1.Token.EPSILON)) { + return following; + } + let expected = new IntervalSet_1.IntervalSet(); + expected.addAll(following); + expected.remove(Token_1.Token.EPSILON); + while (ctx != null && ctx.invokingState >= 0 && following.contains(Token_1.Token.EPSILON)) { + let invokingState = this.states[ctx.invokingState]; + let rt = invokingState.transition(0); + following = this.nextTokens(rt.followState); + expected.addAll(following); + expected.remove(Token_1.Token.EPSILON); + ctx = ctx._parent; + } + if (following.contains(Token_1.Token.EPSILON)) { + expected.add(Token_1.Token.EOF); + } + return expected; + } + }; + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "states", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "decisionToState", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "modeNameToStartState", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "modeToStartState", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "decisionToDFA", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "modeToDFA", void 0); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "nextTokens", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ATN$1.prototype, "removeState", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ATN$1.prototype, "defineMode", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ATN$1.prototype, "defineDecisionState", null); + __decorate([ + Decorators_1.NotNull + ], ATN$1.prototype, "getExpectedTokens", null); + ATN$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ATN$1); + exports.ATN = ATN$1; + (function (ATN) { + ATN.INVALID_ALT_NUMBER = 0; + })(ATN$1 = exports.ATN || (exports.ATN = {})); + exports.ATN = ATN$1; + + } (ATN)); + return ATN; +} + +var LexerActionExecutor = {}; + +var LexerIndexedCustomAction = {}; + +var hasRequiredLexerIndexedCustomAction; + +function requireLexerIndexedCustomAction () { + if (hasRequiredLexerIndexedCustomAction) return LexerIndexedCustomAction; + hasRequiredLexerIndexedCustomAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerIndexedCustomAction && LexerIndexedCustomAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerIndexedCustomAction && LexerIndexedCustomAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerIndexedCustomAction, "__esModule", { value: true }); + LexerIndexedCustomAction.LexerIndexedCustomAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * This implementation of {@link LexerAction} is used for tracking input offsets + * for position-dependent actions within a {@link LexerActionExecutor}. + * + * This action is not serialized as part of the ATN, and is only required for + * position-dependent lexer actions which appear at a location other than the + * end of a rule. For more information about DFA optimizations employed for + * lexer actions, see {@link LexerActionExecutor#append} and + * {@link LexerActionExecutor#fixOffsetBeforeMatch}. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerIndexedCustomAction$1 = class LexerIndexedCustomAction { + /** + * Constructs a new indexed custom action by associating a character offset + * with a {@link LexerAction}. + * + * Note: This class is only required for lexer actions for which + * {@link LexerAction#isPositionDependent} returns `true`. + * + * @param offset The offset into the input {@link CharStream}, relative to + * the token start index, at which the specified lexer action should be + * executed. + * @param action The lexer action to execute at a particular offset in the + * input {@link CharStream}. + */ + constructor(offset, action) { + this._offset = offset; + this._action = action; + } + /** + * Gets the location in the input {@link CharStream} at which the lexer + * action should be executed. The value is interpreted as an offset relative + * to the token start index. + * + * @returns The location in the input {@link CharStream} at which the lexer + * action should be executed. + */ + get offset() { + return this._offset; + } + /** + * Gets the lexer action to execute. + * + * @returns A {@link LexerAction} object which executes the lexer action. + */ + get action() { + return this._action; + } + /** + * {@inheritDoc} + * + * @returns This method returns the result of calling {@link #getActionType} + * on the {@link LexerAction} returned by {@link #getAction}. + */ + get actionType() { + return this._action.actionType; + } + /** + * {@inheritDoc} + * @returns This method returns `true`. + */ + get isPositionDependent() { + return true; + } + /** + * {@inheritDoc} + * + * This method calls {@link #execute} on the result of {@link #getAction} + * using the provided `lexer`. + */ + execute(lexer) { + // assume the input stream position was properly set by the calling code + this._action.execute(lexer); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this._offset); + hash = MurmurHash_1.MurmurHash.update(hash, this._action); + return MurmurHash_1.MurmurHash.finish(hash, 2); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerIndexedCustomAction)) { + return false; + } + return this._offset === obj._offset + && this._action.equals(obj._action); + } + }; + __decorate([ + Decorators_1.NotNull + ], LexerIndexedCustomAction$1.prototype, "action", null); + __decorate([ + Decorators_1.Override + ], LexerIndexedCustomAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerIndexedCustomAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override + ], LexerIndexedCustomAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerIndexedCustomAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerIndexedCustomAction$1.prototype, "equals", null); + LexerIndexedCustomAction$1 = __decorate([ + __param(1, Decorators_1.NotNull) + ], LexerIndexedCustomAction$1); + LexerIndexedCustomAction.LexerIndexedCustomAction = LexerIndexedCustomAction$1; + + return LexerIndexedCustomAction; +} + +var hasRequiredLexerActionExecutor; + +function requireLexerActionExecutor () { + if (hasRequiredLexerActionExecutor) return LexerActionExecutor; + hasRequiredLexerActionExecutor = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerActionExecutor && LexerActionExecutor.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerActionExecutor && LexerActionExecutor.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerActionExecutor, "__esModule", { value: true }); + LexerActionExecutor.LexerActionExecutor = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:28.8810453-07:00 + const ArrayEqualityComparator_1 = requireArrayEqualityComparator(); + const LexerIndexedCustomAction_1 = requireLexerIndexedCustomAction(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Represents an executor for a sequence of lexer actions which traversed during + * the matching operation of a lexer rule (token). + * + * The executor tracks position information for position-dependent lexer actions + * efficiently, ensuring that actions appearing only at the end of the rule do + * not cause bloating of the {@link DFA} created for the lexer. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerActionExecutor$1 = class LexerActionExecutor { + /** + * Constructs an executor for a sequence of {@link LexerAction} actions. + * @param lexerActions The lexer actions to execute. + */ + constructor(lexerActions) { + this._lexerActions = lexerActions; + let hash = MurmurHash_1.MurmurHash.initialize(); + for (let lexerAction of lexerActions) { + hash = MurmurHash_1.MurmurHash.update(hash, lexerAction); + } + this.cachedHashCode = MurmurHash_1.MurmurHash.finish(hash, lexerActions.length); + } + /** + * Creates a {@link LexerActionExecutor} which executes the actions for + * the input `lexerActionExecutor` followed by a specified + * `lexerAction`. + * + * @param lexerActionExecutor The executor for actions already traversed by + * the lexer while matching a token within a particular + * {@link ATNConfig}. If this is `undefined`, the method behaves as though + * it were an empty executor. + * @param lexerAction The lexer action to execute after the actions + * specified in `lexerActionExecutor`. + * + * @returns A {@link LexerActionExecutor} for executing the combine actions + * of `lexerActionExecutor` and `lexerAction`. + */ + static append(lexerActionExecutor, lexerAction) { + if (!lexerActionExecutor) { + return new LexerActionExecutor([lexerAction]); + } + let lexerActions = lexerActionExecutor._lexerActions.slice(0); + lexerActions.push(lexerAction); + return new LexerActionExecutor(lexerActions); + } + /** + * Creates a {@link LexerActionExecutor} which encodes the current offset + * for position-dependent lexer actions. + * + * Normally, when the executor encounters lexer actions where + * {@link LexerAction#isPositionDependent} returns `true`, it calls + * {@link IntStream#seek} on the input {@link CharStream} to set the input + * position to the *end* of the current token. This behavior provides + * for efficient DFA representation of lexer actions which appear at the end + * of a lexer rule, even when the lexer rule matches a variable number of + * characters. + * + * Prior to traversing a match transition in the ATN, the current offset + * from the token start index is assigned to all position-dependent lexer + * actions which have not already been assigned a fixed offset. By storing + * the offsets relative to the token start index, the DFA representation of + * lexer actions which appear in the middle of tokens remains efficient due + * to sharing among tokens of the same length, regardless of their absolute + * position in the input stream. + * + * If the current executor already has offsets assigned to all + * position-dependent lexer actions, the method returns `this`. + * + * @param offset The current offset to assign to all position-dependent + * lexer actions which do not already have offsets assigned. + * + * @returns A {@link LexerActionExecutor} which stores input stream offsets + * for all position-dependent lexer actions. + */ + fixOffsetBeforeMatch(offset) { + let updatedLexerActions; + for (let i = 0; i < this._lexerActions.length; i++) { + if (this._lexerActions[i].isPositionDependent && !(this._lexerActions[i] instanceof LexerIndexedCustomAction_1.LexerIndexedCustomAction)) { + if (!updatedLexerActions) { + updatedLexerActions = this._lexerActions.slice(0); + } + updatedLexerActions[i] = new LexerIndexedCustomAction_1.LexerIndexedCustomAction(offset, this._lexerActions[i]); + } + } + if (!updatedLexerActions) { + return this; + } + return new LexerActionExecutor(updatedLexerActions); + } + /** + * Gets the lexer actions to be executed by this executor. + * @returns The lexer actions to be executed by this executor. + */ + get lexerActions() { + return this._lexerActions; + } + /** + * Execute the actions encapsulated by this executor within the context of a + * particular {@link Lexer}. + * + * This method calls {@link IntStream#seek} to set the position of the + * `input` {@link CharStream} prior to calling + * {@link LexerAction#execute} on a position-dependent action. Before the + * method returns, the input position will be restored to the same position + * it was in when the method was invoked. + * + * @param lexer The lexer instance. + * @param input The input stream which is the source for the current token. + * When this method is called, the current {@link IntStream#index} for + * `input` should be the start of the following token, i.e. 1 + * character past the end of the current token. + * @param startIndex The token start index. This value may be passed to + * {@link IntStream#seek} to set the `input` position to the beginning + * of the token. + */ + execute(lexer, input, startIndex) { + let requiresSeek = false; + let stopIndex = input.index; + try { + for (let lexerAction of this._lexerActions) { + if (lexerAction instanceof LexerIndexedCustomAction_1.LexerIndexedCustomAction) { + let offset = lexerAction.offset; + input.seek(startIndex + offset); + lexerAction = lexerAction.action; + requiresSeek = (startIndex + offset) !== stopIndex; + } + else if (lexerAction.isPositionDependent) { + input.seek(stopIndex); + requiresSeek = false; + } + lexerAction.execute(lexer); + } + } + finally { + if (requiresSeek) { + input.seek(stopIndex); + } + } + } + hashCode() { + return this.cachedHashCode; + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerActionExecutor)) { + return false; + } + return this.cachedHashCode === obj.cachedHashCode + && ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.equals(this._lexerActions, obj._lexerActions); + } + }; + __decorate([ + Decorators_1.NotNull + ], LexerActionExecutor$1.prototype, "_lexerActions", void 0); + __decorate([ + Decorators_1.NotNull + ], LexerActionExecutor$1.prototype, "lexerActions", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerActionExecutor$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerActionExecutor$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerActionExecutor$1.prototype, "equals", null); + __decorate([ + Decorators_1.NotNull, + __param(1, Decorators_1.NotNull) + ], LexerActionExecutor$1, "append", null); + LexerActionExecutor$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerActionExecutor$1); + LexerActionExecutor.LexerActionExecutor = LexerActionExecutor$1; + + return LexerActionExecutor; +} + +var LexerNoViableAltException = {}; + +var hasRequiredLexerNoViableAltException; + +function requireLexerNoViableAltException () { + if (hasRequiredLexerNoViableAltException) return LexerNoViableAltException; + hasRequiredLexerNoViableAltException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerNoViableAltException && LexerNoViableAltException.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerNoViableAltException && LexerNoViableAltException.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerNoViableAltException, "__esModule", { value: true }); + LexerNoViableAltException.LexerNoViableAltException = void 0; + const RecognitionException_1 = requireRecognitionException(); + const Decorators_1 = requireDecorators(); + const Interval_1 = requireInterval(); + const Utils = requireUtils(); + let LexerNoViableAltException$1 = class LexerNoViableAltException extends RecognitionException_1.RecognitionException { + constructor(lexer, input, startIndex, deadEndConfigs) { + super(lexer, input); + this._startIndex = startIndex; + this._deadEndConfigs = deadEndConfigs; + } + get startIndex() { + return this._startIndex; + } + get deadEndConfigs() { + return this._deadEndConfigs; + } + get inputStream() { + return super.inputStream; + } + toString() { + let symbol = ""; + if (this._startIndex >= 0 && this._startIndex < this.inputStream.size) { + symbol = this.inputStream.getText(Interval_1.Interval.of(this._startIndex, this._startIndex)); + symbol = Utils.escapeWhitespace(symbol, false); + } + // return String.format(Locale.getDefault(), "%s('%s')", LexerNoViableAltException.class.getSimpleName(), symbol); + return `LexerNoViableAltException('${symbol}')`; + } + }; + __decorate([ + Decorators_1.Override + ], LexerNoViableAltException$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.Override + ], LexerNoViableAltException$1.prototype, "toString", null); + LexerNoViableAltException$1 = __decorate([ + __param(1, Decorators_1.NotNull) + ], LexerNoViableAltException$1); + LexerNoViableAltException.LexerNoViableAltException = LexerNoViableAltException$1; + + return LexerNoViableAltException; +} + +var OrderedATNConfigSet = {}; + +var hasRequiredOrderedATNConfigSet; + +function requireOrderedATNConfigSet () { + if (hasRequiredOrderedATNConfigSet) return OrderedATNConfigSet; + hasRequiredOrderedATNConfigSet = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (OrderedATNConfigSet && OrderedATNConfigSet.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(OrderedATNConfigSet, "__esModule", { value: true }); + OrderedATNConfigSet.OrderedATNConfigSet = void 0; + const ATNConfigSet_1 = requireATNConfigSet(); + const Decorators_1 = requireDecorators(); + /** + * + * @author Sam Harwell + */ + let OrderedATNConfigSet$1 = class OrderedATNConfigSet extends ATNConfigSet_1.ATNConfigSet { + constructor(set, readonly) { + if (set != null && readonly != null) { + super(set, readonly); + } + else { + super(); + } + } + clone(readonly) { + let copy = new OrderedATNConfigSet(this, readonly); + if (!readonly && this.isReadOnly) { + copy.addAll(this); + } + return copy; + } + getKey(e) { + // This is a specially crafted key to ensure configurations are only merged if they are equal + return { state: 0, alt: e.hashCode() }; + } + canMerge(left, leftKey, right) { + return left.equals(right); + } + }; + __decorate([ + Decorators_1.Override + ], OrderedATNConfigSet$1.prototype, "clone", null); + __decorate([ + Decorators_1.Override + ], OrderedATNConfigSet$1.prototype, "getKey", null); + __decorate([ + Decorators_1.Override + ], OrderedATNConfigSet$1.prototype, "canMerge", null); + OrderedATNConfigSet.OrderedATNConfigSet = OrderedATNConfigSet$1; + + return OrderedATNConfigSet; +} + +var hasRequiredLexerATNSimulator; + +function requireLexerATNSimulator () { + if (hasRequiredLexerATNSimulator) return LexerATNSimulator; + hasRequiredLexerATNSimulator = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerATNSimulator && LexerATNSimulator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerATNSimulator && LexerATNSimulator.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LexerATNSimulator = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:29.1083066-07:00 + const AcceptStateInfo_1 = requireAcceptStateInfo(); + const ATN_1 = requireATN(); + const ATNConfig_1 = requireATNConfig(); + const ATNConfigSet_1 = requireATNConfigSet(); + const ATNSimulator_1 = requireATNSimulator(); + const DFAState_1 = requireDFAState(); + const Interval_1 = requireInterval(); + const IntStream_1 = requireIntStream(); + const Lexer_1 = requireLexer(); + const LexerActionExecutor_1 = requireLexerActionExecutor(); + const LexerNoViableAltException_1 = requireLexerNoViableAltException(); + const Decorators_1 = requireDecorators(); + const OrderedATNConfigSet_1 = requireOrderedATNConfigSet(); + const PredictionContext_1 = requirePredictionContext(); + const RuleStopState_1 = requireRuleStopState(); + const Token_1 = requireToken(); + const assert = require$$0$9; + /** "dup" of ParserInterpreter */ + let LexerATNSimulator$1 = class LexerATNSimulator extends ATNSimulator_1.ATNSimulator { + constructor(atn, recog) { + super(atn); + this.optimize_tail_calls = true; + /** The current token's starting index into the character stream. + * Shared across DFA to ATN simulation in case the ATN fails and the + * DFA did not have a previous accept state. In this case, we use the + * ATN-generated exception object. + */ + this.startIndex = -1; + /** line number 1..n within the input */ + this._line = 1; + /** The index of the character relative to the beginning of the line 0..n-1 */ + this._charPositionInLine = 0; + this.mode = Lexer_1.Lexer.DEFAULT_MODE; + /** Used during DFA/ATN exec to record the most recent accept configuration info */ + this.prevAccept = new LexerATNSimulator.SimState(); + this.recog = recog; + } + copyState(simulator) { + this._charPositionInLine = simulator.charPositionInLine; + this._line = simulator._line; + this.mode = simulator.mode; + this.startIndex = simulator.startIndex; + } + match(input, mode) { + this.mode = mode; + let mark = input.mark(); + try { + this.startIndex = input.index; + this.prevAccept.reset(); + let s0 = this.atn.modeToDFA[mode].s0; + if (s0 == null) { + return this.matchATN(input); + } + else { + return this.execATN(input, s0); + } + } + finally { + input.release(mark); + } + } + reset() { + this.prevAccept.reset(); + this.startIndex = -1; + this._line = 1; + this._charPositionInLine = 0; + this.mode = Lexer_1.Lexer.DEFAULT_MODE; + } + matchATN(input) { + let startState = this.atn.modeToStartState[this.mode]; + if (LexerATNSimulator.debug) { + console.log(`matchATN mode ${this.mode} start: ${startState}`); + } + let old_mode = this.mode; + let s0_closure = this.computeStartState(input, startState); + let suppressEdge = s0_closure.hasSemanticContext; + if (suppressEdge) { + s0_closure.hasSemanticContext = false; + } + let next = this.addDFAState(s0_closure); + if (!suppressEdge) { + let dfa = this.atn.modeToDFA[this.mode]; + if (!dfa.s0) { + dfa.s0 = next; + } + else { + next = dfa.s0; + } + } + let predict = this.execATN(input, next); + if (LexerATNSimulator.debug) { + console.log(`DFA after matchATN: ${this.atn.modeToDFA[old_mode].toLexerString()}`); + } + return predict; + } + execATN(input, ds0) { + // console.log("enter exec index "+input.index+" from "+ds0.configs); + if (LexerATNSimulator.debug) { + console.log(`start state closure=${ds0.configs}`); + } + if (ds0.isAcceptState) { + // allow zero-length tokens + this.captureSimState(this.prevAccept, input, ds0); + } + let t = input.LA(1); + // @NotNull + let s = ds0; // s is current/from DFA state + while (true) { // while more work + if (LexerATNSimulator.debug) { + console.log(`execATN loop starting closure: ${s.configs}`); + } + // As we move src->trg, src->trg, we keep track of the previous trg to + // avoid looking up the DFA state again, which is expensive. + // If the previous target was already part of the DFA, we might + // be able to avoid doing a reach operation upon t. If s!=null, + // it means that semantic predicates didn't prevent us from + // creating a DFA state. Once we know s!=null, we check to see if + // the DFA state has an edge already for t. If so, we can just reuse + // it's configuration set; there's no point in re-computing it. + // This is kind of like doing DFA simulation within the ATN + // simulation because DFA simulation is really just a way to avoid + // computing reach/closure sets. Technically, once we know that + // we have a previously added DFA state, we could jump over to + // the DFA simulator. But, that would mean popping back and forth + // a lot and making things more complicated algorithmically. + // This optimization makes a lot of sense for loops within DFA. + // A character will take us back to an existing DFA state + // that already has lots of edges out of it. e.g., .* in comments. + let target = this.getExistingTargetState(s, t); + if (target == null) { + target = this.computeTargetState(input, s, t); + } + if (target === ATNSimulator_1.ATNSimulator.ERROR) { + break; + } + // If this is a consumable input element, make sure to consume before + // capturing the accept state so the input index, line, and char + // position accurately reflect the state of the interpreter at the + // end of the token. + if (t !== IntStream_1.IntStream.EOF) { + this.consume(input); + } + if (target.isAcceptState) { + this.captureSimState(this.prevAccept, input, target); + if (t === IntStream_1.IntStream.EOF) { + break; + } + } + t = input.LA(1); + s = target; // flip; current DFA target becomes new src/from state + } + return this.failOrAccept(this.prevAccept, input, s.configs, t); + } + /** + * Get an existing target state for an edge in the DFA. If the target state + * for the edge has not yet been computed or is otherwise not available, + * this method returns `undefined`. + * + * @param s The current DFA state + * @param t The next input symbol + * @returns The existing target DFA state for the given input symbol + * `t`, or `undefined` if the target state for this edge is not + * already cached + */ + getExistingTargetState(s, t) { + let target = s.getTarget(t); + if (LexerATNSimulator.debug && target != null) { + console.log("reuse state " + s.stateNumber + + " edge to " + target.stateNumber); + } + return target; + } + /** + * Compute a target state for an edge in the DFA, and attempt to add the + * computed state and corresponding edge to the DFA. + * + * @param input The input stream + * @param s The current DFA state + * @param t The next input symbol + * + * @returns The computed target DFA state for the given input symbol + * `t`. If `t` does not lead to a valid DFA state, this method + * returns {@link #ERROR}. + */ + computeTargetState(input, s, t) { + let reach = new OrderedATNConfigSet_1.OrderedATNConfigSet(); + // if we don't find an existing DFA state + // Fill reach starting from closure, following t transitions + this.getReachableConfigSet(input, s.configs, reach, t); + if (reach.isEmpty) { // we got nowhere on t from s + if (!reach.hasSemanticContext) { + // we got nowhere on t, don't throw out this knowledge; it'd + // cause a failover from DFA later. + this.addDFAEdge(s, t, ATNSimulator_1.ATNSimulator.ERROR); + } + // stop when we can't match any more char + return ATNSimulator_1.ATNSimulator.ERROR; + } + // Add an edge from s to target DFA found/created for reach + return this.addDFAEdge(s, t, reach); + } + failOrAccept(prevAccept, input, reach, t) { + if (prevAccept.dfaState != null) { + let lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor; + this.accept(input, lexerActionExecutor, this.startIndex, prevAccept.index, prevAccept.line, prevAccept.charPos); + return prevAccept.dfaState.prediction; + } + else { + // if no accept and EOF is first char, return EOF + if (t === IntStream_1.IntStream.EOF && input.index === this.startIndex) { + return Token_1.Token.EOF; + } + throw new LexerNoViableAltException_1.LexerNoViableAltException(this.recog, input, this.startIndex, reach); + } + } + /** Given a starting configuration set, figure out all ATN configurations + * we can reach upon input `t`. Parameter `reach` is a return + * parameter. + */ + getReachableConfigSet(input, closure, reach, t) { + // this is used to skip processing for configs which have a lower priority + // than a config that already reached an accept state for the same rule + let skipAlt = ATN_1.ATN.INVALID_ALT_NUMBER; + for (let c of closure) { + let currentAltReachedAcceptState = c.alt === skipAlt; + if (currentAltReachedAcceptState && c.hasPassedThroughNonGreedyDecision) { + continue; + } + if (LexerATNSimulator.debug) { + console.log(`testing ${this.getTokenName(t)} at ${c.toString(this.recog, true)}`); + } + let n = c.state.numberOfOptimizedTransitions; + for (let ti = 0; ti < n; ti++) { // for each optimized transition + let trans = c.state.getOptimizedTransition(ti); + let target = this.getReachableTarget(trans, t); + if (target != null) { + let lexerActionExecutor = c.lexerActionExecutor; + let config; + if (lexerActionExecutor != null) { + lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - this.startIndex); + config = c.transform(target, true, lexerActionExecutor); + } + else { + assert(c.lexerActionExecutor == null); + config = c.transform(target, true); + } + let treatEofAsEpsilon = t === IntStream_1.IntStream.EOF; + if (this.closure(input, config, reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) { + // any remaining configs for this alt have a lower priority than + // the one that just reached an accept state. + skipAlt = c.alt; + break; + } + } + } + } + } + accept(input, lexerActionExecutor, startIndex, index, line, charPos) { + if (LexerATNSimulator.debug) { + console.log(`ACTION ${lexerActionExecutor}`); + } + // seek to after last char in token + input.seek(index); + this._line = line; + this._charPositionInLine = charPos; + if (lexerActionExecutor != null && this.recog != null) { + lexerActionExecutor.execute(this.recog, input, startIndex); + } + } + getReachableTarget(trans, t) { + if (trans.matches(t, Lexer_1.Lexer.MIN_CHAR_VALUE, Lexer_1.Lexer.MAX_CHAR_VALUE)) { + return trans.target; + } + return undefined; + } + computeStartState(input, p) { + let initialContext = PredictionContext_1.PredictionContext.EMPTY_FULL; + let configs = new OrderedATNConfigSet_1.OrderedATNConfigSet(); + for (let i = 0; i < p.numberOfTransitions; i++) { + let target = p.transition(i).target; + let c = ATNConfig_1.ATNConfig.create(target, i + 1, initialContext); + this.closure(input, c, configs, false, false, false); + } + return configs; + } + /** + * Since the alternatives within any lexer decision are ordered by + * preference, this method stops pursuing the closure as soon as an accept + * state is reached. After the first accept state is reached by depth-first + * search from `config`, all other (potentially reachable) states for + * this rule would have a lower priority. + * + * @returns `true` if an accept state is reached, otherwise + * `false`. + */ + closure(input, config, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) { + if (LexerATNSimulator.debug) { + console.log("closure(" + config.toString(this.recog, true) + ")"); + } + if (config.state instanceof RuleStopState_1.RuleStopState) { + if (LexerATNSimulator.debug) { + if (this.recog != null) { + console.log(`closure at ${this.recog.ruleNames[config.state.ruleIndex]} rule stop ${config}`); + } + else { + console.log(`closure at rule stop ${config}`); + } + } + let context = config.context; + if (context.isEmpty) { + configs.add(config); + return true; + } + else if (context.hasEmpty) { + configs.add(config.transform(config.state, true, PredictionContext_1.PredictionContext.EMPTY_FULL)); + currentAltReachedAcceptState = true; + } + for (let i = 0; i < context.size; i++) { + let returnStateNumber = context.getReturnState(i); + if (returnStateNumber === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + continue; + } + let newContext = context.getParent(i); // "pop" return state + let returnState = this.atn.states[returnStateNumber]; + let c = config.transform(returnState, false, newContext); + currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); + } + return currentAltReachedAcceptState; + } + // optimization + if (!config.state.onlyHasEpsilonTransitions) { + if (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision) { + configs.add(config); + } + } + let p = config.state; + for (let i = 0; i < p.numberOfOptimizedTransitions; i++) { + let t = p.getOptimizedTransition(i); + let c = this.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon); + if (c != null) { + currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); + } + } + return currentAltReachedAcceptState; + } + // side-effect: can alter configs.hasSemanticContext + getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon) { + let c; + switch (t.serializationType) { + case 3 /* RULE */: + let ruleTransition = t; + if (this.optimize_tail_calls && ruleTransition.optimizedTailCall && !config.context.hasEmpty) { + c = config.transform(t.target, true); + } + else { + let newContext = config.context.getChild(ruleTransition.followState.stateNumber); + c = config.transform(t.target, true, newContext); + } + break; + case 10 /* PRECEDENCE */: + throw new Error("Precedence predicates are not supported in lexers."); + case 4 /* PREDICATE */: + /* Track traversing semantic predicates. If we traverse, + we cannot add a DFA state for this "reach" computation + because the DFA would not test the predicate again in the + future. Rather than creating collections of semantic predicates + like v3 and testing them on prediction, v4 will test them on the + fly all the time using the ATN not the DFA. This is slower but + semantically it's not used that often. One of the key elements to + this predicate mechanism is not adding DFA states that see + predicates immediately afterwards in the ATN. For example, + + a : ID {p1}? | ID {p2}? ; + + should create the start state for rule 'a' (to save start state + competition), but should not create target of ID state. The + collection of ATN states the following ID references includes + states reached by traversing predicates. Since this is when we + test them, we cannot cash the DFA state target of ID. + */ + let pt = t; + if (LexerATNSimulator.debug) { + console.log("EVAL rule " + pt.ruleIndex + ":" + pt.predIndex); + } + configs.hasSemanticContext = true; + if (this.evaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative)) { + c = config.transform(t.target, true); + } + else { + c = undefined; + } + break; + case 6 /* ACTION */: + if (config.context.hasEmpty) { + // execute actions anywhere in the start rule for a token. + // + // TODO: if the entry rule is invoked recursively, some + // actions may be executed during the recursive call. The + // problem can appear when hasEmpty is true but + // isEmpty is false. In this case, the config needs to be + // split into two contexts - one with just the empty path + // and another with everything but the empty path. + // Unfortunately, the current algorithm does not allow + // getEpsilonTarget to return two configurations, so + // additional modifications are needed before we can support + // the split operation. + let lexerActionExecutor = LexerActionExecutor_1.LexerActionExecutor.append(config.lexerActionExecutor, this.atn.lexerActions[t.actionIndex]); + c = config.transform(t.target, true, lexerActionExecutor); + break; + } + else { + // ignore actions in referenced rules + c = config.transform(t.target, true); + break; + } + case 1 /* EPSILON */: + c = config.transform(t.target, true); + break; + case 5 /* ATOM */: + case 2 /* RANGE */: + case 7 /* SET */: + if (treatEofAsEpsilon) { + if (t.matches(IntStream_1.IntStream.EOF, Lexer_1.Lexer.MIN_CHAR_VALUE, Lexer_1.Lexer.MAX_CHAR_VALUE)) { + c = config.transform(t.target, false); + break; + } + } + c = undefined; + break; + default: + c = undefined; + break; + } + return c; + } + /** + * Evaluate a predicate specified in the lexer. + * + * If `speculative` is `true`, this method was called before + * {@link #consume} for the matched character. This method should call + * {@link #consume} before evaluating the predicate to ensure position + * sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine}, + * and {@link Lexer#getCharPositionInLine}, properly reflect the current + * lexer state. This method should restore `input` and the simulator + * to the original state before returning (i.e. undo the actions made by the + * call to {@link #consume}. + * + * @param input The input stream. + * @param ruleIndex The rule containing the predicate. + * @param predIndex The index of the predicate within the rule. + * @param speculative `true` if the current index in `input` is + * one character before the predicate's location. + * + * @returns `true` if the specified predicate evaluates to + * `true`. + */ + evaluatePredicate(input, ruleIndex, predIndex, speculative) { + // assume true if no recognizer was provided + if (this.recog == null) { + return true; + } + if (!speculative) { + return this.recog.sempred(undefined, ruleIndex, predIndex); + } + let savedCharPositionInLine = this._charPositionInLine; + let savedLine = this._line; + let index = input.index; + let marker = input.mark(); + try { + this.consume(input); + return this.recog.sempred(undefined, ruleIndex, predIndex); + } + finally { + this._charPositionInLine = savedCharPositionInLine; + this._line = savedLine; + input.seek(index); + input.release(marker); + } + } + captureSimState(settings, input, dfaState) { + settings.index = input.index; + settings.line = this._line; + settings.charPos = this._charPositionInLine; + settings.dfaState = dfaState; + } + addDFAEdge(p, t, q) { + if (q instanceof ATNConfigSet_1.ATNConfigSet) { + /* leading to this call, ATNConfigSet.hasSemanticContext is used as a + * marker indicating dynamic predicate evaluation makes this edge + * dependent on the specific input sequence, so the static edge in the + * DFA should be omitted. The target DFAState is still created since + * execATN has the ability to resynchronize with the DFA state cache + * following the predicate evaluation step. + * + * TJP notes: next time through the DFA, we see a pred again and eval. + * If that gets us to a previously created (but dangling) DFA + * state, we can continue in pure DFA mode from there. + */ + let suppressEdge = q.hasSemanticContext; + if (suppressEdge) { + q.hasSemanticContext = false; + } + // @NotNull + let to = this.addDFAState(q); + if (suppressEdge) { + return to; + } + this.addDFAEdge(p, t, to); + return to; + } + else { + if (LexerATNSimulator.debug) { + console.log("EDGE " + p + " -> " + q + " upon " + String.fromCharCode(t)); + } + if (p != null) { + p.setTarget(t, q); + } + } + } + /** Add a new DFA state if there isn't one with this set of + * configurations already. This method also detects the first + * configuration containing an ATN rule stop state. Later, when + * traversing the DFA, we will know which rule to accept. + */ + addDFAState(configs) { + /* the lexer evaluates predicates on-the-fly; by this point configs + * should not contain any configurations with unevaluated predicates. + */ + assert(!configs.hasSemanticContext); + let proposed = new DFAState_1.DFAState(configs); + let existing = this.atn.modeToDFA[this.mode].states.get(proposed); + if (existing != null) { + return existing; + } + configs.optimizeConfigs(this); + let newState = new DFAState_1.DFAState(configs.clone(true)); + let firstConfigWithRuleStopState; + for (let c of configs) { + if (c.state instanceof RuleStopState_1.RuleStopState) { + firstConfigWithRuleStopState = c; + break; + } + } + if (firstConfigWithRuleStopState != null) { + let prediction = this.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex]; + let lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor; + newState.acceptStateInfo = new AcceptStateInfo_1.AcceptStateInfo(prediction, lexerActionExecutor); + } + return this.atn.modeToDFA[this.mode].addState(newState); + } + getDFA(mode) { + return this.atn.modeToDFA[mode]; + } + /** Get the text matched so far for the current token. + */ + getText(input) { + // index is first lookahead char, don't include. + return input.getText(Interval_1.Interval.of(this.startIndex, input.index - 1)); + } + get line() { + return this._line; + } + set line(line) { + this._line = line; + } + get charPositionInLine() { + return this._charPositionInLine; + } + set charPositionInLine(charPositionInLine) { + this._charPositionInLine = charPositionInLine; + } + consume(input) { + let curChar = input.LA(1); + if (curChar === "\n".charCodeAt(0)) { + this._line++; + this._charPositionInLine = 0; + } + else { + this._charPositionInLine++; + } + input.consume(); + } + getTokenName(t) { + if (t === -1) { + return "EOF"; + } + //if ( atn.g!=null ) return atn.g.getTokenDisplayName(t); + return "'" + String.fromCharCode(t) + "'"; + } + }; + __decorate([ + Decorators_1.NotNull + ], LexerATNSimulator$1.prototype, "prevAccept", void 0); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "copyState", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "match", null); + __decorate([ + Decorators_1.Override + ], LexerATNSimulator$1.prototype, "reset", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "matchATN", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "execATN", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "getExistingTargetState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "computeTargetState", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "getReachableConfigSet", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "accept", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "computeStartState", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "closure", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "getEpsilonTarget", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "evaluatePredicate", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "captureSimState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "addDFAState", null); + __decorate([ + Decorators_1.NotNull + ], LexerATNSimulator$1.prototype, "getDFA", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "getText", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1.prototype, "consume", null); + __decorate([ + Decorators_1.NotNull + ], LexerATNSimulator$1.prototype, "getTokenName", null); + LexerATNSimulator$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], LexerATNSimulator$1); + exports.LexerATNSimulator = LexerATNSimulator$1; + (function (LexerATNSimulator) { + LexerATNSimulator.debug = false; + LexerATNSimulator.dfa_debug = false; + /** When we hit an accept state in either the DFA or the ATN, we + * have to notify the character stream to start buffering characters + * via {@link IntStream#mark} and record the current state. The current sim state + * includes the current index into the input, the current line, + * and current character position in that line. Note that the Lexer is + * tracking the starting line and characterization of the token. These + * variables track the "state" of the simulator when it hits an accept state. + * + * We track these variables separately for the DFA and ATN simulation + * because the DFA simulation often has to fail over to the ATN + * simulation. If the ATN simulation fails, we need the DFA to fall + * back to its previously accepted state, if any. If the ATN succeeds, + * then the ATN does the accept and the DFA simulator that invoked it + * can simply return the predicted token type. + */ + class SimState { + constructor() { + this.index = -1; + this.line = 0; + this.charPos = -1; + } + reset() { + this.index = -1; + this.line = 0; + this.charPos = -1; + this.dfaState = undefined; + } + } + LexerATNSimulator.SimState = SimState; + })(LexerATNSimulator$1 = exports.LexerATNSimulator || (exports.LexerATNSimulator = {})); + exports.LexerATNSimulator = LexerATNSimulator$1; + + } (LexerATNSimulator)); + return LexerATNSimulator; +} + +var hasRequiredLexer; + +function requireLexer () { + if (hasRequiredLexer) return Lexer; + hasRequiredLexer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Lexer && Lexer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(Lexer, "__esModule", { value: true }); + Lexer.Lexer = void 0; + const CommonTokenFactory_1 = requireCommonTokenFactory(); + const IntegerStack_1 = requireIntegerStack(); + const Interval_1 = requireInterval(); + const IntStream_1 = requireIntStream(); + const LexerATNSimulator_1 = requireLexerATNSimulator(); + const LexerNoViableAltException_1 = requireLexerNoViableAltException(); + const Decorators_1 = requireDecorators(); + const Recognizer_1 = requireRecognizer(); + const Token_1 = requireToken(); + /** A lexer is recognizer that draws input symbols from a character stream. + * lexer grammars result in a subclass of this object. A Lexer object + * uses simplified match() and error recovery mechanisms in the interest + * of speed. + */ + let Lexer$1 = class Lexer extends Recognizer_1.Recognizer { + constructor(input) { + super(); + /** How to create token objects */ + this._factory = CommonTokenFactory_1.CommonTokenFactory.DEFAULT; + /** What character index in the stream did the current token start at? + * Needed, for example, to get the text for current token. Set at + * the start of nextToken. + */ + this._tokenStartCharIndex = -1; + /** The line on which the first character of the token resides */ + this._tokenStartLine = 0; + /** The character position of first character within the line */ + this._tokenStartCharPositionInLine = 0; + /** Once we see EOF on char stream, next token will be EOF. + * If you have DONE : EOF ; then you see DONE EOF. + */ + this._hitEOF = false; + /** The channel number for the current token */ + this._channel = 0; + /** The token type for the current token */ + this._type = 0; + this._modeStack = new IntegerStack_1.IntegerStack(); + this._mode = Lexer.DEFAULT_MODE; + this._input = input; + this._tokenFactorySourcePair = { source: this, stream: input }; + } + static get DEFAULT_TOKEN_CHANNEL() { + return Token_1.Token.DEFAULT_CHANNEL; + } + static get HIDDEN() { + return Token_1.Token.HIDDEN_CHANNEL; + } + reset(resetInput) { + // wack Lexer state variables + if (resetInput === undefined || resetInput) { + this._input.seek(0); // rewind the input + } + this._token = undefined; + this._type = Token_1.Token.INVALID_TYPE; + this._channel = Token_1.Token.DEFAULT_CHANNEL; + this._tokenStartCharIndex = -1; + this._tokenStartCharPositionInLine = -1; + this._tokenStartLine = -1; + this._text = undefined; + this._hitEOF = false; + this._mode = Lexer.DEFAULT_MODE; + this._modeStack.clear(); + this.interpreter.reset(); + } + /** Return a token from this source; i.e., match a token on the char + * stream. + */ + nextToken() { + if (this._input == null) { + throw new Error("nextToken requires a non-null input stream."); + } + // Mark start location in char stream so unbuffered streams are + // guaranteed at least have text of current token + let tokenStartMarker = this._input.mark(); + try { + outer: while (true) { + if (this._hitEOF) { + return this.emitEOF(); + } + this._token = undefined; + this._channel = Token_1.Token.DEFAULT_CHANNEL; + this._tokenStartCharIndex = this._input.index; + this._tokenStartCharPositionInLine = this.interpreter.charPositionInLine; + this._tokenStartLine = this.interpreter.line; + this._text = undefined; + do { + this._type = Token_1.Token.INVALID_TYPE; + // System.out.println("nextToken line "+tokenStartLine+" at "+((char)input.LA(1))+ + // " in mode "+mode+ + // " at index "+input.index); + let ttype; + try { + ttype = this.interpreter.match(this._input, this._mode); + } + catch (e) { + if (e instanceof LexerNoViableAltException_1.LexerNoViableAltException) { + this.notifyListeners(e); // report error + this.recover(e); + ttype = Lexer.SKIP; + } + else { + throw e; + } + } + if (this._input.LA(1) === IntStream_1.IntStream.EOF) { + this._hitEOF = true; + } + if (this._type === Token_1.Token.INVALID_TYPE) { + this._type = ttype; + } + if (this._type === Lexer.SKIP) { + continue outer; + } + } while (this._type === Lexer.MORE); + if (this._token == null) { + return this.emit(); + } + return this._token; + } + } + finally { + // make sure we release marker after match or + // unbuffered char stream will keep buffering + this._input.release(tokenStartMarker); + } + } + /** Instruct the lexer to skip creating a token for current lexer rule + * and look for another token. nextToken() knows to keep looking when + * a lexer rule finishes with token set to SKIP_TOKEN. Recall that + * if token==undefined at end of any token rule, it creates one for you + * and emits it. + */ + skip() { + this._type = Lexer.SKIP; + } + more() { + this._type = Lexer.MORE; + } + mode(m) { + this._mode = m; + } + pushMode(m) { + if (LexerATNSimulator_1.LexerATNSimulator.debug) { + console.log("pushMode " + m); + } + this._modeStack.push(this._mode); + this.mode(m); + } + popMode() { + if (this._modeStack.isEmpty) { + throw new Error("EmptyStackException"); + } + if (LexerATNSimulator_1.LexerATNSimulator.debug) { + console.log("popMode back to " + this._modeStack.peek()); + } + this.mode(this._modeStack.pop()); + return this._mode; + } + get tokenFactory() { + return this._factory; + } + // @Override + set tokenFactory(factory) { + this._factory = factory; + } + get inputStream() { + return this._input; + } + /** Set the char stream and reset the lexer */ + set inputStream(input) { + this.reset(false); + this._input = input; + this._tokenFactorySourcePair = { source: this, stream: this._input }; + } + get sourceName() { + return this._input.sourceName; + } + emit(token) { + if (!token) { + token = this._factory.create(this._tokenFactorySourcePair, this._type, this._text, this._channel, this._tokenStartCharIndex, this.charIndex - 1, this._tokenStartLine, this._tokenStartCharPositionInLine); + } + this._token = token; + return token; + } + emitEOF() { + let cpos = this.charPositionInLine; + let line = this.line; + let eof = this._factory.create(this._tokenFactorySourcePair, Token_1.Token.EOF, undefined, Token_1.Token.DEFAULT_CHANNEL, this._input.index, this._input.index - 1, line, cpos); + this.emit(eof); + return eof; + } + get line() { + return this.interpreter.line; + } + set line(line) { + this.interpreter.line = line; + } + get charPositionInLine() { + return this.interpreter.charPositionInLine; + } + set charPositionInLine(charPositionInLine) { + this.interpreter.charPositionInLine = charPositionInLine; + } + /** What is the index of the current character of lookahead? */ + get charIndex() { + return this._input.index; + } + /** Return the text matched so far for the current token or any + * text override. + */ + get text() { + if (this._text != null) { + return this._text; + } + return this.interpreter.getText(this._input); + } + /** Set the complete text of this token; it wipes any previous + * changes to the text. + */ + set text(text) { + this._text = text; + } + /** Override if emitting multiple tokens. */ + get token() { return this._token; } + set token(_token) { + this._token = _token; + } + set type(ttype) { + this._type = ttype; + } + get type() { + return this._type; + } + set channel(channel) { + this._channel = channel; + } + get channel() { + return this._channel; + } + /** Return a list of all Token objects in input char stream. + * Forces load of all tokens. Does not include EOF token. + */ + getAllTokens() { + let tokens = []; + let t = this.nextToken(); + while (t.type !== Token_1.Token.EOF) { + tokens.push(t); + t = this.nextToken(); + } + return tokens; + } + notifyListeners(e) { + let text = this._input.getText(Interval_1.Interval.of(this._tokenStartCharIndex, this._input.index)); + let msg = "token recognition error at: '" + + this.getErrorDisplay(text) + "'"; + let listener = this.getErrorListenerDispatch(); + if (listener.syntaxError) { + listener.syntaxError(this, undefined, this._tokenStartLine, this._tokenStartCharPositionInLine, msg, e); + } + } + getErrorDisplay(s) { + if (typeof s === "number") { + switch (s) { + case Token_1.Token.EOF: + return ""; + case 0x0a: + return "\\n"; + case 0x09: + return "\\t"; + case 0x0d: + return "\\r"; + } + return String.fromCharCode(s); + } + return s.replace(/\n/g, "\\n") + .replace(/\t/g, "\\t") + .replace(/\r/g, "\\r"); + } + getCharErrorDisplay(c) { + let s = this.getErrorDisplay(c); + return "'" + s + "'"; + } + recover(re) { + if (re instanceof LexerNoViableAltException_1.LexerNoViableAltException) { + if (this._input.LA(1) !== IntStream_1.IntStream.EOF) { + // skip a char and try again + this.interpreter.consume(this._input); + } + } + else { + //System.out.println("consuming char "+(char)input.LA(1)+" during recovery"); + //re.printStackTrace(); + // TODO: Do we lose character or line position information? + this._input.consume(); + } + } + }; + Lexer$1.DEFAULT_MODE = 0; + Lexer$1.MORE = -2; + Lexer$1.SKIP = -3; + Lexer$1.MIN_CHAR_VALUE = 0x0000; + Lexer$1.MAX_CHAR_VALUE = 0x10FFFF; + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "nextToken", null); + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "tokenFactory", null); + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "sourceName", null); + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "line", null); + __decorate([ + Decorators_1.Override + ], Lexer$1.prototype, "charPositionInLine", null); + Lexer.Lexer = Lexer$1; + + return Lexer; +} + +var hasRequiredIntervalSet; + +function requireIntervalSet () { + if (hasRequiredIntervalSet) return IntervalSet; + hasRequiredIntervalSet = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (IntervalSet && IntervalSet.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (IntervalSet && IntervalSet.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(IntervalSet, "__esModule", { value: true }); + IntervalSet.IntervalSet = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:40.8683480-07:00 + const ArrayEqualityComparator_1 = requireArrayEqualityComparator(); + const IntegerList_1 = requireIntegerList(); + const Interval_1 = requireInterval(); + const Lexer_1 = requireLexer(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * This class implements the {@link IntSet} backed by a sorted array of + * non-overlapping intervals. It is particularly efficient for representing + * large collections of numbers, where the majority of elements appear as part + * of a sequential range of numbers that are all part of the set. For example, + * the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }. + * + * This class is able to represent sets containing any combination of values in + * the range {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE} + * (inclusive). + */ + let IntervalSet$1 = class IntervalSet { + constructor(intervals) { + this.readonly = false; + if (intervals != null) { + this._intervals = intervals.slice(0); + } + else { + this._intervals = []; + } + } + static get COMPLETE_CHAR_SET() { + if (IntervalSet._COMPLETE_CHAR_SET === undefined) { + IntervalSet._COMPLETE_CHAR_SET = IntervalSet.of(Lexer_1.Lexer.MIN_CHAR_VALUE, Lexer_1.Lexer.MAX_CHAR_VALUE); + IntervalSet._COMPLETE_CHAR_SET.setReadonly(true); + } + return IntervalSet._COMPLETE_CHAR_SET; + } + static get EMPTY_SET() { + if (IntervalSet._EMPTY_SET == null) { + IntervalSet._EMPTY_SET = new IntervalSet(); + IntervalSet._EMPTY_SET.setReadonly(true); + } + return IntervalSet._EMPTY_SET; + } + /** + * Create a set with all ints within range [a..b] (inclusive). If b is omitted, the set contains the single element + * a. + */ + static of(a, b = a) { + let s = new IntervalSet(); + s.add(a, b); + return s; + } + clear() { + if (this.readonly) { + throw new Error("can't alter readonly IntervalSet"); + } + this._intervals.length = 0; + } + /** Add interval; i.e., add all integers from a to b to set. + * If b<a, do nothing. + * Keep list in sorted order (by left range value). + * If overlap, combine ranges. For example, + * If this is {1..5, 10..20}, adding 6..7 yields + * {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}. + */ + add(a, b = a) { + this.addRange(Interval_1.Interval.of(a, b)); + } + // copy on write so we can cache a..a intervals and sets of that + addRange(addition) { + if (this.readonly) { + throw new Error("can't alter readonly IntervalSet"); + } + //System.out.println("add "+addition+" to "+intervals.toString()); + if (addition.b < addition.a) { + return; + } + // find position in list + // Use iterators as we modify list in place + for (let i = 0; i < this._intervals.length; i++) { + let r = this._intervals[i]; + if (addition.equals(r)) { + return; + } + if (addition.adjacent(r) || !addition.disjoint(r)) { + // next to each other, make a single larger interval + let bigger = addition.union(r); + this._intervals[i] = bigger; + // make sure we didn't just create an interval that + // should be merged with next interval in list + while (i < this._intervals.length - 1) { + i++; + let next = this._intervals[i]; + if (!bigger.adjacent(next) && bigger.disjoint(next)) { + break; + } + // if we bump up against or overlap next, merge + // remove this one + this._intervals.splice(i, 1); + i--; + // move backwards to what we just set + this._intervals[i] = bigger.union(next); + // set to 3 merged ones + } + // first call to next after previous duplicates the result + return; + } + if (addition.startsBeforeDisjoint(r)) { + // insert before r + this._intervals.splice(i, 0, addition); + return; + } + // if disjoint and after r, a future iteration will handle it + } + // ok, must be after last interval (and disjoint from last interval) + // just add it + this._intervals.push(addition); + } + /** combine all sets in the array returned the or'd value */ + static or(sets) { + let r = new IntervalSet(); + for (let s of sets) { + r.addAll(s); + } + return r; + } + addAll(set) { + if (set == null) { + return this; + } + if (set instanceof IntervalSet) { + let other = set; + // walk set and add each interval + let n = other._intervals.length; + for (let i = 0; i < n; i++) { + let I = other._intervals[i]; + this.add(I.a, I.b); + } + } + else { + for (let value of set.toArray()) { + this.add(value); + } + } + return this; + } + complementRange(minElement, maxElement) { + return this.complement(IntervalSet.of(minElement, maxElement)); + } + /** {@inheritDoc} */ + complement(vocabulary) { + if (vocabulary.isNil) { + // nothing in common with null set + return IntervalSet.EMPTY_SET; + } + let vocabularyIS; + if (vocabulary instanceof IntervalSet) { + vocabularyIS = vocabulary; + } + else { + vocabularyIS = new IntervalSet(); + vocabularyIS.addAll(vocabulary); + } + return vocabularyIS.subtract(this); + } + subtract(a) { + if (a == null || a.isNil) { + return new IntervalSet(this._intervals); + } + if (a instanceof IntervalSet) { + return IntervalSet.subtract(this, a); + } + let other = new IntervalSet(); + other.addAll(a); + return IntervalSet.subtract(this, other); + } + /** + * Compute the set difference between two interval sets. The specific + * operation is `left - right`. + */ + static subtract(left, right) { + if (left.isNil) { + return new IntervalSet(); + } + let result = new IntervalSet(left._intervals); + if (right.isNil) { + // right set has no elements; just return the copy of the current set + return result; + } + let resultI = 0; + let rightI = 0; + while (resultI < result._intervals.length && rightI < right._intervals.length) { + let resultInterval = result._intervals[resultI]; + let rightInterval = right._intervals[rightI]; + // operation: (resultInterval - rightInterval) and update indexes + if (rightInterval.b < resultInterval.a) { + rightI++; + continue; + } + if (rightInterval.a > resultInterval.b) { + resultI++; + continue; + } + let beforeCurrent; + let afterCurrent; + if (rightInterval.a > resultInterval.a) { + beforeCurrent = new Interval_1.Interval(resultInterval.a, rightInterval.a - 1); + } + if (rightInterval.b < resultInterval.b) { + afterCurrent = new Interval_1.Interval(rightInterval.b + 1, resultInterval.b); + } + if (beforeCurrent) { + if (afterCurrent) { + // split the current interval into two + result._intervals[resultI] = beforeCurrent; + result._intervals.splice(resultI + 1, 0, afterCurrent); + resultI++; + rightI++; + continue; + } + else { + // replace the current interval + result._intervals[resultI] = beforeCurrent; + resultI++; + continue; + } + } + else { + if (afterCurrent) { + // replace the current interval + result._intervals[resultI] = afterCurrent; + rightI++; + continue; + } + else { + // remove the current interval (thus no need to increment resultI) + result._intervals.splice(resultI, 1); + continue; + } + } + } + // If rightI reached right.intervals.size, no more intervals to subtract from result. + // If resultI reached result.intervals.size, we would be subtracting from an empty set. + // Either way, we are done. + return result; + } + or(a) { + let o = new IntervalSet(); + o.addAll(this); + o.addAll(a); + return o; + } + /** {@inheritDoc} */ + and(other) { + if (other.isNil) { //|| !(other instanceof IntervalSet) ) { + // nothing in common with null set + return new IntervalSet(); + } + let myIntervals = this._intervals; + let theirIntervals = other._intervals; + let intersection; + let mySize = myIntervals.length; + let theirSize = theirIntervals.length; + let i = 0; + let j = 0; + // iterate down both interval lists looking for nondisjoint intervals + while (i < mySize && j < theirSize) { + let mine = myIntervals[i]; + let theirs = theirIntervals[j]; + //System.out.println("mine="+mine+" and theirs="+theirs); + if (mine.startsBeforeDisjoint(theirs)) { + // move this iterator looking for interval that might overlap + i++; + } + else if (theirs.startsBeforeDisjoint(mine)) { + // move other iterator looking for interval that might overlap + j++; + } + else if (mine.properlyContains(theirs)) { + // overlap, add intersection, get next theirs + if (!intersection) { + intersection = new IntervalSet(); + } + intersection.addRange(mine.intersection(theirs)); + j++; + } + else if (theirs.properlyContains(mine)) { + // overlap, add intersection, get next mine + if (!intersection) { + intersection = new IntervalSet(); + } + intersection.addRange(mine.intersection(theirs)); + i++; + } + else if (!mine.disjoint(theirs)) { + // overlap, add intersection + if (!intersection) { + intersection = new IntervalSet(); + } + intersection.addRange(mine.intersection(theirs)); + // Move the iterator of lower range [a..b], but not + // the upper range as it may contain elements that will collide + // with the next iterator. So, if mine=[0..115] and + // theirs=[115..200], then intersection is 115 and move mine + // but not theirs as theirs may collide with the next range + // in thisIter. + // move both iterators to next ranges + if (mine.startsAfterNonDisjoint(theirs)) { + j++; + } + else if (theirs.startsAfterNonDisjoint(mine)) { + i++; + } + } + } + if (!intersection) { + return new IntervalSet(); + } + return intersection; + } + /** {@inheritDoc} */ + contains(el) { + let n = this._intervals.length; + let l = 0; + let r = n - 1; + // Binary search for the element in the (sorted, disjoint) array of intervals. + while (l <= r) { + let m = (l + r) >> 1; + let I = this._intervals[m]; + let a = I.a; + let b = I.b; + if (b < el) { + l = m + 1; + } + else if (a > el) { + r = m - 1; + } + else { + // el >= a && el <= b + return true; + } + } + return false; + } + /** {@inheritDoc} */ + get isNil() { + return this._intervals == null || this._intervals.length === 0; + } + /** + * Returns the maximum value contained in the set if not isNil. + * + * @return the maximum value contained in the set. + * @throws RangeError if set is empty + */ + get maxElement() { + if (this.isNil) { + throw new RangeError("set is empty"); + } + let last = this._intervals[this._intervals.length - 1]; + return last.b; + } + /** + * Returns the minimum value contained in the set if not isNil. + * + * @return the minimum value contained in the set. + * @throws RangeError if set is empty + */ + get minElement() { + if (this.isNil) { + throw new RangeError("set is empty"); + } + return this._intervals[0].a; + } + /** Return a list of Interval objects. */ + get intervals() { + return this._intervals; + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + for (let I of this._intervals) { + hash = MurmurHash_1.MurmurHash.update(hash, I.a); + hash = MurmurHash_1.MurmurHash.update(hash, I.b); + } + hash = MurmurHash_1.MurmurHash.finish(hash, this._intervals.length * 2); + return hash; + } + /** Are two IntervalSets equal? Because all intervals are sorted + * and disjoint, equals is a simple linear walk over both lists + * to make sure they are the same. Interval.equals() is used + * by the List.equals() method to check the ranges. + */ + equals(o) { + if (o == null || !(o instanceof IntervalSet)) { + return false; + } + return ArrayEqualityComparator_1.ArrayEqualityComparator.INSTANCE.equals(this._intervals, o._intervals); + } + toString(elemAreChar = false) { + let buf = ""; + if (this._intervals == null || this._intervals.length === 0) { + return "{}"; + } + if (this.size > 1) { + buf += "{"; + } + let first = true; + for (let I of this._intervals) { + if (first) { + first = false; + } + else { + buf += ", "; + } + let a = I.a; + let b = I.b; + if (a === b) { + if (a === Token_1.Token.EOF) { + buf += ""; + } + else if (elemAreChar) { + buf += "'" + String.fromCodePoint(a) + "'"; + } + else { + buf += a; + } + } + else { + if (elemAreChar) { + buf += "'" + String.fromCodePoint(a) + "'..'" + String.fromCodePoint(b) + "'"; + } + else { + buf += a + ".." + b; + } + } + } + if (this.size > 1) { + buf += "}"; + } + return buf; + } + toStringVocabulary(vocabulary) { + if (this._intervals == null || this._intervals.length === 0) { + return "{}"; + } + let buf = ""; + if (this.size > 1) { + buf += "{"; + } + let first = true; + for (let I of this._intervals) { + if (first) { + first = false; + } + else { + buf += ", "; + } + let a = I.a; + let b = I.b; + if (a === b) { + buf += this.elementName(vocabulary, a); + } + else { + for (let i = a; i <= b; i++) { + if (i > a) { + buf += ", "; + } + buf += this.elementName(vocabulary, i); + } + } + } + if (this.size > 1) { + buf += "}"; + } + return buf; + } + elementName(vocabulary, a) { + if (a === Token_1.Token.EOF) { + return ""; + } + else if (a === Token_1.Token.EPSILON) { + return ""; + } + else { + return vocabulary.getDisplayName(a); + } + } + get size() { + let n = 0; + let numIntervals = this._intervals.length; + if (numIntervals === 1) { + let firstInterval = this._intervals[0]; + return firstInterval.b - firstInterval.a + 1; + } + for (let i = 0; i < numIntervals; i++) { + let I = this._intervals[i]; + n += (I.b - I.a + 1); + } + return n; + } + toIntegerList() { + let values = new IntegerList_1.IntegerList(this.size); + let n = this._intervals.length; + for (let i = 0; i < n; i++) { + let I = this._intervals[i]; + let a = I.a; + let b = I.b; + for (let v = a; v <= b; v++) { + values.add(v); + } + } + return values; + } + toSet() { + let s = new Set(); + for (let I of this._intervals) { + let a = I.a; + let b = I.b; + for (let v = a; v <= b; v++) { + s.add(v); + } + } + return s; + } + toArray() { + let values = new Array(); + let n = this._intervals.length; + for (let i = 0; i < n; i++) { + let I = this._intervals[i]; + let a = I.a; + let b = I.b; + for (let v = a; v <= b; v++) { + values.push(v); + } + } + return values; + } + remove(el) { + if (this.readonly) { + throw new Error("can't alter readonly IntervalSet"); + } + let n = this._intervals.length; + for (let i = 0; i < n; i++) { + let I = this._intervals[i]; + let a = I.a; + let b = I.b; + if (el < a) { + break; // list is sorted and el is before this interval; not here + } + // if whole interval x..x, rm + if (el === a && el === b) { + this._intervals.splice(i, 1); + break; + } + // if on left edge x..b, adjust left + if (el === a) { + this._intervals[i] = Interval_1.Interval.of(I.a + 1, I.b); + break; + } + // if on right edge a..x, adjust right + if (el === b) { + this._intervals[i] = Interval_1.Interval.of(I.a, I.b - 1); + break; + } + // if in middle a..x..b, split interval + if (el > a && el < b) { // found in this interval + let oldb = I.b; + this._intervals[i] = Interval_1.Interval.of(I.a, el - 1); // [a..x-1] + this.add(el + 1, oldb); // add [x+1..b] + } + } + } + get isReadonly() { + return this.readonly; + } + setReadonly(readonly) { + if (this.readonly && !readonly) { + throw new Error("can't alter readonly IntervalSet"); + } + this.readonly = readonly; + } + }; + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "addAll", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "complement", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "subtract", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "or", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "and", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "contains", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "isNil", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "equals", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], IntervalSet$1.prototype, "toStringVocabulary", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], IntervalSet$1.prototype, "elementName", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], IntervalSet$1.prototype, "remove", null); + __decorate([ + Decorators_1.NotNull + ], IntervalSet$1, "of", null); + __decorate([ + Decorators_1.NotNull + ], IntervalSet$1, "subtract", null); + IntervalSet.IntervalSet = IntervalSet$1; + + return IntervalSet; +} + +var NoViableAltException = {}; + +var Parser = {}; + +var ATNDeserializationOptions = {}; + +var hasRequiredATNDeserializationOptions; + +function requireATNDeserializationOptions () { + if (hasRequiredATNDeserializationOptions) return ATNDeserializationOptions; + hasRequiredATNDeserializationOptions = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNDeserializationOptions && ATNDeserializationOptions.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ATNDeserializationOptions, "__esModule", { value: true }); + ATNDeserializationOptions.ATNDeserializationOptions = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:25.8187912-07:00 + const Decorators_1 = requireDecorators(); + /** + * + * @author Sam Harwell + */ + let ATNDeserializationOptions$1 = class ATNDeserializationOptions { + constructor(options) { + this.readOnly = false; + if (options) { + this.verifyATN = options.verifyATN; + this.generateRuleBypassTransitions = options.generateRuleBypassTransitions; + this.optimize = options.optimize; + } + else { + this.verifyATN = true; + this.generateRuleBypassTransitions = false; + this.optimize = true; + } + } + static get defaultOptions() { + if (ATNDeserializationOptions._defaultOptions == null) { + ATNDeserializationOptions._defaultOptions = new ATNDeserializationOptions(); + ATNDeserializationOptions._defaultOptions.makeReadOnly(); + } + return ATNDeserializationOptions._defaultOptions; + } + get isReadOnly() { + return this.readOnly; + } + makeReadOnly() { + this.readOnly = true; + } + get isVerifyATN() { + return this.verifyATN; + } + set isVerifyATN(verifyATN) { + this.throwIfReadOnly(); + this.verifyATN = verifyATN; + } + get isGenerateRuleBypassTransitions() { + return this.generateRuleBypassTransitions; + } + set isGenerateRuleBypassTransitions(generateRuleBypassTransitions) { + this.throwIfReadOnly(); + this.generateRuleBypassTransitions = generateRuleBypassTransitions; + } + get isOptimize() { + return this.optimize; + } + set isOptimize(optimize) { + this.throwIfReadOnly(); + this.optimize = optimize; + } + throwIfReadOnly() { + if (this.isReadOnly) { + throw new Error("The object is read only."); + } + } + }; + __decorate([ + Decorators_1.NotNull + ], ATNDeserializationOptions$1, "defaultOptions", null); + ATNDeserializationOptions.ATNDeserializationOptions = ATNDeserializationOptions$1; + + return ATNDeserializationOptions; +} + +var ATNDeserializer = {}; + +var ActionTransition = {}; + +var hasRequiredActionTransition; + +function requireActionTransition () { + if (hasRequiredActionTransition) return ActionTransition; + hasRequiredActionTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ActionTransition && ActionTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ActionTransition && ActionTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ActionTransition, "__esModule", { value: true }); + ActionTransition.ActionTransition = void 0; + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + let ActionTransition$1 = class ActionTransition extends Transition_1.Transition { + constructor(target, ruleIndex, actionIndex = -1, isCtxDependent = false) { + super(target); + this.ruleIndex = ruleIndex; + this.actionIndex = actionIndex; + this.isCtxDependent = isCtxDependent; + } + get serializationType() { + return 6 /* ACTION */; + } + get isEpsilon() { + return true; // we are to be ignored by analysis 'cept for predicates + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return false; + } + toString() { + return "action_" + this.ruleIndex + ":" + this.actionIndex; + } + }; + __decorate([ + Decorators_1.Override + ], ActionTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], ActionTransition$1.prototype, "isEpsilon", null); + __decorate([ + Decorators_1.Override + ], ActionTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override + ], ActionTransition$1.prototype, "toString", null); + ActionTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ActionTransition$1); + ActionTransition.ActionTransition = ActionTransition$1; + + return ActionTransition; +} + +var AtomTransition = {}; + +var hasRequiredAtomTransition; + +function requireAtomTransition () { + if (hasRequiredAtomTransition) return AtomTransition; + hasRequiredAtomTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (AtomTransition && AtomTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (AtomTransition && AtomTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(AtomTransition, "__esModule", { value: true }); + AtomTransition.AtomTransition = void 0; + const IntervalSet_1 = requireIntervalSet(); + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + /** TODO: make all transitions sets? no, should remove set edges */ + let AtomTransition$1 = class AtomTransition extends Transition_1.Transition { + constructor(target, label) { + super(target); + this._label = label; + } + get serializationType() { + return 5 /* ATOM */; + } + get label() { + return IntervalSet_1.IntervalSet.of(this._label); + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return this._label === symbol; + } + toString() { + return String(this.label); + } + }; + __decorate([ + Decorators_1.Override + ], AtomTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], AtomTransition$1.prototype, "label", null); + __decorate([ + Decorators_1.Override + ], AtomTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], AtomTransition$1.prototype, "toString", null); + AtomTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], AtomTransition$1); + AtomTransition.AtomTransition = AtomTransition$1; + + return AtomTransition; +} + +var BasicBlockStartState = {}; + +var BlockStartState = {}; + +var hasRequiredBlockStartState; + +function requireBlockStartState () { + if (hasRequiredBlockStartState) return BlockStartState; + hasRequiredBlockStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(BlockStartState, "__esModule", { value: true }); + BlockStartState.BlockStartState = void 0; + const DecisionState_1 = requireDecisionState(); + /** The start of a regular `(...)` block. */ + let BlockStartState$1 = class BlockStartState extends DecisionState_1.DecisionState { + }; + BlockStartState.BlockStartState = BlockStartState$1; + + return BlockStartState; +} + +var hasRequiredBasicBlockStartState; + +function requireBasicBlockStartState () { + if (hasRequiredBasicBlockStartState) return BasicBlockStartState; + hasRequiredBasicBlockStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (BasicBlockStartState && BasicBlockStartState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(BasicBlockStartState, "__esModule", { value: true }); + BasicBlockStartState.BasicBlockStartState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:27.7669801-07:00 + const ATNStateType_1 = requireATNStateType(); + const BlockStartState_1 = requireBlockStartState(); + const Decorators_1 = requireDecorators(); + /** + * + * @author Sam Harwell + */ + let BasicBlockStartState$1 = class BasicBlockStartState extends BlockStartState_1.BlockStartState { + get stateType() { + return ATNStateType_1.ATNStateType.BLOCK_START; + } + }; + __decorate([ + Decorators_1.Override + ], BasicBlockStartState$1.prototype, "stateType", null); + BasicBlockStartState.BasicBlockStartState = BasicBlockStartState$1; + + return BasicBlockStartState; +} + +var BlockEndState = {}; + +var hasRequiredBlockEndState; + +function requireBlockEndState () { + if (hasRequiredBlockEndState) return BlockEndState; + hasRequiredBlockEndState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (BlockEndState && BlockEndState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(BlockEndState, "__esModule", { value: true }); + BlockEndState.BlockEndState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:27.9125304-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + /** Terminal node of a simple `(a|b|c)` block. */ + let BlockEndState$1 = class BlockEndState extends ATNState_1.ATNState { + get stateType() { + return ATNStateType_1.ATNStateType.BLOCK_END; + } + }; + __decorate([ + Decorators_1.Override + ], BlockEndState$1.prototype, "stateType", null); + BlockEndState.BlockEndState = BlockEndState$1; + + return BlockEndState; +} + +var EpsilonTransition = {}; + +var hasRequiredEpsilonTransition; + +function requireEpsilonTransition () { + if (hasRequiredEpsilonTransition) return EpsilonTransition; + hasRequiredEpsilonTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (EpsilonTransition && EpsilonTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (EpsilonTransition && EpsilonTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(EpsilonTransition, "__esModule", { value: true }); + EpsilonTransition.EpsilonTransition = void 0; + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + let EpsilonTransition$1 = class EpsilonTransition extends Transition_1.Transition { + constructor(target, outermostPrecedenceReturn = -1) { + super(target); + this._outermostPrecedenceReturn = outermostPrecedenceReturn; + } + /** + * @returns the rule index of a precedence rule for which this transition is + * returning from, where the precedence value is 0; otherwise, -1. + * + * @see ATNConfig.isPrecedenceFilterSuppressed + * @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet, ParserRuleContext, PredictionContextCache) + * @since 4.4.1 + */ + get outermostPrecedenceReturn() { + return this._outermostPrecedenceReturn; + } + get serializationType() { + return 1 /* EPSILON */; + } + get isEpsilon() { + return true; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return false; + } + toString() { + return "epsilon"; + } + }; + __decorate([ + Decorators_1.Override + ], EpsilonTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], EpsilonTransition$1.prototype, "isEpsilon", null); + __decorate([ + Decorators_1.Override + ], EpsilonTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], EpsilonTransition$1.prototype, "toString", null); + EpsilonTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], EpsilonTransition$1); + EpsilonTransition.EpsilonTransition = EpsilonTransition$1; + + return EpsilonTransition; +} + +var LexerChannelAction = {}; + +var hasRequiredLexerChannelAction; + +function requireLexerChannelAction () { + if (hasRequiredLexerChannelAction) return LexerChannelAction; + hasRequiredLexerChannelAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerChannelAction && LexerChannelAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerChannelAction && LexerChannelAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerChannelAction, "__esModule", { value: true }); + LexerChannelAction.LexerChannelAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `channel` lexer action by calling + * {@link Lexer#setChannel} with the assigned channel. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerChannelAction$1 = class LexerChannelAction { + /** + * Constructs a new `channel` action with the specified channel value. + * @param channel The channel value to pass to {@link Lexer#setChannel}. + */ + constructor(channel) { + this._channel = channel; + } + /** + * Gets the channel to use for the {@link Token} created by the lexer. + * + * @returns The channel to use for the {@link Token} created by the lexer. + */ + get channel() { + return this._channel; + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#CHANNEL}. + */ + get actionType() { + return 0 /* CHANNEL */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#setChannel} with the + * value provided by {@link #getChannel}. + */ + execute(lexer) { + lexer.channel = this._channel; + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + hash = MurmurHash_1.MurmurHash.update(hash, this._channel); + return MurmurHash_1.MurmurHash.finish(hash, 2); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerChannelAction)) { + return false; + } + return this._channel === obj._channel; + } + toString() { + return `channel(${this._channel})`; + } + }; + __decorate([ + Decorators_1.Override + ], LexerChannelAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerChannelAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerChannelAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerChannelAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerChannelAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerChannelAction$1.prototype, "toString", null); + LexerChannelAction.LexerChannelAction = LexerChannelAction$1; + + return LexerChannelAction; +} + +var LexerCustomAction = {}; + +var hasRequiredLexerCustomAction; + +function requireLexerCustomAction () { + if (hasRequiredLexerCustomAction) return LexerCustomAction; + hasRequiredLexerCustomAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerCustomAction && LexerCustomAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerCustomAction && LexerCustomAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerCustomAction, "__esModule", { value: true }); + LexerCustomAction.LexerCustomAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Executes a custom lexer action by calling {@link Recognizer#action} with the + * rule and action indexes assigned to the custom action. The implementation of + * a custom action is added to the generated code for the lexer in an override + * of {@link Recognizer#action} when the grammar is compiled. + * + * This class may represent embedded actions created with the `{...}` + * syntax in ANTLR 4, as well as actions created for lexer commands where the + * command argument could not be evaluated when the grammar was compiled. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerCustomAction$1 = class LexerCustomAction { + /** + * Constructs a custom lexer action with the specified rule and action + * indexes. + * + * @param ruleIndex The rule index to use for calls to + * {@link Recognizer#action}. + * @param actionIndex The action index to use for calls to + * {@link Recognizer#action}. + */ + constructor(ruleIndex, actionIndex) { + this._ruleIndex = ruleIndex; + this._actionIndex = actionIndex; + } + /** + * Gets the rule index to use for calls to {@link Recognizer#action}. + * + * @returns The rule index for the custom action. + */ + get ruleIndex() { + return this._ruleIndex; + } + /** + * Gets the action index to use for calls to {@link Recognizer#action}. + * + * @returns The action index for the custom action. + */ + get actionIndex() { + return this._actionIndex; + } + /** + * {@inheritDoc} + * + * @returns This method returns {@link LexerActionType#CUSTOM}. + */ + get actionType() { + return 1 /* CUSTOM */; + } + /** + * Gets whether the lexer action is position-dependent. Position-dependent + * actions may have different semantics depending on the {@link CharStream} + * index at the time the action is executed. + * + * Custom actions are position-dependent since they may represent a + * user-defined embedded action which makes calls to methods like + * {@link Lexer#getText}. + * + * @returns This method returns `true`. + */ + get isPositionDependent() { + return true; + } + /** + * {@inheritDoc} + * + * Custom actions are implemented by calling {@link Lexer#action} with the + * appropriate rule and action indexes. + */ + execute(lexer) { + lexer.action(undefined, this._ruleIndex, this._actionIndex); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + hash = MurmurHash_1.MurmurHash.update(hash, this._ruleIndex); + hash = MurmurHash_1.MurmurHash.update(hash, this._actionIndex); + return MurmurHash_1.MurmurHash.finish(hash, 3); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerCustomAction)) { + return false; + } + return this._ruleIndex === obj._ruleIndex + && this._actionIndex === obj._actionIndex; + } + }; + __decorate([ + Decorators_1.Override + ], LexerCustomAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerCustomAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerCustomAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerCustomAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerCustomAction$1.prototype, "equals", null); + LexerCustomAction.LexerCustomAction = LexerCustomAction$1; + + return LexerCustomAction; +} + +var LexerModeAction = {}; + +var hasRequiredLexerModeAction; + +function requireLexerModeAction () { + if (hasRequiredLexerModeAction) return LexerModeAction; + hasRequiredLexerModeAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerModeAction && LexerModeAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerModeAction && LexerModeAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerModeAction, "__esModule", { value: true }); + LexerModeAction.LexerModeAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `mode` lexer action by calling {@link Lexer#mode} with + * the assigned mode. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerModeAction$1 = class LexerModeAction { + /** + * Constructs a new `mode` action with the specified mode value. + * @param mode The mode value to pass to {@link Lexer#mode}. + */ + constructor(mode) { + this._mode = mode; + } + /** + * Get the lexer mode this action should transition the lexer to. + * + * @returns The lexer mode for this `mode` command. + */ + get mode() { + return this._mode; + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#MODE}. + */ + get actionType() { + return 2 /* MODE */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#mode} with the + * value provided by {@link #getMode}. + */ + execute(lexer) { + lexer.mode(this._mode); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + hash = MurmurHash_1.MurmurHash.update(hash, this._mode); + return MurmurHash_1.MurmurHash.finish(hash, 2); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerModeAction)) { + return false; + } + return this._mode === obj._mode; + } + toString() { + return `mode(${this._mode})`; + } + }; + __decorate([ + Decorators_1.Override + ], LexerModeAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerModeAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerModeAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerModeAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerModeAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerModeAction$1.prototype, "toString", null); + LexerModeAction.LexerModeAction = LexerModeAction$1; + + return LexerModeAction; +} + +var LexerMoreAction = {}; + +var hasRequiredLexerMoreAction; + +function requireLexerMoreAction () { + if (hasRequiredLexerMoreAction) return LexerMoreAction; + hasRequiredLexerMoreAction = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerMoreAction && LexerMoreAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerMoreAction && LexerMoreAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LexerMoreAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `more` lexer action by calling {@link Lexer#more}. + * + * The `more` command does not have any parameters, so this action is + * implemented as a singleton instance exposed by {@link #INSTANCE}. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerMoreAction$1 = class LexerMoreAction { + /** + * Constructs the singleton instance of the lexer `more` command. + */ + constructor() { + // intentionally empty + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#MORE}. + */ + get actionType() { + return 3 /* MORE */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#more}. + */ + execute(lexer) { + lexer.more(); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + return MurmurHash_1.MurmurHash.finish(hash, 1); + } + equals(obj) { + return obj === this; + } + toString() { + return "more"; + } + }; + __decorate([ + Decorators_1.Override + ], LexerMoreAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerMoreAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerMoreAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerMoreAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerMoreAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerMoreAction$1.prototype, "toString", null); + exports.LexerMoreAction = LexerMoreAction$1; + (function (LexerMoreAction) { + /** + * Provides a singleton instance of this parameterless lexer action. + */ + LexerMoreAction.INSTANCE = new LexerMoreAction(); + })(LexerMoreAction$1 = exports.LexerMoreAction || (exports.LexerMoreAction = {})); + + } (LexerMoreAction)); + return LexerMoreAction; +} + +var LexerPopModeAction = {}; + +var hasRequiredLexerPopModeAction; + +function requireLexerPopModeAction () { + if (hasRequiredLexerPopModeAction) return LexerPopModeAction; + hasRequiredLexerPopModeAction = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerPopModeAction && LexerPopModeAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerPopModeAction && LexerPopModeAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LexerPopModeAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `popMode` lexer action by calling {@link Lexer#popMode}. + * + * The `popMode` command does not have any parameters, so this action is + * implemented as a singleton instance exposed by {@link #INSTANCE}. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerPopModeAction$1 = class LexerPopModeAction { + /** + * Constructs the singleton instance of the lexer `popMode` command. + */ + constructor() { + // intentionally empty + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#POP_MODE}. + */ + get actionType() { + return 4 /* POP_MODE */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#popMode}. + */ + execute(lexer) { + lexer.popMode(); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + return MurmurHash_1.MurmurHash.finish(hash, 1); + } + equals(obj) { + return obj === this; + } + toString() { + return "popMode"; + } + }; + __decorate([ + Decorators_1.Override + ], LexerPopModeAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerPopModeAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerPopModeAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerPopModeAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerPopModeAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerPopModeAction$1.prototype, "toString", null); + exports.LexerPopModeAction = LexerPopModeAction$1; + (function (LexerPopModeAction) { + /** + * Provides a singleton instance of this parameterless lexer action. + */ + LexerPopModeAction.INSTANCE = new LexerPopModeAction(); + })(LexerPopModeAction$1 = exports.LexerPopModeAction || (exports.LexerPopModeAction = {})); + + } (LexerPopModeAction)); + return LexerPopModeAction; +} + +var LexerPushModeAction = {}; + +var hasRequiredLexerPushModeAction; + +function requireLexerPushModeAction () { + if (hasRequiredLexerPushModeAction) return LexerPushModeAction; + hasRequiredLexerPushModeAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerPushModeAction && LexerPushModeAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerPushModeAction && LexerPushModeAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerPushModeAction, "__esModule", { value: true }); + LexerPushModeAction.LexerPushModeAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `pushMode` lexer action by calling + * {@link Lexer#pushMode} with the assigned mode. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerPushModeAction$1 = class LexerPushModeAction { + /** + * Constructs a new `pushMode` action with the specified mode value. + * @param mode The mode value to pass to {@link Lexer#pushMode}. + */ + constructor(mode) { + this._mode = mode; + } + /** + * Get the lexer mode this action should transition the lexer to. + * + * @returns The lexer mode for this `pushMode` command. + */ + get mode() { + return this._mode; + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#PUSH_MODE}. + */ + get actionType() { + return 5 /* PUSH_MODE */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#pushMode} with the + * value provided by {@link #getMode}. + */ + execute(lexer) { + lexer.pushMode(this._mode); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + hash = MurmurHash_1.MurmurHash.update(hash, this._mode); + return MurmurHash_1.MurmurHash.finish(hash, 2); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerPushModeAction)) { + return false; + } + return this._mode === obj._mode; + } + toString() { + return `pushMode(${this._mode})`; + } + }; + __decorate([ + Decorators_1.Override + ], LexerPushModeAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerPushModeAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerPushModeAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerPushModeAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerPushModeAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerPushModeAction$1.prototype, "toString", null); + LexerPushModeAction.LexerPushModeAction = LexerPushModeAction$1; + + return LexerPushModeAction; +} + +var LexerSkipAction = {}; + +var hasRequiredLexerSkipAction; + +function requireLexerSkipAction () { + if (hasRequiredLexerSkipAction) return LexerSkipAction; + hasRequiredLexerSkipAction = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerSkipAction && LexerSkipAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerSkipAction && LexerSkipAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LexerSkipAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `skip` lexer action by calling {@link Lexer#skip}. + * + * The `skip` command does not have any parameters, so this action is + * implemented as a singleton instance exposed by {@link #INSTANCE}. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerSkipAction$1 = class LexerSkipAction { + /** + * Constructs the singleton instance of the lexer `skip` command. + */ + constructor() { + // intentionally empty + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#SKIP}. + */ + get actionType() { + return 6 /* SKIP */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by calling {@link Lexer#skip}. + */ + execute(lexer) { + lexer.skip(); + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + return MurmurHash_1.MurmurHash.finish(hash, 1); + } + equals(obj) { + return obj === this; + } + toString() { + return "skip"; + } + }; + __decorate([ + Decorators_1.Override + ], LexerSkipAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerSkipAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerSkipAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerSkipAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerSkipAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerSkipAction$1.prototype, "toString", null); + exports.LexerSkipAction = LexerSkipAction$1; + (function (LexerSkipAction) { + /** + * Provides a singleton instance of this parameterless lexer action. + */ + LexerSkipAction.INSTANCE = new LexerSkipAction(); + })(LexerSkipAction$1 = exports.LexerSkipAction || (exports.LexerSkipAction = {})); + + } (LexerSkipAction)); + return LexerSkipAction; +} + +var LexerTypeAction = {}; + +var hasRequiredLexerTypeAction; + +function requireLexerTypeAction () { + if (hasRequiredLexerTypeAction) return LexerTypeAction; + hasRequiredLexerTypeAction = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerTypeAction && LexerTypeAction.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerTypeAction && LexerTypeAction.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerTypeAction, "__esModule", { value: true }); + LexerTypeAction.LexerTypeAction = void 0; + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + /** + * Implements the `type` lexer action by setting `Lexer.type` + * with the assigned type. + * + * @author Sam Harwell + * @since 4.2 + */ + let LexerTypeAction$1 = class LexerTypeAction { + /** + * Constructs a new `type` action with the specified token type value. + * @param type The type to assign to the token using `Lexer.type`. + */ + constructor(type) { + this._type = type; + } + /** + * Gets the type to assign to a token created by the lexer. + * @returns The type to assign to a token created by the lexer. + */ + get type() { + return this._type; + } + /** + * {@inheritDoc} + * @returns This method returns {@link LexerActionType#TYPE}. + */ + get actionType() { + return 7 /* TYPE */; + } + /** + * {@inheritDoc} + * @returns This method returns `false`. + */ + get isPositionDependent() { + return false; + } + /** + * {@inheritDoc} + * + * This action is implemented by setting `Lexer.type` with the + * value provided by `type`. + */ + execute(lexer) { + lexer.type = this._type; + } + hashCode() { + let hash = MurmurHash_1.MurmurHash.initialize(); + hash = MurmurHash_1.MurmurHash.update(hash, this.actionType); + hash = MurmurHash_1.MurmurHash.update(hash, this._type); + return MurmurHash_1.MurmurHash.finish(hash, 2); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof LexerTypeAction)) { + return false; + } + return this._type === obj._type; + } + toString() { + return `type(${this._type})`; + } + }; + __decorate([ + Decorators_1.Override + ], LexerTypeAction$1.prototype, "actionType", null); + __decorate([ + Decorators_1.Override + ], LexerTypeAction$1.prototype, "isPositionDependent", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], LexerTypeAction$1.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], LexerTypeAction$1.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], LexerTypeAction$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], LexerTypeAction$1.prototype, "toString", null); + LexerTypeAction.LexerTypeAction = LexerTypeAction$1; + + return LexerTypeAction; +} + +var LoopEndState = {}; + +var hasRequiredLoopEndState; + +function requireLoopEndState () { + if (hasRequiredLoopEndState) return LoopEndState; + hasRequiredLoopEndState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LoopEndState && LoopEndState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(LoopEndState, "__esModule", { value: true }); + LoopEndState.LoopEndState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:30.7737978-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + /** Mark the end of a * or + loop. */ + let LoopEndState$1 = class LoopEndState extends ATNState_1.ATNState { + get stateType() { + return ATNStateType_1.ATNStateType.LOOP_END; + } + }; + __decorate([ + Decorators_1.Override + ], LoopEndState$1.prototype, "stateType", null); + LoopEndState.LoopEndState = LoopEndState$1; + + return LoopEndState; +} + +var ParserATNSimulator = {}; + +var ConflictInfo = {}; + +var hasRequiredConflictInfo; + +function requireConflictInfo () { + if (hasRequiredConflictInfo) return ConflictInfo; + hasRequiredConflictInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ConflictInfo && ConflictInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ConflictInfo, "__esModule", { value: true }); + ConflictInfo.ConflictInfo = void 0; + const Decorators_1 = requireDecorators(); + const Utils = requireUtils(); + /** + * This class stores information about a configuration conflict. + * + * @author Sam Harwell + */ + let ConflictInfo$1 = class ConflictInfo { + constructor(conflictedAlts, exact) { + this._conflictedAlts = conflictedAlts; + this.exact = exact; + } + /** + * Gets the set of conflicting alternatives for the configuration set. + */ + get conflictedAlts() { + return this._conflictedAlts; + } + /** + * Gets whether or not the configuration conflict is an exact conflict. + * An exact conflict occurs when the prediction algorithm determines that + * the represented alternatives for a particular configuration set cannot be + * further reduced by consuming additional input. After reaching an exact + * conflict during an SLL prediction, only switch to full-context prediction + * could reduce the set of viable alternatives. In LL prediction, an exact + * conflict indicates a true ambiguity in the input. + * + * For the {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} prediction mode, + * accept states are conflicting but not exact are treated as non-accept + * states. + */ + get isExact() { + return this.exact; + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof ConflictInfo)) { + return false; + } + return this.isExact === obj.isExact + && Utils.equals(this.conflictedAlts, obj.conflictedAlts); + } + hashCode() { + return this.conflictedAlts.hashCode(); + } + }; + __decorate([ + Decorators_1.Override + ], ConflictInfo$1.prototype, "equals", null); + __decorate([ + Decorators_1.Override + ], ConflictInfo$1.prototype, "hashCode", null); + ConflictInfo.ConflictInfo = ConflictInfo$1; + + return ConflictInfo; +} + +var ParserRuleContext = {}; + +var ErrorNode = {}; + +var TerminalNode = {}; + +var hasRequiredTerminalNode; + +function requireTerminalNode () { + if (hasRequiredTerminalNode) return TerminalNode; + hasRequiredTerminalNode = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TerminalNode && TerminalNode.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(TerminalNode, "__esModule", { value: true }); + TerminalNode.TerminalNode = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:48.1433686-07:00 + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + let TerminalNode$1 = class TerminalNode { + constructor(symbol) { + this._symbol = symbol; + } + getChild(i) { + throw new RangeError("Terminal Node has no children."); + } + get symbol() { + return this._symbol; + } + get parent() { + return this._parent; + } + setParent(parent) { + this._parent = parent; + } + get payload() { + return this._symbol; + } + get sourceInterval() { + let tokenIndex = this._symbol.tokenIndex; + return new Interval_1.Interval(tokenIndex, tokenIndex); + } + get childCount() { + return 0; + } + accept(visitor) { + return visitor.visitTerminal(this); + } + get text() { + return this._symbol.text || ""; + } + toStringTree(parser) { + return this.toString(); + } + toString() { + if (this._symbol.type === Token_1.Token.EOF) { + return ""; + } + return this._symbol.text || ""; + } + }; + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "getChild", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "parent", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "setParent", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "payload", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "sourceInterval", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "childCount", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "accept", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "toStringTree", null); + __decorate([ + Decorators_1.Override + ], TerminalNode$1.prototype, "toString", null); + TerminalNode.TerminalNode = TerminalNode$1; + + return TerminalNode; +} + +var hasRequiredErrorNode; + +function requireErrorNode () { + if (hasRequiredErrorNode) return ErrorNode; + hasRequiredErrorNode = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ErrorNode && ErrorNode.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ErrorNode, "__esModule", { value: true }); + ErrorNode.ErrorNode = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:47.4646355-07:00 + const Decorators_1 = requireDecorators(); + const TerminalNode_1 = requireTerminalNode(); + /** Represents a token that was consumed during resynchronization + * rather than during a valid match operation. For example, + * we will create this kind of a node during single token insertion + * and deletion as well as during "consume until error recovery set" + * upon no viable alternative exceptions. + */ + let ErrorNode$1 = class ErrorNode extends TerminalNode_1.TerminalNode { + constructor(token) { + super(token); + } + accept(visitor) { + return visitor.visitErrorNode(this); + } + }; + __decorate([ + Decorators_1.Override + ], ErrorNode$1.prototype, "accept", null); + ErrorNode.ErrorNode = ErrorNode$1; + + return ErrorNode; +} + +var RuleContext = {}; + +var RuleNode = {}; + +var hasRequiredRuleNode; + +function requireRuleNode () { + if (hasRequiredRuleNode) return RuleNode; + hasRequiredRuleNode = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(RuleNode, "__esModule", { value: true }); + RuleNode.RuleNode = void 0; + let RuleNode$1 = class RuleNode { + }; + RuleNode.RuleNode = RuleNode$1; + + return RuleNode; +} + +var Trees = {}; + +var hasRequiredTrees; + +function requireTrees () { + if (hasRequiredTrees) return Trees; + hasRequiredTrees = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Trees && Trees.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (Trees && Trees.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(Trees, "__esModule", { value: true }); + Trees.Trees = void 0; + const ATN_1 = requireATN(); + const CommonToken_1 = requireCommonToken(); + const ErrorNode_1 = requireErrorNode(); + const Decorators_1 = requireDecorators(); + const Parser_1 = requireParser$1(); + const ParserRuleContext_1 = requireParserRuleContext(); + const RuleNode_1 = requireRuleNode(); + const TerminalNode_1 = requireTerminalNode(); + const Token_1 = requireToken(); + const Utils = requireUtils(); + /** A set of utility routines useful for all kinds of ANTLR trees. */ + let Trees$1 = class Trees { + static toStringTree(t, arg2) { + let ruleNames; + if (arg2 instanceof Parser_1.Parser) { + ruleNames = arg2.ruleNames; + } + else { + ruleNames = arg2; + } + let s = Utils.escapeWhitespace(this.getNodeText(t, ruleNames), false); + if (t.childCount === 0) { + return s; + } + let buf = ""; + buf += ("("); + s = Utils.escapeWhitespace(this.getNodeText(t, ruleNames), false); + buf += (s); + buf += (" "); + for (let i = 0; i < t.childCount; i++) { + if (i > 0) { + buf += (" "); + } + buf += (this.toStringTree(t.getChild(i), ruleNames)); + } + buf += (")"); + return buf; + } + static getNodeText(t, arg2) { + let ruleNames; + if (arg2 instanceof Parser_1.Parser) { + ruleNames = arg2.ruleNames; + } + else if (arg2) { + ruleNames = arg2; + } + else { + // no recog or rule names + let payload = t.payload; + if (typeof payload.text === "string") { + return payload.text; + } + return t.payload.toString(); + } + if (t instanceof RuleNode_1.RuleNode) { + let ruleContext = t.ruleContext; + let ruleIndex = ruleContext.ruleIndex; + let ruleName = ruleNames[ruleIndex]; + let altNumber = ruleContext.altNumber; + if (altNumber !== ATN_1.ATN.INVALID_ALT_NUMBER) { + return ruleName + ":" + altNumber; + } + return ruleName; + } + else if (t instanceof ErrorNode_1.ErrorNode) { + return t.toString(); + } + else if (t instanceof TerminalNode_1.TerminalNode) { + let symbol = t.symbol; + return symbol.text || ""; + } + throw new TypeError("Unexpected node type"); + } + static getChildren(t) { + let kids = []; + for (let i = 0; i < t.childCount; i++) { + kids.push(t.getChild(i)); + } + return kids; + } + static getAncestors(t) { + let ancestors = []; + let p = t.parent; + while (p) { + ancestors.unshift(p); // insert at start + p = p.parent; + } + return ancestors; + } + /** Return true if t is u's parent or a node on path to root from u. + * Use === not equals(). + * + * @since 4.5.1 + */ + static isAncestorOf(t, u) { + if (!t || !u || !t.parent) { + return false; + } + let p = u.parent; + while (p) { + if (t === p) { + return true; + } + p = p.parent; + } + return false; + } + static findAllTokenNodes(t, ttype) { + return Trees.findAllNodes(t, ttype, true); + } + static findAllRuleNodes(t, ruleIndex) { + return Trees.findAllNodes(t, ruleIndex, false); + } + static findAllNodes(t, index, findTokens) { + let nodes = []; + Trees._findAllNodes(t, index, findTokens, nodes); + return nodes; + } + static _findAllNodes(t, index, findTokens, nodes) { + // check this node (the root) first + if (findTokens && t instanceof TerminalNode_1.TerminalNode) { + if (t.symbol.type === index) { + nodes.push(t); + } + } + else if (!findTokens && t instanceof ParserRuleContext_1.ParserRuleContext) { + if (t.ruleIndex === index) { + nodes.push(t); + } + } + // check children + for (let i = 0; i < t.childCount; i++) { + Trees._findAllNodes(t.getChild(i), index, findTokens, nodes); + } + } + /** Get all descendents; includes t itself. + * + * @since 4.5.1 + */ + static getDescendants(t) { + let nodes = []; + function recurse(e) { + nodes.push(e); + const n = e.childCount; + for (let i = 0; i < n; i++) { + recurse(e.getChild(i)); + } + } + recurse(t); + return nodes; + } + /** Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex + * inclusively using postorder traversal. Recursive depth-first-search. + * + * @since 4.5 + */ + static getRootOfSubtreeEnclosingRegion(t, startTokenIndex, // inclusive + stopTokenIndex) { + let n = t.childCount; + for (let i = 0; i < n; i++) { + let child = t.getChild(i); + let r = Trees.getRootOfSubtreeEnclosingRegion(child, startTokenIndex, stopTokenIndex); + if (r) { + return r; + } + } + if (t instanceof ParserRuleContext_1.ParserRuleContext) { + let stopToken = t.stop; + if (startTokenIndex >= t.start.tokenIndex && // is range fully contained in t? + (stopToken == null || stopTokenIndex <= stopToken.tokenIndex)) { + // note: r.stop==null likely implies that we bailed out of parser and there's nothing to the right + return t; + } + } + return undefined; + } + /** Replace any subtree siblings of root that are completely to left + * or right of lookahead range with a CommonToken(Token.INVALID_TYPE,"...") + * node. The source interval for t is not altered to suit smaller range! + * + * WARNING: destructive to t. + * + * @since 4.5.1 + */ + static stripChildrenOutOfRange(t, root, startIndex, stopIndex) { + if (!t) { + return; + } + let count = t.childCount; + for (let i = 0; i < count; i++) { + let child = t.getChild(i); + let range = child.sourceInterval; + if (child instanceof ParserRuleContext_1.ParserRuleContext && (range.b < startIndex || range.a > stopIndex)) { + if (Trees.isAncestorOf(child, root)) { // replace only if subtree doesn't have displayed root + let abbrev = new CommonToken_1.CommonToken(Token_1.Token.INVALID_TYPE, "..."); + t.children[i] = new TerminalNode_1.TerminalNode(abbrev); // HACK access to private + } + } + } + } + static findNodeSuchThat(t, pred) { + // No type check needed as long as users only use one of the available overloads + if (pred(t)) { + return t; + } + let n = t.childCount; + for (let i = 0; i < n; i++) { + let u = Trees.findNodeSuchThat(t.getChild(i), pred); + if (u !== undefined) { + return u; + } + } + return undefined; + } + }; + __decorate([ + __param(0, Decorators_1.NotNull) + ], Trees$1, "toStringTree", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], Trees$1, "getAncestors", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], Trees$1, "getRootOfSubtreeEnclosingRegion", null); + Trees.Trees = Trees$1; + + return Trees; +} + +var hasRequiredRuleContext; + +function requireRuleContext () { + if (hasRequiredRuleContext) return RuleContext; + hasRequiredRuleContext = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleContext && RuleContext.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(RuleContext, "__esModule", { value: true }); + RuleContext.RuleContext = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:57.3490837-07:00 + const ATN_1 = requireATN(); + const Recognizer_1 = requireRecognizer(); + const RuleNode_1 = requireRuleNode(); + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const ParserRuleContext_1 = requireParserRuleContext(); + /** A rule context is a record of a single rule invocation. + * + * We form a stack of these context objects using the parent + * pointer. A parent pointer of `undefined` indicates that the current + * context is the bottom of the stack. The ParserRuleContext subclass + * as a children list so that we can turn this data structure into a + * tree. + * + * The root node always has a `undefined` pointer and invokingState of -1. + * + * Upon entry to parsing, the first invoked rule function creates a + * context object (a subclass specialized for that rule such as + * SContext) and makes it the root of a parse tree, recorded by field + * Parser._ctx. + * + * public final SContext s() throws RecognitionException { + * SContext _localctx = new SContext(_ctx, state); <-- create new node + * enterRule(_localctx, 0, RULE_s); <-- push it + * ... + * exitRule(); <-- pop back to _localctx + * return _localctx; + * } + * + * A subsequent rule invocation of r from the start rule s pushes a + * new context object for r whose parent points at s and use invoking + * state is the state with r emanating as edge label. + * + * The invokingState fields from a context object to the root + * together form a stack of rule indication states where the root + * (bottom of the stack) has a -1 sentinel value. If we invoke start + * symbol s then call r1, which calls r2, the would look like + * this: + * + * SContext[-1] <- root node (bottom of the stack) + * R1Context[p] <- p in rule s called r1 + * R2Context[q] <- q in rule r1 called r2 + * + * So the top of the stack, _ctx, represents a call to the current + * rule and it holds the return address from another rule that invoke + * to this rule. To invoke a rule, we must always have a current context. + * + * The parent contexts are useful for computing lookahead sets and + * getting error information. + * + * These objects are used during parsing and prediction. + * For the special case of parsers, we use the subclass + * ParserRuleContext. + * + * @see ParserRuleContext + */ + let RuleContext$1 = class RuleContext extends RuleNode_1.RuleNode { + constructor(parent, invokingState) { + super(); + this._parent = parent; + this.invokingState = invokingState != null ? invokingState : -1; + } + static getChildContext(parent, invokingState) { + return new RuleContext(parent, invokingState); + } + depth() { + let n = 0; + let p = this; + while (p) { + p = p._parent; + n++; + } + return n; + } + /** A context is empty if there is no invoking state; meaning nobody called + * current context. + */ + get isEmpty() { + return this.invokingState === -1; + } + // satisfy the ParseTree / SyntaxTree interface + get sourceInterval() { + return Interval_1.Interval.INVALID; + } + get ruleContext() { return this; } + get parent() { return this._parent; } + /** @since 4.7. {@see ParseTree#setParent} comment */ + setParent(parent) { + this._parent = parent; + } + get payload() { return this; } + /** Return the combined text of all child nodes. This method only considers + * tokens which have been added to the parse tree. + * + * Since tokens on hidden channels (e.g. whitespace or comments) are not + * added to the parse trees, they will not appear in the output of this + * method. + */ + get text() { + if (this.childCount === 0) { + return ""; + } + let builder = ""; + for (let i = 0; i < this.childCount; i++) { + builder += this.getChild(i).text; + } + return builder.toString(); + } + get ruleIndex() { return -1; } + /** For rule associated with this parse tree internal node, return + * the outer alternative number used to match the input. Default + * implementation does not compute nor store this alt num. Create + * a subclass of ParserRuleContext with backing field and set + * option contextSuperClass. + * to set it. + * + * @since 4.5.3 + */ + get altNumber() { return ATN_1.ATN.INVALID_ALT_NUMBER; } + /** Set the outer alternative number for this context node. Default + * implementation does nothing to avoid backing field overhead for + * trees that don't need it. Create + * a subclass of ParserRuleContext with backing field and set + * option contextSuperClass. + * + * @since 4.5.3 + */ + set altNumber(altNumber) { + // intentionally ignored by the base implementation + } + getChild(i) { + throw new RangeError("i must be greater than or equal to 0 and less than childCount"); + } + get childCount() { + return 0; + } + accept(visitor) { + return visitor.visitChildren(this); + } + toStringTree(recog) { + return Trees_1.Trees.toStringTree(this, recog); + } + toString(arg1, stop) { + const ruleNames = (arg1 instanceof Recognizer_1.Recognizer) ? arg1.ruleNames : arg1; + stop = stop || ParserRuleContext_1.ParserRuleContext.emptyContext(); + let buf = ""; + let p = this; + buf += ("["); + while (p && p !== stop) { + if (!ruleNames) { + if (!p.isEmpty) { + buf += (p.invokingState); + } + } + else { + let ruleIndex = p.ruleIndex; + let ruleName = (ruleIndex >= 0 && ruleIndex < ruleNames.length) + ? ruleNames[ruleIndex] : ruleIndex.toString(); + buf += (ruleName); + } + if (p._parent && (ruleNames || !p._parent.isEmpty)) { + buf += (" "); + } + p = p._parent; + } + buf += ("]"); + return buf.toString(); + } + }; + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "sourceInterval", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "ruleContext", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "parent", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "setParent", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "payload", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "getChild", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "childCount", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "accept", null); + __decorate([ + Decorators_1.Override + ], RuleContext$1.prototype, "toStringTree", null); + RuleContext.RuleContext = RuleContext$1; + + return RuleContext; +} + +var hasRequiredParserRuleContext; + +function requireParserRuleContext () { + if (hasRequiredParserRuleContext) return ParserRuleContext; + hasRequiredParserRuleContext = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParserRuleContext && ParserRuleContext.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ParserRuleContext, "__esModule", { value: true }); + ParserRuleContext.ParserRuleContext = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:56.6285494-07:00 + const ErrorNode_1 = requireErrorNode(); + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + const RuleContext_1 = requireRuleContext(); + const TerminalNode_1 = requireTerminalNode(); + /** A rule invocation record for parsing. + * + * Contains all of the information about the current rule not stored in the + * RuleContext. It handles parse tree children list, Any ATN state + * tracing, and the default values available for rule invocations: + * start, stop, rule index, current alt number. + * + * Subclasses made for each rule and grammar track the parameters, + * return values, locals, and labels specific to that rule. These + * are the objects that are returned from rules. + * + * Note text is not an actual field of a rule return value; it is computed + * from start and stop using the input stream's toString() method. I + * could add a ctor to this so that we can pass in and store the input + * stream, but I'm not sure we want to do that. It would seem to be undefined + * to get the .text property anyway if the rule matches tokens from multiple + * input streams. + * + * I do not use getters for fields of objects that are used simply to + * group values such as this aggregate. The getters/setters are there to + * satisfy the superclass interface. + */ + let ParserRuleContext$1 = class ParserRuleContext extends RuleContext_1.RuleContext { + constructor(parent, invokingStateNumber) { + if (invokingStateNumber == null) { + super(); + } + else { + super(parent, invokingStateNumber); + } + } + static emptyContext() { + return ParserRuleContext.EMPTY; + } + /** + * COPY a ctx (I'm deliberately not using copy constructor) to avoid + * confusion with creating node with parent. Does not copy children + * (except error leaves). + * + * This is used in the generated parser code to flip a generic XContext + * node for rule X to a YContext for alt label Y. In that sense, it is not + * really a generic copy function. + * + * If we do an error sync() at start of a rule, we might add error nodes + * to the generic XContext so this function must copy those nodes to the + * YContext as well else they are lost! + */ + copyFrom(ctx) { + this._parent = ctx._parent; + this.invokingState = ctx.invokingState; + this._start = ctx._start; + this._stop = ctx._stop; + // copy any error nodes to alt label node + if (ctx.children) { + this.children = []; + // reset parent pointer for any error nodes + for (let child of ctx.children) { + if (child instanceof ErrorNode_1.ErrorNode) { + this.addChild(child); + } + } + } + } + // Double dispatch methods for listeners + enterRule(listener) { + // intentionally empty + } + exitRule(listener) { + // intentionally empty + } + /** Add a parse tree node to this as a child. Works for + * internal and leaf nodes. Does not set parent link; + * other add methods must do that. Other addChild methods + * call this. + * + * We cannot set the parent pointer of the incoming node + * because the existing interfaces do not have a setParent() + * method and I don't want to break backward compatibility for this. + * + * @since 4.7 + */ + addAnyChild(t) { + if (!this.children) { + this.children = [t]; + } + else { + this.children.push(t); + } + return t; + } + addChild(t) { + if (t instanceof TerminalNode_1.TerminalNode) { + t.setParent(this); + this.addAnyChild(t); + return; + } + else if (t instanceof RuleContext_1.RuleContext) { + // Does not set parent link + this.addAnyChild(t); + return; + } + else { + // Deprecated code path + t = new TerminalNode_1.TerminalNode(t); + this.addAnyChild(t); + t.setParent(this); + return t; + } + } + addErrorNode(node) { + if (node instanceof ErrorNode_1.ErrorNode) { + const errorNode = node; + errorNode.setParent(this); + return this.addAnyChild(errorNode); + } + else { + // deprecated path + const badToken = node; + let t = new ErrorNode_1.ErrorNode(badToken); + this.addAnyChild(t); + t.setParent(this); + return t; + } + } + // public void trace(int s) { + // if ( states==null ) states = new ArrayList(); + // states.add(s); + // } + /** Used by enterOuterAlt to toss out a RuleContext previously added as + * we entered a rule. If we have # label, we will need to remove + * generic ruleContext object. + */ + removeLastChild() { + if (this.children) { + this.children.pop(); + } + } + get parent() { + let parent = super.parent; + if (parent === undefined || parent instanceof ParserRuleContext) { + return parent; + } + throw new TypeError("Invalid parent type for ParserRuleContext"); + } + // Note: in TypeScript, order or arguments reversed + getChild(i, ctxType) { + if (!this.children || i < 0 || i >= this.children.length) { + throw new RangeError("index parameter must be between >= 0 and <= number of children."); + } + if (ctxType == null) { + return this.children[i]; + } + let result = this.tryGetChild(i, ctxType); + if (result === undefined) { + throw new Error("The specified node does not exist"); + } + return result; + } + tryGetChild(i, ctxType) { + if (!this.children || i < 0 || i >= this.children.length) { + return undefined; + } + let j = -1; // what node with ctxType have we found? + for (let o of this.children) { + if (o instanceof ctxType) { + j++; + if (j === i) { + return o; + } + } + } + return undefined; + } + getToken(ttype, i) { + let result = this.tryGetToken(ttype, i); + if (result === undefined) { + throw new Error("The specified token does not exist"); + } + return result; + } + tryGetToken(ttype, i) { + if (!this.children || i < 0 || i >= this.children.length) { + return undefined; + } + let j = -1; // what token with ttype have we found? + for (let o of this.children) { + if (o instanceof TerminalNode_1.TerminalNode) { + let symbol = o.symbol; + if (symbol.type === ttype) { + j++; + if (j === i) { + return o; + } + } + } + } + return undefined; + } + getTokens(ttype) { + let tokens = []; + if (!this.children) { + return tokens; + } + for (let o of this.children) { + if (o instanceof TerminalNode_1.TerminalNode) { + let symbol = o.symbol; + if (symbol.type === ttype) { + tokens.push(o); + } + } + } + return tokens; + } + get ruleContext() { + return this; + } + // NOTE: argument order change from Java version + getRuleContext(i, ctxType) { + return this.getChild(i, ctxType); + } + tryGetRuleContext(i, ctxType) { + return this.tryGetChild(i, ctxType); + } + getRuleContexts(ctxType) { + let contexts = []; + if (!this.children) { + return contexts; + } + for (let o of this.children) { + if (o instanceof ctxType) { + contexts.push(o); + } + } + return contexts; + } + get childCount() { + return this.children ? this.children.length : 0; + } + get sourceInterval() { + if (!this._start) { + return Interval_1.Interval.INVALID; + } + if (!this._stop || this._stop.tokenIndex < this._start.tokenIndex) { + return Interval_1.Interval.of(this._start.tokenIndex, this._start.tokenIndex - 1); // empty + } + return Interval_1.Interval.of(this._start.tokenIndex, this._stop.tokenIndex); + } + /** + * Get the initial token in this context. + * Note that the range from start to stop is inclusive, so for rules that do not consume anything + * (for example, zero length or error productions) this token may exceed stop. + */ + get start() { return this._start; } + /** + * Get the final token in this context. + * Note that the range from start to stop is inclusive, so for rules that do not consume anything + * (for example, zero length or error productions) this token may precede start. + */ + get stop() { return this._stop; } + /** Used for rule context info debugging during parse-time, not so much for ATN debugging */ + toInfoString(recognizer) { + let rules = recognizer.getRuleInvocationStack(this).reverse(); + return "ParserRuleContext" + rules + "{" + + "start=" + this._start + + ", stop=" + this._stop + + "}"; + } + }; + ParserRuleContext$1.EMPTY = new ParserRuleContext$1(); + __decorate([ + Decorators_1.Override + ], ParserRuleContext$1.prototype, "parent", null); + __decorate([ + Decorators_1.Override + ], ParserRuleContext$1.prototype, "childCount", null); + __decorate([ + Decorators_1.Override + ], ParserRuleContext$1.prototype, "sourceInterval", null); + ParserRuleContext.ParserRuleContext = ParserRuleContext$1; + + return ParserRuleContext; +} + +var PredictionMode = {}; + +var hasRequiredPredictionMode; + +function requirePredictionMode () { + if (hasRequiredPredictionMode) return PredictionMode; + hasRequiredPredictionMode = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PredictionMode && PredictionMode.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PredictionMode = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:36.2673893-07:00 + const Array2DHashMap_1 = requireArray2DHashMap(); + const MurmurHash_1 = requireMurmurHash(); + const Decorators_1 = requireDecorators(); + const RuleStopState_1 = requireRuleStopState(); + (function (PredictionMode) { + /** + * The SLL(*) prediction mode. This prediction mode ignores the current + * parser context when making predictions. This is the fastest prediction + * mode, and provides correct results for many grammars. This prediction + * mode is more powerful than the prediction mode provided by ANTLR 3, but + * may result in syntax errors for grammar and input combinations which are + * not SLL. + * + * When using this prediction mode, the parser will either return a correct + * parse tree (i.e. the same parse tree that would be returned with the + * {@link #LL} prediction mode), or it will report a syntax error. If a + * syntax error is encountered when using the {@link #SLL} prediction mode, + * it may be due to either an actual syntax error in the input or indicate + * that the particular combination of grammar and input requires the more + * powerful {@link #LL} prediction abilities to complete successfully. + * + * This prediction mode does not provide any guarantees for prediction + * behavior for syntactically-incorrect inputs. + */ + PredictionMode[PredictionMode["SLL"] = 0] = "SLL"; + /** + * The LL(*) prediction mode. This prediction mode allows the current parser + * context to be used for resolving SLL conflicts that occur during + * prediction. This is the fastest prediction mode that guarantees correct + * parse results for all combinations of grammars with syntactically correct + * inputs. + * + * When using this prediction mode, the parser will make correct decisions + * for all syntactically-correct grammar and input combinations. However, in + * cases where the grammar is truly ambiguous this prediction mode might not + * report a precise answer for *exactly which* alternatives are + * ambiguous. + * + * This prediction mode does not provide any guarantees for prediction + * behavior for syntactically-incorrect inputs. + */ + PredictionMode[PredictionMode["LL"] = 1] = "LL"; + /** + * The LL(*) prediction mode with exact ambiguity detection. In addition to + * the correctness guarantees provided by the {@link #LL} prediction mode, + * this prediction mode instructs the prediction algorithm to determine the + * complete and exact set of ambiguous alternatives for every ambiguous + * decision encountered while parsing. + * + * This prediction mode may be used for diagnosing ambiguities during + * grammar development. Due to the performance overhead of calculating sets + * of ambiguous alternatives, this prediction mode should be avoided when + * the exact results are not necessary. + * + * This prediction mode does not provide any guarantees for prediction + * behavior for syntactically-incorrect inputs. + */ + PredictionMode[PredictionMode["LL_EXACT_AMBIG_DETECTION"] = 2] = "LL_EXACT_AMBIG_DETECTION"; + })(exports.PredictionMode || (exports.PredictionMode = {})); + (function (PredictionMode) { + /** A Map that uses just the state and the stack context as the key. */ + // NOTE: Base type used to be FlexibleHashMap + class AltAndContextMap extends Array2DHashMap_1.Array2DHashMap { + constructor() { + super(AltAndContextConfigEqualityComparator.INSTANCE); + } + } + class AltAndContextConfigEqualityComparator { + AltAndContextConfigEqualityComparator() { + // intentionally empty + } + /** + * The hash code is only a function of the {@link ATNState#stateNumber} + * and {@link ATNConfig#context}. + */ + hashCode(o) { + let hashCode = MurmurHash_1.MurmurHash.initialize(7); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, o.state.stateNumber); + hashCode = MurmurHash_1.MurmurHash.update(hashCode, o.context); + hashCode = MurmurHash_1.MurmurHash.finish(hashCode, 2); + return hashCode; + } + equals(a, b) { + if (a === b) { + return true; + } + if (a == null || b == null) { + return false; + } + return a.state.stateNumber === b.state.stateNumber + && a.context.equals(b.context); + } + } + AltAndContextConfigEqualityComparator.INSTANCE = new AltAndContextConfigEqualityComparator(); + __decorate([ + Decorators_1.Override + ], AltAndContextConfigEqualityComparator.prototype, "hashCode", null); + __decorate([ + Decorators_1.Override + ], AltAndContextConfigEqualityComparator.prototype, "equals", null); + /** + * Checks if any configuration in `configs` is in a + * {@link RuleStopState}. Configurations meeting this condition have reached + * the end of the decision rule (local context) or end of start rule (full + * context). + * + * @param configs the configuration set to test + * @returns `true` if any configuration in `configs` is in a + * {@link RuleStopState}, otherwise `false` + */ + function hasConfigInRuleStopState(configs) { + for (let c of configs) { + if (c.state instanceof RuleStopState_1.RuleStopState) { + return true; + } + } + return false; + } + PredictionMode.hasConfigInRuleStopState = hasConfigInRuleStopState; + /** + * Checks if all configurations in `configs` are in a + * {@link RuleStopState}. Configurations meeting this condition have reached + * the end of the decision rule (local context) or end of start rule (full + * context). + * + * @param configs the configuration set to test + * @returns `true` if all configurations in `configs` are in a + * {@link RuleStopState}, otherwise `false` + */ + function allConfigsInRuleStopStates(/*@NotNull*/ configs) { + for (let config of configs) { + if (!(config.state instanceof RuleStopState_1.RuleStopState)) { + return false; + } + } + return true; + } + PredictionMode.allConfigsInRuleStopStates = allConfigsInRuleStopStates; + })(exports.PredictionMode || (exports.PredictionMode = {})); + + } (PredictionMode)); + return PredictionMode; +} + +var SimulatorState = {}; + +var hasRequiredSimulatorState; + +function requireSimulatorState () { + if (hasRequiredSimulatorState) return SimulatorState; + hasRequiredSimulatorState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (SimulatorState && SimulatorState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (SimulatorState && SimulatorState.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(SimulatorState, "__esModule", { value: true }); + SimulatorState.SimulatorState = void 0; + const Decorators_1 = requireDecorators(); + const ParserRuleContext_1 = requireParserRuleContext(); + /** + * + * @author Sam Harwell + */ + let SimulatorState$1 = class SimulatorState { + constructor(outerContext, s0, useContext, remainingOuterContext) { + this.outerContext = outerContext != null ? outerContext : ParserRuleContext_1.ParserRuleContext.emptyContext(); + this.s0 = s0; + this.useContext = useContext; + this.remainingOuterContext = remainingOuterContext; + } + }; + SimulatorState$1 = __decorate([ + __param(1, Decorators_1.NotNull) + ], SimulatorState$1); + SimulatorState.SimulatorState = SimulatorState$1; + + return SimulatorState; +} + +var hasRequiredParserATNSimulator; + +function requireParserATNSimulator () { + if (hasRequiredParserATNSimulator) return ParserATNSimulator; + hasRequiredParserATNSimulator = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParserATNSimulator && ParserATNSimulator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParserATNSimulator && ParserATNSimulator.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ParserATNSimulator, "__esModule", { value: true }); + ParserATNSimulator.ParserATNSimulator = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:31.1989835-07:00 + const AcceptStateInfo_1 = requireAcceptStateInfo(); + const ActionTransition_1 = requireActionTransition(); + const Array2DHashSet_1 = requireArray2DHashSet(); + const Arrays_1 = requireArrays(); + const ATN_1 = requireATN(); + const ATNConfig_1 = requireATNConfig(); + const ATNConfigSet_1 = requireATNConfigSet(); + const ATNSimulator_1 = requireATNSimulator(); + const ATNStateType_1 = requireATNStateType(); + const AtomTransition_1 = requireAtomTransition(); + const BitSet_1 = requireBitSet(); + const ConflictInfo_1 = requireConflictInfo(); + const DecisionState_1 = requireDecisionState(); + const DFAState_1 = requireDFAState(); + const IntegerList_1 = requireIntegerList(); + const Interval_1 = requireInterval(); + const IntStream_1 = requireIntStream(); + const Decorators_1 = requireDecorators(); + const NotSetTransition_1 = requireNotSetTransition(); + const NoViableAltException_1 = requireNoViableAltException(); + const ObjectEqualityComparator_1 = requireObjectEqualityComparator(); + const ParserRuleContext_1 = requireParserRuleContext(); + const PredictionContext_1 = requirePredictionContext(); + const PredictionContextCache_1 = requirePredictionContextCache(); + const PredictionMode_1 = requirePredictionMode(); + const RuleStopState_1 = requireRuleStopState(); + const RuleTransition_1 = requireRuleTransition(); + const SemanticContext_1 = requireSemanticContext(); + const SetTransition_1 = requireSetTransition(); + const SimulatorState_1 = requireSimulatorState(); + const Token_1 = requireToken(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const assert = require$$0$9; + const MAX_SHORT_VALUE = 0xFFFF; + const MIN_INTEGER_VALUE = -2147483648; + /** + * The embodiment of the adaptive LL(*), ALL(*), parsing strategy. + * + * The basic complexity of the adaptive strategy makes it harder to understand. + * We begin with ATN simulation to build paths in a DFA. Subsequent prediction + * requests go through the DFA first. If they reach a state without an edge for + * the current symbol, the algorithm fails over to the ATN simulation to + * complete the DFA path for the current input (until it finds a conflict state + * or uniquely predicting state). + * + * All of that is done without using the outer context because we want to create + * a DFA that is not dependent upon the rule invocation stack when we do a + * prediction. One DFA works in all contexts. We avoid using context not + * necessarily because it's slower, although it can be, but because of the DFA + * caching problem. The closure routine only considers the rule invocation stack + * created during prediction beginning in the decision rule. For example, if + * prediction occurs without invoking another rule's ATN, there are no context + * stacks in the configurations. When lack of context leads to a conflict, we + * don't know if it's an ambiguity or a weakness in the strong LL(*) parsing + * strategy (versus full LL(*)). + * + * When SLL yields a configuration set with conflict, we rewind the input and + * retry the ATN simulation, this time using full outer context without adding + * to the DFA. Configuration context stacks will be the full invocation stacks + * from the start rule. If we get a conflict using full context, then we can + * definitively say we have a true ambiguity for that input sequence. If we + * don't get a conflict, it implies that the decision is sensitive to the outer + * context. (It is not context-sensitive in the sense of context-sensitive + * grammars.) + * + * The next time we reach this DFA state with an SLL conflict, through DFA + * simulation, we will again retry the ATN simulation using full context mode. + * This is slow because we can't save the results and have to "interpret" the + * ATN each time we get that input. + * + * **CACHING FULL CONTEXT PREDICTIONS** + * + * We could cache results from full context to predicted alternative easily and + * that saves a lot of time but doesn't work in presence of predicates. The set + * of visible predicates from the ATN start state changes depending on the + * context, because closure can fall off the end of a rule. I tried to cache + * tuples (stack context, semantic context, predicted alt) but it was slower + * than interpreting and much more complicated. Also required a huge amount of + * memory. The goal is not to create the world's fastest parser anyway. I'd like + * to keep this algorithm simple. By launching multiple threads, we can improve + * the speed of parsing across a large number of files. + * + * There is no strict ordering between the amount of input used by SLL vs LL, + * which makes it really hard to build a cache for full context. Let's say that + * we have input A B C that leads to an SLL conflict with full context X. That + * implies that using X we might only use A B but we could also use A B C D to + * resolve conflict. Input A B C D could predict alternative 1 in one position + * in the input and A B C E could predict alternative 2 in another position in + * input. The conflicting SLL configurations could still be non-unique in the + * full context prediction, which would lead us to requiring more input than the + * original A B C. To make a prediction cache work, we have to track the exact + * input used during the previous prediction. That amounts to a cache that maps + * X to a specific DFA for that context. + * + * Something should be done for left-recursive expression predictions. They are + * likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry + * with full LL thing Sam does. + * + * **AVOIDING FULL CONTEXT PREDICTION** + * + * We avoid doing full context retry when the outer context is empty, we did not + * dip into the outer context by falling off the end of the decision state rule, + * or when we force SLL mode. + * + * As an example of the not dip into outer context case, consider as super + * constructor calls versus function calls. One grammar might look like + * this: + * + * ```antlr + * ctorBody + * : '{' superCall? stat* '}' + * ; + * ``` + * + * Or, you might see something like + * + * ```antlr + * stat + * : superCall ';' + * | expression ';' + * | ... + * ; + * ``` + * + * In both cases I believe that no closure operations will dip into the outer + * context. In the first case ctorBody in the worst case will stop at the '}'. + * In the 2nd case it should stop at the ';'. Both cases should stay within the + * entry rule and not dip into the outer context. + * + * **PREDICATES** + * + * Predicates are always evaluated if present in either SLL or LL both. SLL and + * LL simulation deals with predicates differently. SLL collects predicates as + * it performs closure operations like ANTLR v3 did. It delays predicate + * evaluation until it reaches and accept state. This allows us to cache the SLL + * ATN simulation whereas, if we had evaluated predicates on-the-fly during + * closure, the DFA state configuration sets would be different and we couldn't + * build up a suitable DFA. + * + * When building a DFA accept state during ATN simulation, we evaluate any + * predicates and return the sole semantically valid alternative. If there is + * more than 1 alternative, we report an ambiguity. If there are 0 alternatives, + * we throw an exception. Alternatives without predicates act like they have + * true predicates. The simple way to think about it is to strip away all + * alternatives with false predicates and choose the minimum alternative that + * remains. + * + * When we start in the DFA and reach an accept state that's predicated, we test + * those and return the minimum semantically viable alternative. If no + * alternatives are viable, we throw an exception. + * + * During full LL ATN simulation, closure always evaluates predicates and + * on-the-fly. This is crucial to reducing the configuration set size during + * closure. It hits a landmine when parsing with the Java grammar, for example, + * without this on-the-fly evaluation. + * + * **SHARING DFA** + * + * All instances of the same parser share the same decision DFAs through a + * static field. Each instance gets its own ATN simulator but they share the + * same {@link ATN#decisionToDFA} field. They also share a + * {@link PredictionContextCache} object that makes sure that all + * {@link PredictionContext} objects are shared among the DFA states. This makes + * a big size difference. + * + * **THREAD SAFETY** + * + * The {@link ParserATNSimulator} locks on the {@link ATN#decisionToDFA} field when + * it adds a new DFA object to that array. {@link #addDFAEdge} + * locks on the DFA for the current decision when setting the + * {@link DFAState#edges} field. {@link #addDFAState} locks on + * the DFA for the current decision when looking up a DFA state to see if it + * already exists. We must make sure that all requests to add DFA states that + * are equivalent result in the same shared DFA object. This is because lots of + * threads will be trying to update the DFA at once. The + * {@link #addDFAState} method also locks inside the DFA lock + * but this time on the shared context cache when it rebuilds the + * configurations' {@link PredictionContext} objects using cached + * subgraphs/nodes. No other locking occurs, even during DFA simulation. This is + * safe as long as we can guarantee that all threads referencing + * `s.edge[t]` get the same physical target {@link DFAState}, or + * `undefined`. Once into the DFA, the DFA simulation does not reference the + * {@link DFA#states} map. It follows the {@link DFAState#edges} field to new + * targets. The DFA simulator will either find {@link DFAState#edges} to be + * `undefined`, to be non-`undefined` and `dfa.edges[t]` undefined, or + * `dfa.edges[t]` to be non-undefined. The + * {@link #addDFAEdge} method could be racing to set the field + * but in either case the DFA simulator works; if `undefined`, and requests ATN + * simulation. It could also race trying to get `dfa.edges[t]`, but either + * way it will work because it's not doing a test and set operation. + * + * **Starting with SLL then failing to combined SLL/LL (Two-Stage + * Parsing)** + * + * Sam pointed out that if SLL does not give a syntax error, then there is no + * point in doing full LL, which is slower. We only have to try LL if we get a + * syntax error. For maximum speed, Sam starts the parser set to pure SLL + * mode with the {@link BailErrorStrategy}: + * + * ``` + * parser.interpreter.{@link #setPredictionMode setPredictionMode}`(`{@link PredictionMode#SLL}`)`; + * parser.{@link Parser#setErrorHandler setErrorHandler}(new {@link BailErrorStrategy}()); + * ``` + * + * If it does not get a syntax error, then we're done. If it does get a syntax + * error, we need to retry with the combined SLL/LL strategy. + * + * The reason this works is as follows. If there are no SLL conflicts, then the + * grammar is SLL (at least for that input set). If there is an SLL conflict, + * the full LL analysis must yield a set of viable alternatives which is a + * subset of the alternatives reported by SLL. If the LL set is a singleton, + * then the grammar is LL but not SLL. If the LL set is the same size as the SLL + * set, the decision is SLL. If the LL set has size > 1, then that decision + * is truly ambiguous on the current input. If the LL set is smaller, then the + * SLL conflict resolution might choose an alternative that the full LL would + * rule out as a possibility based upon better context information. If that's + * the case, then the SLL parse will definitely get an error because the full LL + * analysis says it's not viable. If SLL conflict resolution chooses an + * alternative within the LL set, them both SLL and LL would choose the same + * alternative because they both choose the minimum of multiple conflicting + * alternatives. + * + * Let's say we have a set of SLL conflicting alternatives `{1, 2, 3}` and + * a smaller LL set called *s*. If *s* is `{2, 3}`, then SLL + * parsing will get an error because SLL will pursue alternative 1. If + * *s* is `{1, 2}` or `{1, 3}` then both SLL and LL will + * choose the same alternative because alternative one is the minimum of either + * set. If *s* is `{2}` or `{3}` then SLL will get a syntax + * error. If *s* is `{1}` then SLL will succeed. + * + * Of course, if the input is invalid, then we will get an error for sure in + * both SLL and LL parsing. Erroneous input will therefore require 2 passes over + * the input. + */ + let ParserATNSimulator$1 = class ParserATNSimulator extends ATNSimulator_1.ATNSimulator { + constructor(atn, parser) { + super(atn); + this.predictionMode = PredictionMode_1.PredictionMode.LL; + this.force_global_context = false; + this.always_try_local_context = true; + /** + * Determines whether the DFA is used for full-context predictions. When + * `true`, the DFA stores transition information for both full-context + * and SLL parsing; otherwise, the DFA only stores SLL transition + * information. + * + * For some grammars, enabling the full-context DFA can result in a + * substantial performance improvement. However, this improvement typically + * comes at the expense of memory used for storing the cached DFA states, + * configuration sets, and prediction contexts. + * + * The default value is `false`. + */ + this.enable_global_context_dfa = false; + this.optimize_unique_closure = true; + this.optimize_ll1 = true; + this.optimize_tail_calls = true; + this.tail_call_preserves_sll = true; + this.treat_sllk1_conflict_as_ambiguity = false; + /** + * When `true`, ambiguous alternatives are reported when they are + * encountered within {@link #execATN}. When `false`, these messages + * are suppressed. The default is `false`. + * + * When messages about ambiguous alternatives are not required, setting this + * to `false` enables additional internal optimizations which may lose + * this information. + */ + this.reportAmbiguities = false; + /** By default we do full context-sensitive LL(*) parsing not + * Strong LL(*) parsing. If we fail with Strong LL(*) we + * try full LL(*). That means we rewind and use context information + * when closure operations fall off the end of the rule that + * holds the decision were evaluating. + */ + this.userWantsCtxSensitive = true; + this._parser = parser; + } + getPredictionMode() { + return this.predictionMode; + } + setPredictionMode(predictionMode) { + this.predictionMode = predictionMode; + } + reset() { + // intentionally empty + } + adaptivePredict(input, decision, outerContext, useContext) { + if (useContext === undefined) { + useContext = false; + } + let dfa = this.atn.decisionToDFA[decision]; + assert(dfa != null); + if (this.optimize_ll1 && !dfa.isPrecedenceDfa && !dfa.isEmpty) { + let ll_1 = input.LA(1); + if (ll_1 >= 0 && ll_1 <= 0xFFFF) { + let key = ((decision << 16) >>> 0) + ll_1; + let alt = this.atn.LL1Table.get(key); + if (alt != null) { + return alt; + } + } + } + this.dfa = dfa; + if (this.force_global_context) { + useContext = true; + } + else if (!this.always_try_local_context) { + useContext = useContext || dfa.isContextSensitive; + } + this.userWantsCtxSensitive = useContext || (this.predictionMode !== PredictionMode_1.PredictionMode.SLL && outerContext != null && !this.atn.decisionToState[decision].sll); + if (outerContext == null) { + outerContext = ParserRuleContext_1.ParserRuleContext.emptyContext(); + } + let state; + if (!dfa.isEmpty) { + state = this.getStartState(dfa, input, outerContext, useContext); + } + if (state == null) { + if (outerContext == null) { + outerContext = ParserRuleContext_1.ParserRuleContext.emptyContext(); + } + if (ParserATNSimulator.debug) { + console.log("ATN decision " + dfa.decision + + " exec LA(1)==" + this.getLookaheadName(input) + + ", outerContext=" + outerContext.toString(this._parser)); + } + state = this.computeStartState(dfa, outerContext, useContext); + } + let m = input.mark(); + let index = input.index; + try { + let alt = this.execDFA(dfa, input, index, state); + if (ParserATNSimulator.debug) { + console.log("DFA after predictATN: " + dfa.toString(this._parser.vocabulary, this._parser.ruleNames)); + } + return alt; + } + finally { + this.dfa = undefined; + input.seek(index); + input.release(m); + } + } + getStartState(dfa, input, outerContext, useContext) { + if (!useContext) { + if (dfa.isPrecedenceDfa) { + // the start state for a precedence DFA depends on the current + // parser precedence, and is provided by a DFA method. + let state = dfa.getPrecedenceStartState(this._parser.precedence, false); + if (state == null) { + return undefined; + } + return new SimulatorState_1.SimulatorState(outerContext, state, false, outerContext); + } + else { + if (dfa.s0 == null) { + return undefined; + } + return new SimulatorState_1.SimulatorState(outerContext, dfa.s0, false, outerContext); + } + } + if (!this.enable_global_context_dfa) { + return undefined; + } + let remainingContext = outerContext; + assert(outerContext != null); + let s0; + if (dfa.isPrecedenceDfa) { + s0 = dfa.getPrecedenceStartState(this._parser.precedence, true); + } + else { + s0 = dfa.s0full; + } + while (remainingContext != null && s0 != null && s0.isContextSensitive) { + remainingContext = this.skipTailCalls(remainingContext); + s0 = s0.getContextTarget(this.getReturnState(remainingContext)); + if (remainingContext.isEmpty) { + assert(s0 == null || !s0.isContextSensitive); + } + else { + remainingContext = remainingContext.parent; + } + } + if (s0 == null) { + return undefined; + } + return new SimulatorState_1.SimulatorState(outerContext, s0, useContext, remainingContext); + } + execDFA(dfa, input, startIndex, state) { + let outerContext = state.outerContext; + if (ParserATNSimulator.dfa_debug) { + console.log("DFA decision " + dfa.decision + + " exec LA(1)==" + this.getLookaheadName(input) + + ", outerContext=" + outerContext.toString(this._parser)); + } + if (ParserATNSimulator.dfa_debug) { + console.log(dfa.toString(this._parser.vocabulary, this._parser.ruleNames)); + } + let s = state.s0; + let t = input.LA(1); + let remainingOuterContext = state.remainingOuterContext; + while (true) { + if (ParserATNSimulator.dfa_debug) { + console.log("DFA state " + s.stateNumber + " LA(1)==" + this.getLookaheadName(input)); + } + if (state.useContext) { + while (s.isContextSymbol(t)) { + let next; + if (remainingOuterContext != null) { + remainingOuterContext = this.skipTailCalls(remainingOuterContext); + next = s.getContextTarget(this.getReturnState(remainingOuterContext)); + } + if (next == null) { + // fail over to ATN + let initialState = new SimulatorState_1.SimulatorState(state.outerContext, s, state.useContext, remainingOuterContext); + return this.execATN(dfa, input, startIndex, initialState); + } + assert(remainingOuterContext != null); + remainingOuterContext = remainingOuterContext.parent; + s = next; + } + } + if (this.isAcceptState(s, state.useContext)) { + if (s.predicates != null) { + if (ParserATNSimulator.dfa_debug) { + console.log("accept " + s); + } + } + else { + if (ParserATNSimulator.dfa_debug) { + console.log("accept; predict " + s.prediction + " in state " + s.stateNumber); + } + } + // keep going unless we're at EOF or state only has one alt number + // mentioned in configs; check if something else could match + // TODO: don't we always stop? only lexer would keep going + // TODO: v3 dfa don't do this. + break; + } + // t is not updated if one of these states is reached + assert(!this.isAcceptState(s, state.useContext)); + // if no edge, pop over to ATN interpreter, update DFA and return + let target = this.getExistingTargetState(s, t); + if (target == null) { + if (ParserATNSimulator.dfa_debug && t >= 0) { + console.log("no edge for " + this._parser.vocabulary.getDisplayName(t)); + } + let alt; + if (ParserATNSimulator.dfa_debug) { + let interval = Interval_1.Interval.of(startIndex, this._parser.inputStream.index); + console.log("ATN exec upon " + + this._parser.inputStream.getText(interval) + + " at DFA state " + s.stateNumber); + } + let initialState = new SimulatorState_1.SimulatorState(outerContext, s, state.useContext, remainingOuterContext); + alt = this.execATN(dfa, input, startIndex, initialState); + if (ParserATNSimulator.dfa_debug) { + console.log("back from DFA update, alt=" + alt + ", dfa=\n" + dfa.toString(this._parser.vocabulary, this._parser.ruleNames)); + //dump(dfa); + } + // action already executed + if (ParserATNSimulator.dfa_debug) { + console.log("DFA decision " + dfa.decision + + " predicts " + alt); + } + return alt; // we've updated DFA, exec'd action, and have our deepest answer + } + else if (target === ATNSimulator_1.ATNSimulator.ERROR) { + let errorState = new SimulatorState_1.SimulatorState(outerContext, s, state.useContext, remainingOuterContext); + return this.handleNoViableAlt(input, startIndex, errorState); + } + s = target; + if (!this.isAcceptState(s, state.useContext) && t !== IntStream_1.IntStream.EOF) { + input.consume(); + t = input.LA(1); + } + } + // if ( acceptState==null ) { + // if ( debug ) System.out.println("!!! no viable alt in dfa"); + // return -1; + // } + if (!state.useContext && s.configs.conflictInfo != null) { + if (dfa.atnStartState instanceof DecisionState_1.DecisionState) { + if (!this.userWantsCtxSensitive || + (!s.configs.dipsIntoOuterContext && s.configs.isExactConflict) || + (this.treat_sllk1_conflict_as_ambiguity && input.index === startIndex)) ; + else { + assert(!state.useContext); + // Before attempting full context prediction, check to see if there are + // disambiguating or validating predicates to evaluate which allow an + // immediate decision + let conflictingAlts; + let predicates = s.predicates; + if (predicates != null) { + let conflictIndex = input.index; + if (conflictIndex !== startIndex) { + input.seek(startIndex); + } + conflictingAlts = this.evalSemanticContext(predicates, outerContext, true); + if (conflictingAlts.cardinality() === 1) { + return conflictingAlts.nextSetBit(0); + } + if (conflictIndex !== startIndex) { + // restore the index so reporting the fallback to full + // context occurs with the index at the correct spot + input.seek(conflictIndex); + } + } + if (this.reportAmbiguities) { + let conflictState = new SimulatorState_1.SimulatorState(outerContext, s, state.useContext, remainingOuterContext); + this.reportAttemptingFullContext(dfa, conflictingAlts, conflictState, startIndex, input.index); + } + input.seek(startIndex); + return this.adaptivePredict(input, dfa.decision, outerContext, true); + } + } + } + // Before jumping to prediction, check to see if there are + // disambiguating or validating predicates to evaluate + let predicates = s.predicates; + if (predicates != null) { + let stopIndex = input.index; + if (startIndex !== stopIndex) { + input.seek(startIndex); + } + let alts = this.evalSemanticContext(predicates, outerContext, this.reportAmbiguities && this.predictionMode === PredictionMode_1.PredictionMode.LL_EXACT_AMBIG_DETECTION); + switch (alts.cardinality()) { + case 0: + throw this.noViableAlt(input, outerContext, s.configs, startIndex); + case 1: + return alts.nextSetBit(0); + default: + // report ambiguity after predicate evaluation to make sure the correct + // set of ambig alts is reported. + if (startIndex !== stopIndex) { + input.seek(stopIndex); + } + this.reportAmbiguity(dfa, s, startIndex, stopIndex, s.configs.isExactConflict, alts, s.configs); + return alts.nextSetBit(0); + } + } + if (ParserATNSimulator.dfa_debug) { + console.log("DFA decision " + dfa.decision + + " predicts " + s.prediction); + } + return s.prediction; + } + /** + * Determines if a particular DFA state should be treated as an accept state + * for the current prediction mode. In addition to the `useContext` + * parameter, the {@link #getPredictionMode()} method provides the + * prediction mode controlling the prediction algorithm as a whole. + * + * The default implementation simply returns the value of + * `DFAState.isAcceptState` except for conflict states when + * `useContext` is `true` and {@link #getPredictionMode()} is + * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}. In that case, only + * conflict states where {@link ATNConfigSet#isExactConflict} is + * `true` are considered accept states. + * + * @param state The DFA state to check. + * @param useContext `true` if the prediction algorithm is currently + * considering the full parser context; otherwise, `false` if the + * algorithm is currently performing a local context prediction. + * + * @returns `true` if the specified `state` is an accept state; + * otherwise, `false`. + */ + isAcceptState(state, useContext) { + if (!state.isAcceptState) { + return false; + } + if (state.configs.conflictingAlts == null) { + // unambiguous + return true; + } + // More picky when we need exact conflicts + if (useContext && this.predictionMode === PredictionMode_1.PredictionMode.LL_EXACT_AMBIG_DETECTION) { + return state.configs.isExactConflict; + } + return true; + } + /** Performs ATN simulation to compute a predicted alternative based + * upon the remaining input, but also updates the DFA cache to avoid + * having to traverse the ATN again for the same input sequence. + * + * There are some key conditions we're looking for after computing a new + * set of ATN configs (proposed DFA state): + * + * * if the set is empty, there is no viable alternative for current symbol + * * does the state uniquely predict an alternative? + * * does the state have a conflict that would prevent us from + * putting it on the work list? + * * if in non-greedy decision is there a config at a rule stop state? + * + * We also have some key operations to do: + * + * * add an edge from previous DFA state to potentially new DFA state, D, + * upon current symbol but only if adding to work list, which means in all + * cases except no viable alternative (and possibly non-greedy decisions?) + * * collecting predicates and adding semantic context to DFA accept states + * * adding rule context to context-sensitive DFA accept states + * * consuming an input symbol + * * reporting a conflict + * * reporting an ambiguity + * * reporting a context sensitivity + * * reporting insufficient predicates + * + * We should isolate those operations, which are side-effecting, to the + * main work loop. We can isolate lots of code into other functions, but + * they should be side effect free. They can return package that + * indicates whether we should report something, whether we need to add a + * DFA edge, whether we need to augment accept state with semantic + * context or rule invocation context. Actually, it seems like we always + * add predicates if they exist, so that can simply be done in the main + * loop for any accept state creation or modification request. + * + * cover these cases: + * dead end + * single alt + * single alt + preds + * conflict + * conflict + preds + * + * TODO: greedy + those + */ + execATN(dfa, input, startIndex, initialState) { + if (ParserATNSimulator.debug) { + console.log("execATN decision " + dfa.decision + " exec LA(1)==" + this.getLookaheadName(input)); + } + let outerContext = initialState.outerContext; + let useContext = initialState.useContext; + let t = input.LA(1); + let previous = initialState; + let contextCache = new PredictionContextCache_1.PredictionContextCache(); + while (true) { // while more work + let nextState = this.computeReachSet(dfa, previous, t, contextCache); + if (nextState == null) { + this.setDFAEdge(previous.s0, input.LA(1), ATNSimulator_1.ATNSimulator.ERROR); + return this.handleNoViableAlt(input, startIndex, previous); + } + let D = nextState.s0; + // predicted alt => accept state + assert(D.isAcceptState || D.prediction === ATN_1.ATN.INVALID_ALT_NUMBER); + // conflicted => accept state + assert(D.isAcceptState || D.configs.conflictInfo == null); + if (this.isAcceptState(D, useContext)) { + let conflictingAlts = D.configs.conflictingAlts; + let predictedAlt = conflictingAlts == null ? D.prediction : ATN_1.ATN.INVALID_ALT_NUMBER; + if (predictedAlt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + if (this.optimize_ll1 + && input.index === startIndex + && !dfa.isPrecedenceDfa + && nextState.outerContext === nextState.remainingOuterContext + && dfa.decision >= 0 + && !D.configs.hasSemanticContext) { + if (t >= 0 && t <= MAX_SHORT_VALUE) { + let key = ((dfa.decision << 16) >>> 0) + t; + this.atn.LL1Table.set(key, predictedAlt); + } + } + if (useContext && this.always_try_local_context) { + this.reportContextSensitivity(dfa, predictedAlt, nextState, startIndex, input.index); + } + } + predictedAlt = D.prediction; + // int k = input.index - startIndex + 1; // how much input we used + // System.out.println("used k="+k); + let attemptFullContext = conflictingAlts != null && this.userWantsCtxSensitive; + if (attemptFullContext) { + // Only exact conflicts are known to be ambiguous when local + // prediction does not step out of the decision rule. + attemptFullContext = !useContext + && (D.configs.dipsIntoOuterContext || !D.configs.isExactConflict) + && (!this.treat_sllk1_conflict_as_ambiguity || input.index !== startIndex); + } + if (D.configs.hasSemanticContext) { + let predPredictions = D.predicates; + if (predPredictions != null) { + let conflictIndex = input.index; + if (conflictIndex !== startIndex) { + input.seek(startIndex); + } + // use complete evaluation here if we'll want to retry with full context if still ambiguous + conflictingAlts = this.evalSemanticContext(predPredictions, outerContext, attemptFullContext || this.reportAmbiguities); + switch (conflictingAlts.cardinality()) { + case 0: + throw this.noViableAlt(input, outerContext, D.configs, startIndex); + case 1: + return conflictingAlts.nextSetBit(0); + } + if (conflictIndex !== startIndex) { + // restore the index so reporting the fallback to full + // context occurs with the index at the correct spot + input.seek(conflictIndex); + } + } + } + if (!attemptFullContext) { + if (conflictingAlts != null) { + if (this.reportAmbiguities && conflictingAlts.cardinality() > 1) { + this.reportAmbiguity(dfa, D, startIndex, input.index, D.configs.isExactConflict, conflictingAlts, D.configs); + } + predictedAlt = conflictingAlts.nextSetBit(0); + } + return predictedAlt; + } + else { + assert(!useContext); + assert(this.isAcceptState(D, false)); + if (ParserATNSimulator.debug) { + console.log("RETRY with outerContext=" + outerContext); + } + let fullContextState = this.computeStartState(dfa, outerContext, true); + if (this.reportAmbiguities) { + this.reportAttemptingFullContext(dfa, conflictingAlts, nextState, startIndex, input.index); + } + input.seek(startIndex); + return this.execATN(dfa, input, startIndex, fullContextState); + } + } + previous = nextState; + if (t !== IntStream_1.IntStream.EOF) { + input.consume(); + t = input.LA(1); + } + } + } + /** + * This method is used to improve the localization of error messages by + * choosing an alternative rather than throwing a + * {@link NoViableAltException} in particular prediction scenarios where the + * {@link #ERROR} state was reached during ATN simulation. + * + * The default implementation of this method uses the following + * algorithm to identify an ATN configuration which successfully parsed the + * decision entry rule. Choosing such an alternative ensures that the + * {@link ParserRuleContext} returned by the calling rule will be complete + * and valid, and the syntax error will be reported later at a more + * localized location. + * + * * If no configuration in `configs` reached the end of the + * decision rule, return {@link ATN#INVALID_ALT_NUMBER}. + * * If all configurations in `configs` which reached the end of the + * decision rule predict the same alternative, return that alternative. + * * If the configurations in `configs` which reached the end of the + * decision rule predict multiple alternatives (call this *S*), + * choose an alternative in the following order. + * + * 1. Filter the configurations in `configs` to only those + * configurations which remain viable after evaluating semantic predicates. + * If the set of these filtered configurations which also reached the end of + * the decision rule is not empty, return the minimum alternative + * represented in this set. + * 1. Otherwise, choose the minimum alternative in *S*. + * + * In some scenarios, the algorithm described above could predict an + * alternative which will result in a {@link FailedPredicateException} in + * parser. Specifically, this could occur if the *only* configuration + * capable of successfully parsing to the end of the decision rule is + * blocked by a semantic predicate. By choosing this alternative within + * {@link #adaptivePredict} instead of throwing a + * {@link NoViableAltException}, the resulting + * {@link FailedPredicateException} in the parser will identify the specific + * predicate which is preventing the parser from successfully parsing the + * decision rule, which helps developers identify and correct logic errors + * in semantic predicates. + * + * @param input The input {@link TokenStream} + * @param startIndex The start index for the current prediction, which is + * the input index where any semantic context in `configs` should be + * evaluated + * @param previous The ATN simulation state immediately before the + * {@link #ERROR} state was reached + * + * @returns The value to return from {@link #adaptivePredict}, or + * {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not + * identified and {@link #adaptivePredict} should report an error instead. + */ + handleNoViableAlt(input, startIndex, previous) { + if (previous.s0 != null) { + let alts = new BitSet_1.BitSet(); + let maxAlt = 0; + for (let config of previous.s0.configs) { + if (config.reachesIntoOuterContext || config.state instanceof RuleStopState_1.RuleStopState) { + alts.set(config.alt); + maxAlt = Math.max(maxAlt, config.alt); + } + } + switch (alts.cardinality()) { + case 0: + break; + case 1: + return alts.nextSetBit(0); + default: + if (!previous.s0.configs.hasSemanticContext) { + // configs doesn't contain any predicates, so the predicate + // filtering code below would be pointless + return alts.nextSetBit(0); + } + /* + * Try to find a configuration set that not only dipped into the outer + * context, but also isn't eliminated by a predicate. + */ + let filteredConfigs = new ATNConfigSet_1.ATNConfigSet(); + for (let config of previous.s0.configs) { + if (config.reachesIntoOuterContext || config.state instanceof RuleStopState_1.RuleStopState) { + filteredConfigs.add(config); + } + } + /* The following code blocks are adapted from predicateDFAState with + * the following key changes. + * + * 1. The code operates on an ATNConfigSet rather than a DFAState. + * 2. Predicates are collected for all alternatives represented in + * filteredConfigs, rather than restricting the evaluation to + * conflicting and/or unique configurations. + */ + let altToPred = this.getPredsForAmbigAlts(alts, filteredConfigs, maxAlt); + if (altToPred != null) { + let predicates = this.getPredicatePredictions(alts, altToPred); + if (predicates != null) { + let stopIndex = input.index; + try { + input.seek(startIndex); + let filteredAlts = this.evalSemanticContext(predicates, previous.outerContext, false); + if (!filteredAlts.isEmpty) { + return filteredAlts.nextSetBit(0); + } + } + finally { + input.seek(stopIndex); + } + } + } + return alts.nextSetBit(0); + } + } + throw this.noViableAlt(input, previous.outerContext, previous.s0.configs, startIndex); + } + computeReachSet(dfa, previous, t, contextCache) { + let useContext = previous.useContext; + let remainingGlobalContext = previous.remainingOuterContext; + let s = previous.s0; + if (useContext) { + while (s.isContextSymbol(t)) { + let next; + if (remainingGlobalContext != null) { + remainingGlobalContext = this.skipTailCalls(remainingGlobalContext); + next = s.getContextTarget(this.getReturnState(remainingGlobalContext)); + } + if (next == null) { + break; + } + assert(remainingGlobalContext != null); + remainingGlobalContext = remainingGlobalContext.parent; + s = next; + } + } + assert(!this.isAcceptState(s, useContext)); + if (this.isAcceptState(s, useContext)) { + return new SimulatorState_1.SimulatorState(previous.outerContext, s, useContext, remainingGlobalContext); + } + let s0 = s; + let target = this.getExistingTargetState(s0, t); + if (target == null) { + let result = this.computeTargetState(dfa, s0, remainingGlobalContext, t, useContext, contextCache); + target = result[0]; + remainingGlobalContext = result[1]; + } + if (target === ATNSimulator_1.ATNSimulator.ERROR) { + return undefined; + } + assert(!useContext || !target.configs.dipsIntoOuterContext); + return new SimulatorState_1.SimulatorState(previous.outerContext, target, useContext, remainingGlobalContext); + } + /** + * Get an existing target state for an edge in the DFA. If the target state + * for the edge has not yet been computed or is otherwise not available, + * this method returns `undefined`. + * + * @param s The current DFA state + * @param t The next input symbol + * @returns The existing target DFA state for the given input symbol + * `t`, or `undefined` if the target state for this edge is not + * already cached + */ + getExistingTargetState(s, t) { + return s.getTarget(t); + } + /** + * Compute a target state for an edge in the DFA, and attempt to add the + * computed state and corresponding edge to the DFA. + * + * @param dfa + * @param s The current DFA state + * @param remainingGlobalContext + * @param t The next input symbol + * @param useContext + * @param contextCache + * + * @returns The computed target DFA state for the given input symbol + * `t`. If `t` does not lead to a valid DFA state, this method + * returns {@link #ERROR}. + */ + computeTargetState(dfa, s, remainingGlobalContext, t, useContext, contextCache) { + let closureConfigs = s.configs.toArray(); + let contextElements; + let reach = new ATNConfigSet_1.ATNConfigSet(); + let stepIntoGlobal; + do { + let hasMoreContext = !useContext || remainingGlobalContext != null; + if (!hasMoreContext) { + reach.isOutermostConfigSet = true; + } + let reachIntermediate = new ATNConfigSet_1.ATNConfigSet(); + /* Configurations already in a rule stop state indicate reaching the end + * of the decision rule (local context) or end of the start rule (full + * context). Once reached, these configurations are never updated by a + * closure operation, so they are handled separately for the performance + * advantage of having a smaller intermediate set when calling closure. + * + * For full-context reach operations, separate handling is required to + * ensure that the alternative matching the longest overall sequence is + * chosen when multiple such configurations can match the input. + */ + let skippedStopStates; + for (let c of closureConfigs) { + if (ParserATNSimulator.debug) { + console.log("testing " + this.getTokenName(t) + " at " + c.toString()); + } + if (c.state instanceof RuleStopState_1.RuleStopState) { + assert(c.context.isEmpty); + if (useContext && !c.reachesIntoOuterContext || t === IntStream_1.IntStream.EOF) { + if (skippedStopStates == null) { + skippedStopStates = []; + } + skippedStopStates.push(c); + } + continue; + } + let n = c.state.numberOfOptimizedTransitions; + for (let ti = 0; ti < n; ti++) { // for each optimized transition + let trans = c.state.getOptimizedTransition(ti); + let target = this.getReachableTarget(c, trans, t); + if (target != null) { + reachIntermediate.add(c.transform(target, false), contextCache); + } + } + } + /* This block optimizes the reach operation for intermediate sets which + * trivially indicate a termination state for the overall + * adaptivePredict operation. + * + * The conditions assume that intermediate + * contains all configurations relevant to the reach set, but this + * condition is not true when one or more configurations have been + * withheld in skippedStopStates, or when the current symbol is EOF. + */ + if (this.optimize_unique_closure && skippedStopStates == null && t !== Token_1.Token.EOF && reachIntermediate.uniqueAlt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + reachIntermediate.isOutermostConfigSet = reach.isOutermostConfigSet; + reach = reachIntermediate; + break; + } + /* If the reach set could not be trivially determined, perform a closure + * operation on the intermediate set to compute its initial value. + */ + let collectPredicates = false; + let treatEofAsEpsilon = t === Token_1.Token.EOF; + this.closure(reachIntermediate, reach, collectPredicates, hasMoreContext, contextCache, treatEofAsEpsilon); + stepIntoGlobal = reach.dipsIntoOuterContext; + if (t === IntStream_1.IntStream.EOF) { + /* After consuming EOF no additional input is possible, so we are + * only interested in configurations which reached the end of the + * decision rule (local context) or end of the start rule (full + * context). Update reach to contain only these configurations. This + * handles both explicit EOF transitions in the grammar and implicit + * EOF transitions following the end of the decision or start rule. + * + * This is handled before the configurations in skippedStopStates, + * because any configurations potentially added from that list are + * already guaranteed to meet this condition whether or not it's + * required. + */ + reach = this.removeAllConfigsNotInRuleStopState(reach, contextCache); + } + /* If skippedStopStates is not undefined, then it contains at least one + * configuration. For full-context reach operations, these + * configurations reached the end of the start rule, in which case we + * only add them back to reach if no configuration during the current + * closure operation reached such a state. This ensures adaptivePredict + * chooses an alternative matching the longest overall sequence when + * multiple alternatives are viable. + */ + if (skippedStopStates != null && (!useContext || !PredictionMode_1.PredictionMode.hasConfigInRuleStopState(reach))) { + assert(skippedStopStates.length > 0); + for (let c of skippedStopStates) { + reach.add(c, contextCache); + } + } + if (useContext && stepIntoGlobal) { + reach.clear(); + // We know remainingGlobalContext is not undefined at this point (why?) + remainingGlobalContext = remainingGlobalContext; + remainingGlobalContext = this.skipTailCalls(remainingGlobalContext); + let nextContextElement = this.getReturnState(remainingGlobalContext); + if (contextElements == null) { + contextElements = new IntegerList_1.IntegerList(); + } + if (remainingGlobalContext.isEmpty) { + remainingGlobalContext = undefined; + } + else { + remainingGlobalContext = remainingGlobalContext.parent; + } + contextElements.add(nextContextElement); + if (nextContextElement !== PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + for (let i = 0; i < closureConfigs.length; i++) { + closureConfigs[i] = closureConfigs[i].appendContext(nextContextElement, contextCache); + } + } + } + } while (useContext && stepIntoGlobal); + if (reach.isEmpty) { + this.setDFAEdge(s, t, ATNSimulator_1.ATNSimulator.ERROR); + return [ATNSimulator_1.ATNSimulator.ERROR, remainingGlobalContext]; + } + let result = this.addDFAEdge(dfa, s, t, contextElements, reach, contextCache); + return [result, remainingGlobalContext]; + } + /** + * Return a configuration set containing only the configurations from + * `configs` which are in a {@link RuleStopState}. If all + * configurations in `configs` are already in a rule stop state, this + * method simply returns `configs`. + * + * @param configs the configuration set to update + * @param contextCache the {@link PredictionContext} cache + * + * @returns `configs` if all configurations in `configs` are in a + * rule stop state, otherwise return a new configuration set containing only + * the configurations from `configs` which are in a rule stop state + */ + removeAllConfigsNotInRuleStopState(configs, contextCache) { + if (PredictionMode_1.PredictionMode.allConfigsInRuleStopStates(configs)) { + return configs; + } + let result = new ATNConfigSet_1.ATNConfigSet(); + for (let config of configs) { + if (!(config.state instanceof RuleStopState_1.RuleStopState)) { + continue; + } + result.add(config, contextCache); + } + return result; + } + computeStartState(dfa, globalContext, useContext) { + let s0 = dfa.isPrecedenceDfa ? dfa.getPrecedenceStartState(this._parser.precedence, useContext) : + useContext ? dfa.s0full : + dfa.s0; + if (s0 != null) { + if (!useContext) { + return new SimulatorState_1.SimulatorState(globalContext, s0, useContext, globalContext); + } + s0.setContextSensitive(this.atn); + } + dfa.decision; + // @NotNull + let p = dfa.atnStartState; + let previousContext = 0; + let remainingGlobalContext = globalContext; + let initialContext = useContext ? PredictionContext_1.PredictionContext.EMPTY_FULL : PredictionContext_1.PredictionContext.EMPTY_LOCAL; // always at least the implicit call to start rule + let contextCache = new PredictionContextCache_1.PredictionContextCache(); + if (useContext) { + if (!this.enable_global_context_dfa) { + while (remainingGlobalContext != null) { + if (remainingGlobalContext.isEmpty) { + previousContext = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY; + remainingGlobalContext = undefined; + } + else { + previousContext = this.getReturnState(remainingGlobalContext); + initialContext = initialContext.appendSingleContext(previousContext, contextCache); + remainingGlobalContext = remainingGlobalContext.parent; + } + } + } + while (s0 != null && s0.isContextSensitive && remainingGlobalContext != null) { + let next; + remainingGlobalContext = this.skipTailCalls(remainingGlobalContext); + if (remainingGlobalContext.isEmpty) { + next = s0.getContextTarget(PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY); + previousContext = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY; + remainingGlobalContext = undefined; + } + else { + previousContext = this.getReturnState(remainingGlobalContext); + next = s0.getContextTarget(previousContext); + initialContext = initialContext.appendSingleContext(previousContext, contextCache); + remainingGlobalContext = remainingGlobalContext.parent; + } + if (next == null) { + break; + } + s0 = next; + } + } + if (s0 != null && !s0.isContextSensitive) { + return new SimulatorState_1.SimulatorState(globalContext, s0, useContext, remainingGlobalContext); + } + let configs = new ATNConfigSet_1.ATNConfigSet(); + while (true) { + let reachIntermediate = new ATNConfigSet_1.ATNConfigSet(); + let n = p.numberOfTransitions; + for (let ti = 0; ti < n; ti++) { + // for each transition + let target = p.transition(ti).target; + reachIntermediate.add(ATNConfig_1.ATNConfig.create(target, ti + 1, initialContext)); + } + let hasMoreContext = remainingGlobalContext != null; + if (!hasMoreContext) { + configs.isOutermostConfigSet = true; + } + let collectPredicates = true; + this.closure(reachIntermediate, configs, collectPredicates, hasMoreContext, contextCache, false); + let stepIntoGlobal = configs.dipsIntoOuterContext; + let next; + if (useContext && !this.enable_global_context_dfa) { + s0 = this.addDFAState(dfa, configs, contextCache); + break; + } + else if (s0 == null) { + if (!dfa.isPrecedenceDfa) { + next = this.addDFAState(dfa, configs, contextCache); + if (useContext) { + if (!dfa.s0full) { + dfa.s0full = next; + } + else { + next = dfa.s0full; + } + } + else { + if (!dfa.s0) { + dfa.s0 = next; + } + else { + next = dfa.s0; + } + } + } + else { + /* If this is a precedence DFA, we use applyPrecedenceFilter + * to convert the computed start state to a precedence start + * state. We then use DFA.setPrecedenceStartState to set the + * appropriate start state for the precedence level rather + * than simply setting DFA.s0. + */ + configs = this.applyPrecedenceFilter(configs, globalContext, contextCache); + next = this.addDFAState(dfa, configs, contextCache); + dfa.setPrecedenceStartState(this._parser.precedence, useContext, next); + } + } + else { + if (dfa.isPrecedenceDfa) { + configs = this.applyPrecedenceFilter(configs, globalContext, contextCache); + } + next = this.addDFAState(dfa, configs, contextCache); + s0.setContextTarget(previousContext, next); + } + s0 = next; + if (!useContext || !stepIntoGlobal) { + break; + } + // TODO: make sure it distinguishes empty stack states + next.setContextSensitive(this.atn); + // We know remainingGlobalContext is not undefined at this point (why?) + remainingGlobalContext = remainingGlobalContext; + configs.clear(); + remainingGlobalContext = this.skipTailCalls(remainingGlobalContext); + let nextContextElement = this.getReturnState(remainingGlobalContext); + if (remainingGlobalContext.isEmpty) { + remainingGlobalContext = undefined; + } + else { + remainingGlobalContext = remainingGlobalContext.parent; + } + if (nextContextElement !== PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + initialContext = initialContext.appendSingleContext(nextContextElement, contextCache); + } + previousContext = nextContextElement; + } + return new SimulatorState_1.SimulatorState(globalContext, s0, useContext, remainingGlobalContext); + } + /** + * This method transforms the start state computed by + * {@link #computeStartState} to the special start state used by a + * precedence DFA for a particular precedence value. The transformation + * process applies the following changes to the start state's configuration + * set. + * + * 1. Evaluate the precedence predicates for each configuration using + * {@link SemanticContext#evalPrecedence}. + * 1. When {@link ATNConfig#isPrecedenceFilterSuppressed} is `false`, + * remove all configurations which predict an alternative greater than 1, + * for which another configuration that predicts alternative 1 is in the + * same ATN state with the same prediction context. This transformation is + * valid for the following reasons: + * + * * The closure block cannot contain any epsilon transitions which bypass + * the body of the closure, so all states reachable via alternative 1 are + * part of the precedence alternatives of the transformed left-recursive + * rule. + * * The "primary" portion of a left recursive rule cannot contain an + * epsilon transition, so the only way an alternative other than 1 can exist + * in a state that is also reachable via alternative 1 is by nesting calls + * to the left-recursive rule, with the outer calls not being at the + * preferred precedence level. The + * {@link ATNConfig#isPrecedenceFilterSuppressed} property marks ATN + * configurations which do not meet this condition, and therefore are not + * eligible for elimination during the filtering process. + * + * The prediction context must be considered by this filter to address + * situations like the following. + * + * ```antlr + * grammar TA; + * prog: statement* EOF; + * statement: letterA | statement letterA 'b' ; + * letterA: 'a'; + * ``` + * + * If the above grammar, the ATN state immediately before the token + * reference `'a'` in `letterA` is reachable from the left edge + * of both the primary and closure blocks of the left-recursive rule + * `statement`. The prediction context associated with each of these + * configurations distinguishes between them, and prevents the alternative + * which stepped out to `prog` (and then back in to `statement` + * from being eliminated by the filter. + * + * @param configs The configuration set computed by + * {@link #computeStartState} as the start state for the DFA. + * @returns The transformed configuration set representing the start state + * for a precedence DFA at a particular precedence level (determined by + * calling {@link Parser#getPrecedence}). + */ + applyPrecedenceFilter(configs, globalContext, contextCache) { + let statesFromAlt1 = new Map(); + let configSet = new ATNConfigSet_1.ATNConfigSet(); + for (let config of configs) { + // handle alt 1 first + if (config.alt !== 1) { + continue; + } + let updatedContext = config.semanticContext.evalPrecedence(this._parser, globalContext); + if (updatedContext == null) { + // the configuration was eliminated + continue; + } + statesFromAlt1.set(config.state.stateNumber, config.context); + if (updatedContext !== config.semanticContext) { + configSet.add(config.transform(config.state, false, updatedContext), contextCache); + } + else { + configSet.add(config, contextCache); + } + } + for (let config of configs) { + if (config.alt === 1) { + // already handled + continue; + } + if (!config.isPrecedenceFilterSuppressed) { + /* In the future, this elimination step could be updated to also + * filter the prediction context for alternatives predicting alt>1 + * (basically a graph subtraction algorithm). + */ + let context = statesFromAlt1.get(config.state.stateNumber); + if (context != null && context.equals(config.context)) { + // eliminated + continue; + } + } + configSet.add(config, contextCache); + } + return configSet; + } + getReachableTarget(source, trans, ttype) { + if (trans.matches(ttype, 0, this.atn.maxTokenType)) { + return trans.target; + } + return undefined; + } + /** collect and set D's semantic context */ + predicateDFAState(D, configs, nalts) { + let conflictingAlts = this.getConflictingAltsFromConfigSet(configs); + if (!conflictingAlts) { + throw new Error("This unhandled scenario is intended to be unreachable, but I'm currently not sure of why we know that's the case."); + } + if (ParserATNSimulator.debug) { + console.log("predicateDFAState " + D); + } + let altToPred = this.getPredsForAmbigAlts(conflictingAlts, configs, nalts); + // altToPred[uniqueAlt] is now our validating predicate (if any) + let predPredictions; + if (altToPred != null) { + // we have a validating predicate; test it + // Update DFA so reach becomes accept state with predicate + predPredictions = this.getPredicatePredictions(conflictingAlts, altToPred); + D.predicates = predPredictions; + } + return predPredictions; + } + getPredsForAmbigAlts(ambigAlts, configs, nalts) { + // REACH=[1|1|[]|0:0, 1|2|[]|0:1] + /* altToPred starts as an array of all undefined contexts. The entry at index i + * corresponds to alternative i. altToPred[i] may have one of three values: + * 1. undefined: no ATNConfig c is found such that c.alt===i + * 2. SemanticContext.NONE: At least one ATNConfig c exists such that + * c.alt===i and c.semanticContext===SemanticContext.NONE. In other words, + * alt i has at least one unpredicated config. + * 3. Non-NONE Semantic Context: There exists at least one, and for all + * ATNConfig c such that c.alt===i, c.semanticContext!==SemanticContext.NONE. + * + * From this, it is clear that NONE||anything==NONE. + */ + let altToPred = new Array(nalts + 1); + let n = altToPred.length; + for (let c of configs) { + if (ambigAlts.get(c.alt)) { + altToPred[c.alt] = SemanticContext_1.SemanticContext.or(altToPred[c.alt], c.semanticContext); + } + } + let nPredAlts = 0; + for (let i = 0; i < n; i++) { + if (altToPred[i] == null) { + altToPred[i] = SemanticContext_1.SemanticContext.NONE; + } + else if (altToPred[i] !== SemanticContext_1.SemanticContext.NONE) { + nPredAlts++; + } + } + // At this point we know `altToPred` doesn't contain any undefined entries + let result = altToPred; + // nonambig alts are undefined in result + if (nPredAlts === 0) { + result = undefined; + } + if (ParserATNSimulator.debug) { + console.log("getPredsForAmbigAlts result " + (result ? Arrays_1.Arrays.toString(result) : "undefined")); + } + return result; + } + getPredicatePredictions(ambigAlts, altToPred) { + let pairs = []; + let containsPredicate = false; + for (let i = 1; i < altToPred.length; i++) { + let pred = altToPred[i]; + // unpredicated is indicated by SemanticContext.NONE + assert(pred != null); + // find first unpredicated but ambig alternative, if any. + // Only ambiguous alternatives will have SemanticContext.NONE. + // Any unambig alts or ambig naked alts after first ambig naked are ignored + // (undefined, i) means alt i is the default prediction + // if no (undefined, i), then no default prediction. + if (ambigAlts != null && ambigAlts.get(i) && pred === SemanticContext_1.SemanticContext.NONE) { + pairs.push(new DFAState_1.DFAState.PredPrediction(pred, i)); + } + else if (pred !== SemanticContext_1.SemanticContext.NONE) { + containsPredicate = true; + pairs.push(new DFAState_1.DFAState.PredPrediction(pred, i)); + } + } + if (!containsPredicate) { + return undefined; + } + // System.out.println(Arrays.toString(altToPred)+"->"+pairs); + return pairs; + } + /** Look through a list of predicate/alt pairs, returning alts for the + * pairs that win. An `undefined` predicate indicates an alt containing an + * unpredicated config which behaves as "always true." + */ + evalSemanticContext(predPredictions, outerContext, complete) { + let predictions = new BitSet_1.BitSet(); + for (let pair of predPredictions) { + if (pair.pred === SemanticContext_1.SemanticContext.NONE) { + predictions.set(pair.alt); + if (!complete) { + break; + } + continue; + } + let evaluatedResult = this.evalSemanticContextImpl(pair.pred, outerContext, pair.alt); + if (ParserATNSimulator.debug || ParserATNSimulator.dfa_debug) { + console.log("eval pred " + pair + "=" + evaluatedResult); + } + if (evaluatedResult) { + if (ParserATNSimulator.debug || ParserATNSimulator.dfa_debug) { + console.log("PREDICT " + pair.alt); + } + predictions.set(pair.alt); + if (!complete) { + break; + } + } + } + return predictions; + } + /** + * Evaluate a semantic context within a specific parser context. + * + * This method might not be called for every semantic context evaluated + * during the prediction process. In particular, we currently do not + * evaluate the following but it may change in the future: + * + * * Precedence predicates (represented by + * {@link SemanticContext.PrecedencePredicate}) are not currently evaluated + * through this method. + * * Operator predicates (represented by {@link SemanticContext.AND} and + * {@link SemanticContext.OR}) are evaluated as a single semantic + * context, rather than evaluating the operands individually. + * Implementations which require evaluation results from individual + * predicates should override this method to explicitly handle evaluation of + * the operands within operator predicates. + * + * @param pred The semantic context to evaluate + * @param parserCallStack The parser context in which to evaluate the + * semantic context + * @param alt The alternative which is guarded by `pred` + * + * @since 4.3 + */ + evalSemanticContextImpl(pred, parserCallStack, alt) { + return pred.eval(this._parser, parserCallStack); + } + /* TODO: If we are doing predicates, there is no point in pursuing + closure operations if we reach a DFA state that uniquely predicts + alternative. We will not be caching that DFA state and it is a + waste to pursue the closure. Might have to advance when we do + ambig detection thought :( + */ + closure(sourceConfigs, configs, collectPredicates, hasMoreContext, contextCache, treatEofAsEpsilon) { + if (contextCache == null) { + contextCache = PredictionContextCache_1.PredictionContextCache.UNCACHED; + } + let currentConfigs = sourceConfigs; + let closureBusy = new Array2DHashSet_1.Array2DHashSet(ObjectEqualityComparator_1.ObjectEqualityComparator.INSTANCE); + while (currentConfigs.size > 0) { + let intermediate = new ATNConfigSet_1.ATNConfigSet(); + for (let config of currentConfigs) { + this.closureImpl(config, configs, intermediate, closureBusy, collectPredicates, hasMoreContext, contextCache, 0, treatEofAsEpsilon); + } + currentConfigs = intermediate; + } + } + closureImpl(config, configs, intermediate, closureBusy, collectPredicates, hasMoreContexts, contextCache, depth, treatEofAsEpsilon) { + if (ParserATNSimulator.debug) { + console.log("closure(" + config.toString(this._parser, true) + ")"); + } + if (config.state instanceof RuleStopState_1.RuleStopState) { + // We hit rule end. If we have context info, use it + if (!config.context.isEmpty) { + let hasEmpty = config.context.hasEmpty; + let nonEmptySize = config.context.size - (hasEmpty ? 1 : 0); + for (let i = 0; i < nonEmptySize; i++) { + let newContext = config.context.getParent(i); // "pop" return state + let returnState = this.atn.states[config.context.getReturnState(i)]; + let c = ATNConfig_1.ATNConfig.create(returnState, config.alt, newContext, config.semanticContext); + // While we have context to pop back from, we may have + // gotten that context AFTER having fallen off a rule. + // Make sure we track that we are now out of context. + c.outerContextDepth = config.outerContextDepth; + c.isPrecedenceFilterSuppressed = config.isPrecedenceFilterSuppressed; + assert(depth > MIN_INTEGER_VALUE); + this.closureImpl(c, configs, intermediate, closureBusy, collectPredicates, hasMoreContexts, contextCache, depth - 1, treatEofAsEpsilon); + } + if (!hasEmpty || !hasMoreContexts) { + return; + } + config = config.transform(config.state, false, PredictionContext_1.PredictionContext.EMPTY_LOCAL); + } + else if (!hasMoreContexts) { + configs.add(config, contextCache); + return; + } + else { + // else if we have no context info, just chase follow links (if greedy) + if (ParserATNSimulator.debug) { + console.log("FALLING off rule " + + this.getRuleName(config.state.ruleIndex)); + } + if (config.context === PredictionContext_1.PredictionContext.EMPTY_FULL) { + // no need to keep full context overhead when we step out + config = config.transform(config.state, false, PredictionContext_1.PredictionContext.EMPTY_LOCAL); + } + else if (!config.reachesIntoOuterContext && PredictionContext_1.PredictionContext.isEmptyLocal(config.context)) { + // add stop state when leaving decision rule for the first time + configs.add(config, contextCache); + } + } + } + let p = config.state; + // optimization + if (!p.onlyHasEpsilonTransitions) { + configs.add(config, contextCache); + // make sure to not return here, because EOF transitions can act as + // both epsilon transitions and non-epsilon transitions. + if (ParserATNSimulator.debug) { + console.log("added config " + configs); + } + } + for (let i = 0; i < p.numberOfOptimizedTransitions; i++) { + // This block implements first-edge elimination of ambiguous LR + // alternatives as part of dynamic disambiguation during prediction. + // See antlr/antlr4#1398. + if (i === 0 + && p.stateType === ATNStateType_1.ATNStateType.STAR_LOOP_ENTRY + && p.precedenceRuleDecision + && !config.context.hasEmpty) { + let precedenceDecision = p; + // When suppress is true, it means the outgoing edge i==0 is + // ambiguous with the outgoing edge i==1, and thus the closure + // operation can dynamically disambiguate by suppressing this + // edge during the closure operation. + let suppress = true; + for (let j = 0; j < config.context.size; j++) { + if (!precedenceDecision.precedenceLoopbackStates.get(config.context.getReturnState(j))) { + suppress = false; + break; + } + } + if (suppress) { + continue; + } + } + let t = p.getOptimizedTransition(i); + let continueCollecting = !(t instanceof ActionTransition_1.ActionTransition) && collectPredicates; + let c = this.getEpsilonTarget(config, t, continueCollecting, depth === 0, contextCache, treatEofAsEpsilon); + if (c != null) { + if (t instanceof RuleTransition_1.RuleTransition) { + if (intermediate != null && !collectPredicates) { + intermediate.add(c, contextCache); + continue; + } + } + let newDepth = depth; + if (config.state instanceof RuleStopState_1.RuleStopState) { + // target fell off end of rule; mark resulting c as having dipped into outer context + // We can't get here if incoming config was rule stop and we had context + // track how far we dip into outer context. Might + // come in handy and we avoid evaluating context dependent + // preds if this is > 0. + if (this.dfa != null && this.dfa.isPrecedenceDfa) { + let outermostPrecedenceReturn = t.outermostPrecedenceReturn; + if (outermostPrecedenceReturn === this.dfa.atnStartState.ruleIndex) { + c.isPrecedenceFilterSuppressed = true; + } + } + c.outerContextDepth = c.outerContextDepth + 1; + if (!closureBusy.add(c)) { + // avoid infinite recursion for right-recursive rules + continue; + } + assert(newDepth > MIN_INTEGER_VALUE); + newDepth--; + if (ParserATNSimulator.debug) { + console.log("dips into outer ctx: " + c); + } + } + else if (t instanceof RuleTransition_1.RuleTransition) { + if (this.optimize_tail_calls && t.optimizedTailCall && (!this.tail_call_preserves_sll || !PredictionContext_1.PredictionContext.isEmptyLocal(config.context))) { + assert(c.context === config.context); + if (newDepth === 0) { + // the pop/push of a tail call would keep the depth + // constant, except we latch if it goes negative + newDepth--; + if (!this.tail_call_preserves_sll && PredictionContext_1.PredictionContext.isEmptyLocal(config.context)) { + // make sure the SLL config "dips into the outer context" or prediction may not fall back to LL on conflict + c.outerContextDepth = c.outerContextDepth + 1; + } + } + } + else { + // latch when newDepth goes negative - once we step out of the entry context we can't return + if (newDepth >= 0) { + newDepth++; + } + } + } + else { + if (!t.isEpsilon && !closureBusy.add(c)) { + // avoid infinite recursion for EOF* and EOF+ + continue; + } + } + this.closureImpl(c, configs, intermediate, closureBusy, continueCollecting, hasMoreContexts, contextCache, newDepth, treatEofAsEpsilon); + } + } + } + getRuleName(index) { + if (this._parser != null && index >= 0) { + return this._parser.ruleNames[index]; + } + return ""; + } + getEpsilonTarget(config, t, collectPredicates, inContext, contextCache, treatEofAsEpsilon) { + switch (t.serializationType) { + case 3 /* RULE */: + return this.ruleTransition(config, t, contextCache); + case 10 /* PRECEDENCE */: + return this.precedenceTransition(config, t, collectPredicates, inContext); + case 4 /* PREDICATE */: + return this.predTransition(config, t, collectPredicates, inContext); + case 6 /* ACTION */: + return this.actionTransition(config, t); + case 1 /* EPSILON */: + return config.transform(t.target, false); + case 5 /* ATOM */: + case 2 /* RANGE */: + case 7 /* SET */: + // EOF transitions act like epsilon transitions after the first EOF + // transition is traversed + if (treatEofAsEpsilon) { + if (t.matches(Token_1.Token.EOF, 0, 1)) { + return config.transform(t.target, false); + } + } + return undefined; + default: + return undefined; + } + } + actionTransition(config, t) { + if (ParserATNSimulator.debug) { + console.log("ACTION edge " + t.ruleIndex + ":" + t.actionIndex); + } + return config.transform(t.target, false); + } + precedenceTransition(config, pt, collectPredicates, inContext) { + if (ParserATNSimulator.debug) { + console.log("PRED (collectPredicates=" + collectPredicates + ") " + + pt.precedence + ">=_p" + + ", ctx dependent=true"); + if (this._parser != null) { + console.log("context surrounding pred is " + + this._parser.getRuleInvocationStack()); + } + } + let c; + if (collectPredicates && inContext) { + let newSemCtx = SemanticContext_1.SemanticContext.and(config.semanticContext, pt.predicate); + c = config.transform(pt.target, false, newSemCtx); + } + else { + c = config.transform(pt.target, false); + } + if (ParserATNSimulator.debug) { + console.log("config from pred transition=" + c); + } + return c; + } + predTransition(config, pt, collectPredicates, inContext) { + if (ParserATNSimulator.debug) { + console.log("PRED (collectPredicates=" + collectPredicates + ") " + + pt.ruleIndex + ":" + pt.predIndex + + ", ctx dependent=" + pt.isCtxDependent); + if (this._parser != null) { + console.log("context surrounding pred is " + + this._parser.getRuleInvocationStack()); + } + } + let c; + if (collectPredicates && + (!pt.isCtxDependent || (pt.isCtxDependent && inContext))) { + let newSemCtx = SemanticContext_1.SemanticContext.and(config.semanticContext, pt.predicate); + c = config.transform(pt.target, false, newSemCtx); + } + else { + c = config.transform(pt.target, false); + } + if (ParserATNSimulator.debug) { + console.log("config from pred transition=" + c); + } + return c; + } + ruleTransition(config, t, contextCache) { + if (ParserATNSimulator.debug) { + console.log("CALL rule " + this.getRuleName(t.target.ruleIndex) + + ", ctx=" + config.context); + } + let returnState = t.followState; + let newContext; + if (this.optimize_tail_calls && t.optimizedTailCall && (!this.tail_call_preserves_sll || !PredictionContext_1.PredictionContext.isEmptyLocal(config.context))) { + newContext = config.context; + } + else if (contextCache != null) { + newContext = contextCache.getChild(config.context, returnState.stateNumber); + } + else { + newContext = config.context.getChild(returnState.stateNumber); + } + return config.transform(t.target, false, newContext); + } + isConflicted(configset, contextCache) { + if (configset.uniqueAlt !== ATN_1.ATN.INVALID_ALT_NUMBER || configset.size <= 1) { + return undefined; + } + let configs = configset.toArray(); + configs.sort(ParserATNSimulator.STATE_ALT_SORT_COMPARATOR); + let exact = !configset.dipsIntoOuterContext; + let alts = new BitSet_1.BitSet(); + let minAlt = configs[0].alt; + alts.set(minAlt); + /* Quick checks come first (single pass, no context joining): + * 1. Make sure first config in the sorted list predicts the minimum + * represented alternative. + * 2. Make sure every represented state has at least one configuration + * which predicts the minimum represented alternative. + * 3. (exact only) make sure every represented state has at least one + * configuration which predicts each represented alternative. + */ + // quick check 1 & 2 => if we assume #1 holds and check #2 against the + // minAlt from the first state, #2 will fail if the assumption was + // incorrect + let currentState = configs[0].state.nonStopStateNumber; + for (let config of configs) { + let stateNumber = config.state.nonStopStateNumber; + if (stateNumber !== currentState) { + if (config.alt !== minAlt) { + return undefined; + } + currentState = stateNumber; + } + } + let representedAlts; + if (exact) { + currentState = configs[0].state.nonStopStateNumber; + // get the represented alternatives of the first state + representedAlts = new BitSet_1.BitSet(); + let maxAlt = minAlt; + for (let config of configs) { + if (config.state.nonStopStateNumber !== currentState) { + break; + } + let alt = config.alt; + representedAlts.set(alt); + maxAlt = alt; + } + // quick check #3: + currentState = configs[0].state.nonStopStateNumber; + let currentAlt = minAlt; + for (let config of configs) { + let stateNumber = config.state.nonStopStateNumber; + let alt = config.alt; + if (stateNumber !== currentState) { + if (currentAlt !== maxAlt) { + exact = false; + break; + } + currentState = stateNumber; + currentAlt = minAlt; + } + else if (alt !== currentAlt) { + if (alt !== representedAlts.nextSetBit(currentAlt + 1)) { + exact = false; + break; + } + currentAlt = alt; + } + } + } + currentState = configs[0].state.nonStopStateNumber; + let firstIndexCurrentState = 0; + let lastIndexCurrentStateMinAlt = 0; + let joinedCheckContext = configs[0].context; + for (let i = 1; i < configs.length; i++) { + let config = configs[i]; + if (config.alt !== minAlt) { + break; + } + if (config.state.nonStopStateNumber !== currentState) { + break; + } + lastIndexCurrentStateMinAlt = i; + joinedCheckContext = contextCache.join(joinedCheckContext, configs[i].context); + } + for (let i = lastIndexCurrentStateMinAlt + 1; i < configs.length; i++) { + let config = configs[i]; + let state = config.state; + alts.set(config.alt); + if (state.nonStopStateNumber !== currentState) { + currentState = state.nonStopStateNumber; + firstIndexCurrentState = i; + lastIndexCurrentStateMinAlt = i; + joinedCheckContext = config.context; + for (let j = firstIndexCurrentState + 1; j < configs.length; j++) { + let config2 = configs[j]; + if (config2.alt !== minAlt) { + break; + } + if (config2.state.nonStopStateNumber !== currentState) { + break; + } + lastIndexCurrentStateMinAlt = j; + joinedCheckContext = contextCache.join(joinedCheckContext, config2.context); + } + i = lastIndexCurrentStateMinAlt; + continue; + } + let joinedCheckContext2 = config.context; + let currentAlt = config.alt; + let lastIndexCurrentStateCurrentAlt = i; + for (let j = lastIndexCurrentStateCurrentAlt + 1; j < configs.length; j++) { + let config2 = configs[j]; + if (config2.alt !== currentAlt) { + break; + } + if (config2.state.nonStopStateNumber !== currentState) { + break; + } + lastIndexCurrentStateCurrentAlt = j; + joinedCheckContext2 = contextCache.join(joinedCheckContext2, config2.context); + } + i = lastIndexCurrentStateCurrentAlt; + let check = contextCache.join(joinedCheckContext, joinedCheckContext2); + if (!joinedCheckContext.equals(check)) { + return undefined; + } + // update exact if necessary + exact = exact && joinedCheckContext.equals(joinedCheckContext2); + } + return new ConflictInfo_1.ConflictInfo(alts, exact); + } + getConflictingAltsFromConfigSet(configs) { + let conflictingAlts = configs.conflictingAlts; + if (conflictingAlts == null && configs.uniqueAlt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + conflictingAlts = new BitSet_1.BitSet(); + conflictingAlts.set(configs.uniqueAlt); + } + return conflictingAlts; + } + getTokenName(t) { + if (t === Token_1.Token.EOF) { + return "EOF"; + } + let vocabulary = this._parser != null ? this._parser.vocabulary : VocabularyImpl_1.VocabularyImpl.EMPTY_VOCABULARY; + let displayName = vocabulary.getDisplayName(t); + if (displayName === String(t)) { + return displayName; + } + return displayName + "<" + t + ">"; + } + getLookaheadName(input) { + return this.getTokenName(input.LA(1)); + } + dumpDeadEndConfigs(nvae) { + console.log("dead end configs: "); + let deadEndConfigs = nvae.deadEndConfigs; + if (!deadEndConfigs) { + return; + } + for (let c of deadEndConfigs) { + let trans = "no edges"; + if (c.state.numberOfOptimizedTransitions > 0) { + let t = c.state.getOptimizedTransition(0); + if (t instanceof AtomTransition_1.AtomTransition) { + trans = "Atom " + this.getTokenName(t._label); + } + else if (t instanceof SetTransition_1.SetTransition) { + let not = t instanceof NotSetTransition_1.NotSetTransition; + trans = (not ? "~" : "") + "Set " + t.set.toString(); + } + } + console.log(c.toString(this._parser, true) + ":" + trans); + } + } + noViableAlt(input, outerContext, configs, startIndex) { + return new NoViableAltException_1.NoViableAltException(this._parser, input, input.get(startIndex), input.LT(1), configs, outerContext); + } + getUniqueAlt(configs) { + let alt = ATN_1.ATN.INVALID_ALT_NUMBER; + for (let c of configs) { + if (alt === ATN_1.ATN.INVALID_ALT_NUMBER) { + alt = c.alt; // found first alt + } + else if (c.alt !== alt) { + return ATN_1.ATN.INVALID_ALT_NUMBER; + } + } + return alt; + } + configWithAltAtStopState(configs, alt) { + for (let c of configs) { + if (c.alt === alt) { + if (c.state instanceof RuleStopState_1.RuleStopState) { + return true; + } + } + } + return false; + } + addDFAEdge(dfa, fromState, t, contextTransitions, toConfigs, contextCache) { + assert(contextTransitions == null || contextTransitions.isEmpty || dfa.isContextSensitive); + let from = fromState; + let to = this.addDFAState(dfa, toConfigs, contextCache); + if (contextTransitions != null) { + for (let context of contextTransitions.toArray()) { + if (context === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + if (from.configs.isOutermostConfigSet) { + continue; + } + } + from.setContextSensitive(this.atn); + from.setContextSymbol(t); + let next = from.getContextTarget(context); + if (next != null) { + from = next; + continue; + } + next = this.addDFAContextState(dfa, from.configs, context, contextCache); + assert(context !== PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY || next.configs.isOutermostConfigSet); + from.setContextTarget(context, next); + from = next; + } + } + if (ParserATNSimulator.debug) { + console.log("EDGE " + from + " -> " + to + " upon " + this.getTokenName(t)); + } + this.setDFAEdge(from, t, to); + if (ParserATNSimulator.debug) { + console.log("DFA=\n" + dfa.toString(this._parser != null ? this._parser.vocabulary : VocabularyImpl_1.VocabularyImpl.EMPTY_VOCABULARY, this._parser != null ? this._parser.ruleNames : undefined)); + } + return to; + } + setDFAEdge(p, t, q) { + if (p != null) { + p.setTarget(t, q); + } + } + /** See comment on LexerInterpreter.addDFAState. */ + addDFAContextState(dfa, configs, returnContext, contextCache) { + if (returnContext !== PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) { + let contextConfigs = new ATNConfigSet_1.ATNConfigSet(); + for (let config of configs) { + contextConfigs.add(config.appendContext(returnContext, contextCache)); + } + return this.addDFAState(dfa, contextConfigs, contextCache); + } + else { + assert(!configs.isOutermostConfigSet, "Shouldn't be adding a duplicate edge."); + configs = configs.clone(true); + configs.isOutermostConfigSet = true; + return this.addDFAState(dfa, configs, contextCache); + } + } + /** See comment on LexerInterpreter.addDFAState. */ + addDFAState(dfa, configs, contextCache) { + let enableDfa = this.enable_global_context_dfa || !configs.isOutermostConfigSet; + if (enableDfa) { + if (!configs.isReadOnly) { + configs.optimizeConfigs(this); + } + let proposed = this.createDFAState(dfa, configs); + let existing = dfa.states.get(proposed); + if (existing != null) { + return existing; + } + } + if (!configs.isReadOnly) { + if (configs.conflictInfo == null) { + configs.conflictInfo = this.isConflicted(configs, contextCache); + } + } + let newState = this.createDFAState(dfa, configs.clone(true)); + // getDecisionState won't return undefined when we request a known valid decision + let decisionState = this.atn.getDecisionState(dfa.decision); + let predictedAlt = this.getUniqueAlt(configs); + if (predictedAlt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + newState.acceptStateInfo = new AcceptStateInfo_1.AcceptStateInfo(predictedAlt); + } + else if (configs.conflictingAlts != null) { + let conflictingAlts = configs.conflictingAlts; + if (conflictingAlts) { + newState.acceptStateInfo = new AcceptStateInfo_1.AcceptStateInfo(conflictingAlts.nextSetBit(0)); + } + } + if (newState.isAcceptState && configs.hasSemanticContext) { + this.predicateDFAState(newState, configs, decisionState.numberOfTransitions); + } + if (!enableDfa) { + return newState; + } + let added = dfa.addState(newState); + if (ParserATNSimulator.debug && added === newState) { + console.log("adding new DFA state: " + newState); + } + return added; + } + createDFAState(dfa, configs) { + return new DFAState_1.DFAState(configs); + } + reportAttemptingFullContext(dfa, conflictingAlts, conflictState, startIndex, stopIndex) { + if (ParserATNSimulator.debug || ParserATNSimulator.retry_debug) { + let interval = Interval_1.Interval.of(startIndex, stopIndex); + console.log("reportAttemptingFullContext decision=" + dfa.decision + ":" + conflictState.s0.configs + + ", input=" + this._parser.inputStream.getText(interval)); + } + if (this._parser != null) { + let listener = this._parser.getErrorListenerDispatch(); + if (listener.reportAttemptingFullContext) { + listener.reportAttemptingFullContext(this._parser, dfa, startIndex, stopIndex, conflictingAlts, conflictState); + } + } + } + reportContextSensitivity(dfa, prediction, acceptState, startIndex, stopIndex) { + if (ParserATNSimulator.debug || ParserATNSimulator.retry_debug) { + let interval = Interval_1.Interval.of(startIndex, stopIndex); + console.log("reportContextSensitivity decision=" + dfa.decision + ":" + acceptState.s0.configs + + ", input=" + this._parser.inputStream.getText(interval)); + } + if (this._parser != null) { + let listener = this._parser.getErrorListenerDispatch(); + if (listener.reportContextSensitivity) { + listener.reportContextSensitivity(this._parser, dfa, startIndex, stopIndex, prediction, acceptState); + } + } + } + /** If context sensitive parsing, we know it's ambiguity not conflict */ + reportAmbiguity(dfa, D, // the DFA state from execATN(): void that had SLL conflicts + startIndex, stopIndex, exact, ambigAlts, configs) { + if (ParserATNSimulator.debug || ParserATNSimulator.retry_debug) { + let interval = Interval_1.Interval.of(startIndex, stopIndex); + console.log("reportAmbiguity " + + ambigAlts + ":" + configs + + ", input=" + this._parser.inputStream.getText(interval)); + } + if (this._parser != null) { + let listener = this._parser.getErrorListenerDispatch(); + if (listener.reportAmbiguity) { + listener.reportAmbiguity(this._parser, dfa, startIndex, stopIndex, exact, ambigAlts, configs); + } + } + } + getReturnState(context) { + if (context.isEmpty) { + return PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY; + } + let state = this.atn.states[context.invokingState]; + let transition = state.transition(0); + return transition.followState.stateNumber; + } + skipTailCalls(context) { + if (!this.optimize_tail_calls) { + return context; + } + while (!context.isEmpty) { + let state = this.atn.states[context.invokingState]; + assert(state.numberOfTransitions === 1 && state.transition(0).serializationType === 3 /* RULE */); + let transition = state.transition(0); + if (!transition.tailCall) { + break; + } + // This method requires that the root ancestor of the ParserRuleContext be empty. If we make it to this + // line, we know the current node is not empty, which means it does have a parent. + context = context.parent; + } + return context; + } + /** + * @since 4.3 + */ + get parser() { + return this._parser; + } + }; + ParserATNSimulator$1.debug = false; + ParserATNSimulator$1.dfa_debug = false; + ParserATNSimulator$1.retry_debug = false; + ParserATNSimulator$1.STATE_ALT_SORT_COMPARATOR = (o1, o2) => { + let diff = o1.state.nonStopStateNumber - o2.state.nonStopStateNumber; + if (diff !== 0) { + return diff; + } + diff = o1.alt - o2.alt; + if (diff !== 0) { + return diff; + } + return 0; + }; + __decorate([ + Decorators_1.NotNull + ], ParserATNSimulator$1.prototype, "predictionMode", void 0); + __decorate([ + Decorators_1.NotNull + ], ParserATNSimulator$1.prototype, "getPredictionMode", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "setPredictionMode", null); + __decorate([ + Decorators_1.Override + ], ParserATNSimulator$1.prototype, "reset", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "adaptivePredict", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getStartState", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "execDFA", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "execATN", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "handleNoViableAlt", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getExistingTargetState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "computeTargetState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "removeAllConfigsNotInRuleStopState", null); + __decorate([ + Decorators_1.NotNull + ], ParserATNSimulator$1.prototype, "computeStartState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "applyPrecedenceFilter", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getReachableTarget", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getPredsForAmbigAlts", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "evalSemanticContext", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "evalSemanticContextImpl", null); + __decorate([ + __param(1, Decorators_1.NotNull), + __param(4, Decorators_1.Nullable) + ], ParserATNSimulator$1.prototype, "closure", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.Nullable), + __param(3, Decorators_1.NotNull), + __param(6, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "closureImpl", null); + __decorate([ + Decorators_1.NotNull + ], ParserATNSimulator$1.prototype, "getRuleName", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getEpsilonTarget", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "actionTransition", null); + __decorate([ + Decorators_1.Nullable, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "precedenceTransition", null); + __decorate([ + Decorators_1.Nullable, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "predTransition", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull), __param(2, Decorators_1.Nullable) + ], ParserATNSimulator$1.prototype, "ruleTransition", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "isConflicted", null); + __decorate([ + Decorators_1.NotNull + ], ParserATNSimulator$1.prototype, "getTokenName", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "dumpDeadEndConfigs", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "noViableAlt", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "getUniqueAlt", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "configWithAltAtStopState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(4, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "addDFAEdge", null); + __decorate([ + __param(0, Decorators_1.Nullable), __param(2, Decorators_1.Nullable) + ], ParserATNSimulator$1.prototype, "setDFAEdge", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "addDFAContextState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "addDFAState", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "createDFAState", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "reportAttemptingFullContext", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(2, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "reportContextSensitivity", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(5, Decorators_1.NotNull), + __param(6, Decorators_1.NotNull) + ], ParserATNSimulator$1.prototype, "reportAmbiguity", null); + ParserATNSimulator$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ParserATNSimulator$1); + ParserATNSimulator.ParserATNSimulator = ParserATNSimulator$1; + + return ParserATNSimulator; +} + +var PlusBlockStartState = {}; + +var hasRequiredPlusBlockStartState; + +function requirePlusBlockStartState () { + if (hasRequiredPlusBlockStartState) return PlusBlockStartState; + hasRequiredPlusBlockStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PlusBlockStartState && PlusBlockStartState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(PlusBlockStartState, "__esModule", { value: true }); + PlusBlockStartState.PlusBlockStartState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:34.9572142-07:00 + const ATNStateType_1 = requireATNStateType(); + const BlockStartState_1 = requireBlockStartState(); + const Decorators_1 = requireDecorators(); + /** Start of `(A|B|...)+` loop. Technically a decision state, but + * we don't use for code generation; somebody might need it, so I'm defining + * it for completeness. In reality, the {@link PlusLoopbackState} node is the + * real decision-making note for `A+`. + */ + let PlusBlockStartState$1 = class PlusBlockStartState extends BlockStartState_1.BlockStartState { + get stateType() { + return ATNStateType_1.ATNStateType.PLUS_BLOCK_START; + } + }; + __decorate([ + Decorators_1.Override + ], PlusBlockStartState$1.prototype, "stateType", null); + PlusBlockStartState.PlusBlockStartState = PlusBlockStartState$1; + + return PlusBlockStartState; +} + +var PlusLoopbackState = {}; + +var hasRequiredPlusLoopbackState; + +function requirePlusLoopbackState () { + if (hasRequiredPlusLoopbackState) return PlusLoopbackState; + hasRequiredPlusLoopbackState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PlusLoopbackState && PlusLoopbackState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(PlusLoopbackState, "__esModule", { value: true }); + PlusLoopbackState.PlusLoopbackState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.0257730-07:00 + const ATNStateType_1 = requireATNStateType(); + const DecisionState_1 = requireDecisionState(); + const Decorators_1 = requireDecorators(); + /** Decision state for `A+` and `(A|B)+`. It has two transitions: + * one to the loop back to start of the block and one to exit. + */ + let PlusLoopbackState$1 = class PlusLoopbackState extends DecisionState_1.DecisionState { + get stateType() { + return ATNStateType_1.ATNStateType.PLUS_LOOP_BACK; + } + }; + __decorate([ + Decorators_1.Override + ], PlusLoopbackState$1.prototype, "stateType", null); + PlusLoopbackState.PlusLoopbackState = PlusLoopbackState$1; + + return PlusLoopbackState; +} + +var PrecedencePredicateTransition = {}; + +var hasRequiredPrecedencePredicateTransition; + +function requirePrecedencePredicateTransition () { + if (hasRequiredPrecedencePredicateTransition) return PrecedencePredicateTransition; + hasRequiredPrecedencePredicateTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PrecedencePredicateTransition && PrecedencePredicateTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (PrecedencePredicateTransition && PrecedencePredicateTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(PrecedencePredicateTransition, "__esModule", { value: true }); + PrecedencePredicateTransition.PrecedencePredicateTransition = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.0994191-07:00 + const AbstractPredicateTransition_1 = requireAbstractPredicateTransition(); + const Decorators_1 = requireDecorators(); + const SemanticContext_1 = requireSemanticContext(); + /** + * + * @author Sam Harwell + */ + let PrecedencePredicateTransition$1 = class PrecedencePredicateTransition extends AbstractPredicateTransition_1.AbstractPredicateTransition { + constructor(target, precedence) { + super(target); + this.precedence = precedence; + } + get serializationType() { + return 10 /* PRECEDENCE */; + } + get isEpsilon() { + return true; + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return false; + } + get predicate() { + return new SemanticContext_1.SemanticContext.PrecedencePredicate(this.precedence); + } + toString() { + return this.precedence + " >= _p"; + } + }; + __decorate([ + Decorators_1.Override + ], PrecedencePredicateTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicateTransition$1.prototype, "isEpsilon", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicateTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override + ], PrecedencePredicateTransition$1.prototype, "toString", null); + PrecedencePredicateTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], PrecedencePredicateTransition$1); + PrecedencePredicateTransition.PrecedencePredicateTransition = PrecedencePredicateTransition$1; + + return PrecedencePredicateTransition; +} + +var RangeTransition = {}; + +var hasRequiredRangeTransition; + +function requireRangeTransition () { + if (hasRequiredRangeTransition) return RangeTransition; + hasRequiredRangeTransition = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RangeTransition && RangeTransition.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (RangeTransition && RangeTransition.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(RangeTransition, "__esModule", { value: true }); + RangeTransition.RangeTransition = void 0; + const IntervalSet_1 = requireIntervalSet(); + const Decorators_1 = requireDecorators(); + const Transition_1 = requireTransition(); + let RangeTransition$1 = class RangeTransition extends Transition_1.Transition { + constructor(target, from, to) { + super(target); + this.from = from; + this.to = to; + } + get serializationType() { + return 2 /* RANGE */; + } + get label() { + return IntervalSet_1.IntervalSet.of(this.from, this.to); + } + matches(symbol, minVocabSymbol, maxVocabSymbol) { + return symbol >= this.from && symbol <= this.to; + } + toString() { + return "'" + String.fromCodePoint(this.from) + "'..'" + String.fromCodePoint(this.to) + "'"; + } + }; + __decorate([ + Decorators_1.Override + ], RangeTransition$1.prototype, "serializationType", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], RangeTransition$1.prototype, "label", null); + __decorate([ + Decorators_1.Override + ], RangeTransition$1.prototype, "matches", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull + ], RangeTransition$1.prototype, "toString", null); + RangeTransition$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], RangeTransition$1); + RangeTransition.RangeTransition = RangeTransition$1; + + return RangeTransition; +} + +var RuleStartState = {}; + +var hasRequiredRuleStartState; + +function requireRuleStartState () { + if (hasRequiredRuleStartState) return RuleStartState; + hasRequiredRuleStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleStartState && RuleStartState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(RuleStartState, "__esModule", { value: true }); + RuleStartState.RuleStartState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:36.6806851-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + let RuleStartState$1 = class RuleStartState extends ATNState_1.ATNState { + constructor() { + super(...arguments); + this.isPrecedenceRule = false; + this.leftFactored = false; + } + get stateType() { + return ATNStateType_1.ATNStateType.RULE_START; + } + }; + __decorate([ + Decorators_1.Override + ], RuleStartState$1.prototype, "stateType", null); + RuleStartState.RuleStartState = RuleStartState$1; + + return RuleStartState; +} + +var StarBlockStartState = {}; + +var hasRequiredStarBlockStartState; + +function requireStarBlockStartState () { + if (hasRequiredStarBlockStartState) return StarBlockStartState; + hasRequiredStarBlockStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (StarBlockStartState && StarBlockStartState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(StarBlockStartState, "__esModule", { value: true }); + StarBlockStartState.StarBlockStartState = void 0; + const ATNStateType_1 = requireATNStateType(); + const BlockStartState_1 = requireBlockStartState(); + const Decorators_1 = requireDecorators(); + /** The block that begins a closure loop. */ + let StarBlockStartState$1 = class StarBlockStartState extends BlockStartState_1.BlockStartState { + get stateType() { + return ATNStateType_1.ATNStateType.STAR_BLOCK_START; + } + }; + __decorate([ + Decorators_1.Override + ], StarBlockStartState$1.prototype, "stateType", null); + StarBlockStartState.StarBlockStartState = StarBlockStartState$1; + + return StarBlockStartState; +} + +var StarLoopbackState = {}; + +var hasRequiredStarLoopbackState; + +function requireStarLoopbackState () { + if (hasRequiredStarLoopbackState) return StarLoopbackState; + hasRequiredStarLoopbackState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (StarLoopbackState && StarLoopbackState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(StarLoopbackState, "__esModule", { value: true }); + StarLoopbackState.StarLoopbackState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:37.6368726-07:00 + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const Decorators_1 = requireDecorators(); + let StarLoopbackState$1 = class StarLoopbackState extends ATNState_1.ATNState { + get loopEntryState() { + return this.transition(0).target; + } + get stateType() { + return ATNStateType_1.ATNStateType.STAR_LOOP_BACK; + } + }; + __decorate([ + Decorators_1.Override + ], StarLoopbackState$1.prototype, "stateType", null); + StarLoopbackState.StarLoopbackState = StarLoopbackState$1; + + return StarLoopbackState; +} + +var TokensStartState = {}; + +var hasRequiredTokensStartState; + +function requireTokensStartState () { + if (hasRequiredTokensStartState) return TokensStartState; + hasRequiredTokensStartState = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TokensStartState && TokensStartState.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(TokensStartState, "__esModule", { value: true }); + TokensStartState.TokensStartState = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:37.7814046-07:00 + const ATNStateType_1 = requireATNStateType(); + const DecisionState_1 = requireDecisionState(); + const Decorators_1 = requireDecorators(); + /** The Tokens rule start state linking to each lexer rule start state */ + let TokensStartState$1 = class TokensStartState extends DecisionState_1.DecisionState { + get stateType() { + return ATNStateType_1.ATNStateType.TOKEN_START; + } + }; + __decorate([ + Decorators_1.Override + ], TokensStartState$1.prototype, "stateType", null); + TokensStartState.TokensStartState = TokensStartState$1; + + return TokensStartState; +} + +var UUID = {}; + +var hasRequiredUUID; + +function requireUUID () { + if (hasRequiredUUID) return UUID; + hasRequiredUUID = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(UUID, "__esModule", { value: true }); + UUID.UUID = void 0; + const MurmurHash_1 = requireMurmurHash(); + let UUID$1 = class UUID { + constructor(mostSigBits, moreSigBits, lessSigBits, leastSigBits) { + this.data = new Uint32Array(4); + this.data[0] = mostSigBits; + this.data[1] = moreSigBits; + this.data[2] = lessSigBits; + this.data[3] = leastSigBits; + } + static fromString(data) { + if (!/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(data)) { + throw new Error("Incorrectly formatted UUID"); + } + let segments = data.split("-"); + let mostSigBits = parseInt(segments[0], 16); + let moreSigBits = ((parseInt(segments[1], 16) << 16) >>> 0) + parseInt(segments[2], 16); + let lessSigBits = ((parseInt(segments[3], 16) << 16) >>> 0) + parseInt(segments[4].substr(0, 4), 16); + let leastSigBits = parseInt(segments[4].substr(-8), 16); + return new UUID(mostSigBits, moreSigBits, lessSigBits, leastSigBits); + } + hashCode() { + return MurmurHash_1.MurmurHash.hashCode([this.data[0], this.data[1], this.data[2], this.data[3]]); + } + equals(obj) { + if (obj === this) { + return true; + } + else if (!(obj instanceof UUID)) { + return false; + } + return this.data[0] === obj.data[0] + && this.data[1] === obj.data[1] + && this.data[2] === obj.data[2] + && this.data[3] === obj.data[3]; + } + toString() { + return ("00000000" + this.data[0].toString(16)).substr(-8) + + "-" + ("0000" + (this.data[1] >>> 16).toString(16)).substr(-4) + + "-" + ("0000" + this.data[1].toString(16)).substr(-4) + + "-" + ("0000" + (this.data[2] >>> 16).toString(16)).substr(-4) + + "-" + ("0000" + this.data[2].toString(16)).substr(-4) + + ("00000000" + this.data[3].toString(16)).substr(-8); + } + }; + UUID.UUID = UUID$1; + + return UUID; +} + +var hasRequiredATNDeserializer; + +function requireATNDeserializer () { + if (hasRequiredATNDeserializer) return ATNDeserializer; + hasRequiredATNDeserializer = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ATNDeserializer && ATNDeserializer.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ATNDeserializer && ATNDeserializer.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ATNDeserializer, "__esModule", { value: true }); + ATNDeserializer.ATNDeserializer = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:25.9683447-07:00 + const ActionTransition_1 = requireActionTransition(); + const Array2DHashSet_1 = requireArray2DHashSet(); + const ATN_1 = requireATN(); + const ATNDeserializationOptions_1 = requireATNDeserializationOptions(); + const ATNStateType_1 = requireATNStateType(); + const AtomTransition_1 = requireAtomTransition(); + const BasicBlockStartState_1 = requireBasicBlockStartState(); + const BasicState_1 = requireBasicState(); + const BitSet_1 = requireBitSet(); + const BlockEndState_1 = requireBlockEndState(); + const BlockStartState_1 = requireBlockStartState(); + const DecisionState_1 = requireDecisionState(); + const DFA_1 = requireDFA(); + const EpsilonTransition_1 = requireEpsilonTransition(); + const IntervalSet_1 = requireIntervalSet(); + const InvalidState_1 = requireInvalidState(); + const LexerChannelAction_1 = requireLexerChannelAction(); + const LexerCustomAction_1 = requireLexerCustomAction(); + const LexerModeAction_1 = requireLexerModeAction(); + const LexerMoreAction_1 = requireLexerMoreAction(); + const LexerPopModeAction_1 = requireLexerPopModeAction(); + const LexerPushModeAction_1 = requireLexerPushModeAction(); + const LexerSkipAction_1 = requireLexerSkipAction(); + const LexerTypeAction_1 = requireLexerTypeAction(); + const LoopEndState_1 = requireLoopEndState(); + const Decorators_1 = requireDecorators(); + const NotSetTransition_1 = requireNotSetTransition(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const PlusBlockStartState_1 = requirePlusBlockStartState(); + const PlusLoopbackState_1 = requirePlusLoopbackState(); + const PrecedencePredicateTransition_1 = requirePrecedencePredicateTransition(); + const PredicateTransition_1 = requirePredicateTransition(); + const RangeTransition_1 = requireRangeTransition(); + const RuleStartState_1 = requireRuleStartState(); + const RuleStopState_1 = requireRuleStopState(); + const RuleTransition_1 = requireRuleTransition(); + const SetTransition_1 = requireSetTransition(); + const StarBlockStartState_1 = requireStarBlockStartState(); + const StarLoopbackState_1 = requireStarLoopbackState(); + const StarLoopEntryState_1 = requireStarLoopEntryState(); + const Token_1 = requireToken(); + const TokensStartState_1 = requireTokensStartState(); + const UUID_1 = requireUUID(); + const WildcardTransition_1 = requireWildcardTransition(); + var UnicodeDeserializingMode; + (function (UnicodeDeserializingMode) { + UnicodeDeserializingMode[UnicodeDeserializingMode["UNICODE_BMP"] = 0] = "UNICODE_BMP"; + UnicodeDeserializingMode[UnicodeDeserializingMode["UNICODE_SMP"] = 1] = "UNICODE_SMP"; + })(UnicodeDeserializingMode || (UnicodeDeserializingMode = {})); + /** + * + * @author Sam Harwell + */ + let ATNDeserializer$1 = class ATNDeserializer { + constructor(deserializationOptions) { + if (deserializationOptions === undefined) { + deserializationOptions = ATNDeserializationOptions_1.ATNDeserializationOptions.defaultOptions; + } + this.deserializationOptions = deserializationOptions; + } + static get SERIALIZED_VERSION() { + /* This value should never change. Updates following this version are + * reflected as change in the unique ID SERIALIZED_UUID. + */ + return 3; + } + /** + * Determines if a particular serialized representation of an ATN supports + * a particular feature, identified by the {@link UUID} used for serializing + * the ATN at the time the feature was first introduced. + * + * @param feature The {@link UUID} marking the first time the feature was + * supported in the serialized ATN. + * @param actualUuid The {@link UUID} of the actual serialized ATN which is + * currently being deserialized. + * @returns `true` if the `actualUuid` value represents a + * serialized ATN at or after the feature identified by `feature` was + * introduced; otherwise, `false`. + */ + static isFeatureSupported(feature, actualUuid) { + let featureIndex = ATNDeserializer.SUPPORTED_UUIDS.findIndex((e) => e.equals(feature)); + if (featureIndex < 0) { + return false; + } + return ATNDeserializer.SUPPORTED_UUIDS.findIndex((e) => e.equals(actualUuid)) >= featureIndex; + } + static getUnicodeDeserializer(mode) { + if (mode === 0 /* UNICODE_BMP */) { + return { + readUnicode: (data, p) => { + return ATNDeserializer.toInt(data[p]); + }, + size: 1, + }; + } + else { + return { + readUnicode: (data, p) => { + return ATNDeserializer.toInt32(data, p); + }, + size: 2, + }; + } + } + deserialize(data) { + data = data.slice(0); + // Each Uint16 value in data is shifted by +2 at the entry to this method. This is an encoding optimization + // targeting the serialized values 0 and -1 (serialized to 0xFFFF), each of which are very common in the + // serialized form of the ATN. In the modified UTF-8 that Java uses for compiled string literals, these two + // character values have multi-byte forms. By shifting each value by +2, they become characters 2 and 1 prior to + // writing the string, each of which have single-byte representations. Since the shift occurs in the tool during + // ATN serialization, each target is responsible for adjusting the values during deserialization. + // + // As a special case, note that the first element of data is not adjusted because it contains the major version + // number of the serialized ATN, which was fixed at 3 at the time the value shifting was implemented. + for (let i = 1; i < data.length; i++) { + data[i] = (data[i] - 2) & 0xFFFF; + } + let p = 0; + let version = ATNDeserializer.toInt(data[p++]); + if (version !== ATNDeserializer.SERIALIZED_VERSION) { + let reason = `Could not deserialize ATN with version ${version} (expected ${ATNDeserializer.SERIALIZED_VERSION}).`; + throw new Error(reason); + } + let uuid = ATNDeserializer.toUUID(data, p); + p += 8; + if (ATNDeserializer.SUPPORTED_UUIDS.findIndex((e) => e.equals(uuid)) < 0) { + let reason = `Could not deserialize ATN with UUID ${uuid} (expected ${ATNDeserializer.SERIALIZED_UUID} or a legacy UUID).`; + throw new Error(reason); + } + let supportsLexerActions = ATNDeserializer.isFeatureSupported(ATNDeserializer.ADDED_LEXER_ACTIONS, uuid); + let grammarType = ATNDeserializer.toInt(data[p++]); + let maxTokenType = ATNDeserializer.toInt(data[p++]); + let atn = new ATN_1.ATN(grammarType, maxTokenType); + // + // STATES + // + let loopBackStateNumbers = []; + let endStateNumbers = []; + let nstates = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < nstates; i++) { + let stype = ATNDeserializer.toInt(data[p++]); + // ignore bad type of states + if (stype === ATNStateType_1.ATNStateType.INVALID_TYPE) { + atn.addState(new InvalidState_1.InvalidState()); + continue; + } + let ruleIndex = ATNDeserializer.toInt(data[p++]); + if (ruleIndex === 0xFFFF) { + ruleIndex = -1; + } + let s = this.stateFactory(stype, ruleIndex); + if (stype === ATNStateType_1.ATNStateType.LOOP_END) { // special case + let loopBackStateNumber = ATNDeserializer.toInt(data[p++]); + loopBackStateNumbers.push([s, loopBackStateNumber]); + } + else if (s instanceof BlockStartState_1.BlockStartState) { + let endStateNumber = ATNDeserializer.toInt(data[p++]); + endStateNumbers.push([s, endStateNumber]); + } + atn.addState(s); + } + // delay the assignment of loop back and end states until we know all the state instances have been initialized + for (let pair of loopBackStateNumbers) { + pair[0].loopBackState = atn.states[pair[1]]; + } + for (let pair of endStateNumbers) { + pair[0].endState = atn.states[pair[1]]; + } + let numNonGreedyStates = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < numNonGreedyStates; i++) { + let stateNumber = ATNDeserializer.toInt(data[p++]); + atn.states[stateNumber].nonGreedy = true; + } + let numSllDecisions = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < numSllDecisions; i++) { + let stateNumber = ATNDeserializer.toInt(data[p++]); + atn.states[stateNumber].sll = true; + } + let numPrecedenceStates = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < numPrecedenceStates; i++) { + let stateNumber = ATNDeserializer.toInt(data[p++]); + atn.states[stateNumber].isPrecedenceRule = true; + } + // + // RULES + // + let nrules = ATNDeserializer.toInt(data[p++]); + if (atn.grammarType === 0 /* LEXER */) { + atn.ruleToTokenType = new Int32Array(nrules); + } + atn.ruleToStartState = new Array(nrules); + for (let i = 0; i < nrules; i++) { + let s = ATNDeserializer.toInt(data[p++]); + let startState = atn.states[s]; + startState.leftFactored = ATNDeserializer.toInt(data[p++]) !== 0; + atn.ruleToStartState[i] = startState; + if (atn.grammarType === 0 /* LEXER */) { + let tokenType = ATNDeserializer.toInt(data[p++]); + if (tokenType === 0xFFFF) { + tokenType = Token_1.Token.EOF; + } + atn.ruleToTokenType[i] = tokenType; + if (!ATNDeserializer.isFeatureSupported(ATNDeserializer.ADDED_LEXER_ACTIONS, uuid)) { + // this piece of unused metadata was serialized prior to the + // addition of LexerAction + ATNDeserializer.toInt(data[p++]); + } + } + } + atn.ruleToStopState = new Array(nrules); + for (let state of atn.states) { + if (!(state instanceof RuleStopState_1.RuleStopState)) { + continue; + } + atn.ruleToStopState[state.ruleIndex] = state; + atn.ruleToStartState[state.ruleIndex].stopState = state; + } + // + // MODES + // + let nmodes = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < nmodes; i++) { + let s = ATNDeserializer.toInt(data[p++]); + atn.modeToStartState.push(atn.states[s]); + } + atn.modeToDFA = new Array(nmodes); + for (let i = 0; i < nmodes; i++) { + atn.modeToDFA[i] = new DFA_1.DFA(atn.modeToStartState[i]); + } + // + // SETS + // + let sets = []; + // First, read all sets with 16-bit Unicode code points <= U+FFFF. + p = this.deserializeSets(data, p, sets, ATNDeserializer.getUnicodeDeserializer(0 /* UNICODE_BMP */)); + // Next, if the ATN was serialized with the Unicode SMP feature, + // deserialize sets with 32-bit arguments <= U+10FFFF. + if (ATNDeserializer.isFeatureSupported(ATNDeserializer.ADDED_UNICODE_SMP, uuid)) { + p = this.deserializeSets(data, p, sets, ATNDeserializer.getUnicodeDeserializer(1 /* UNICODE_SMP */)); + } + // + // EDGES + // + let nedges = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < nedges; i++) { + let src = ATNDeserializer.toInt(data[p]); + let trg = ATNDeserializer.toInt(data[p + 1]); + let ttype = ATNDeserializer.toInt(data[p + 2]); + let arg1 = ATNDeserializer.toInt(data[p + 3]); + let arg2 = ATNDeserializer.toInt(data[p + 4]); + let arg3 = ATNDeserializer.toInt(data[p + 5]); + let trans = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets); + // console.log(`EDGE ${trans.constructor.name} ${src}->${trg} ${Transition.serializationNames[ttype]} ${arg1},${arg2},${arg3}`); + let srcState = atn.states[src]; + srcState.addTransition(trans); + p += 6; + } + let returnTransitionsSet = new Array2DHashSet_1.Array2DHashSet({ + hashCode: (o) => o.stopState ^ o.returnState ^ o.outermostPrecedenceReturn, + equals: (a, b) => { + return a.stopState === b.stopState + && a.returnState === b.returnState + && a.outermostPrecedenceReturn === b.outermostPrecedenceReturn; + }, + }); + let returnTransitions = []; + for (let state of atn.states) { + let returningToLeftFactored = state.ruleIndex >= 0 && atn.ruleToStartState[state.ruleIndex].leftFactored; + for (let i = 0; i < state.numberOfTransitions; i++) { + let t = state.transition(i); + if (!(t instanceof RuleTransition_1.RuleTransition)) { + continue; + } + let ruleTransition = t; + let returningFromLeftFactored = atn.ruleToStartState[ruleTransition.target.ruleIndex].leftFactored; + if (!returningFromLeftFactored && returningToLeftFactored) { + continue; + } + let outermostPrecedenceReturn = -1; + if (atn.ruleToStartState[ruleTransition.target.ruleIndex].isPrecedenceRule) { + if (ruleTransition.precedence === 0) { + outermostPrecedenceReturn = ruleTransition.target.ruleIndex; + } + } + let current = { stopState: ruleTransition.target.ruleIndex, returnState: ruleTransition.followState.stateNumber, outermostPrecedenceReturn }; + if (returnTransitionsSet.add(current)) { + returnTransitions.push(current); + } + } + } + // Add all elements from returnTransitions to the ATN + for (let returnTransition of returnTransitions) { + let transition = new EpsilonTransition_1.EpsilonTransition(atn.states[returnTransition.returnState], returnTransition.outermostPrecedenceReturn); + atn.ruleToStopState[returnTransition.stopState].addTransition(transition); + } + for (let state of atn.states) { + if (state instanceof BlockStartState_1.BlockStartState) { + // we need to know the end state to set its start state + if (state.endState === undefined) { + throw new Error("IllegalStateException"); + } + // block end states can only be associated to a single block start state + if (state.endState.startState !== undefined) { + throw new Error("IllegalStateException"); + } + state.endState.startState = state; + } + if (state instanceof PlusLoopbackState_1.PlusLoopbackState) { + let loopbackState = state; + for (let i = 0; i < loopbackState.numberOfTransitions; i++) { + let target = loopbackState.transition(i).target; + if (target instanceof PlusBlockStartState_1.PlusBlockStartState) { + target.loopBackState = loopbackState; + } + } + } + else if (state instanceof StarLoopbackState_1.StarLoopbackState) { + let loopbackState = state; + for (let i = 0; i < loopbackState.numberOfTransitions; i++) { + let target = loopbackState.transition(i).target; + if (target instanceof StarLoopEntryState_1.StarLoopEntryState) { + target.loopBackState = loopbackState; + } + } + } + } + // + // DECISIONS + // + let ndecisions = ATNDeserializer.toInt(data[p++]); + for (let i = 1; i <= ndecisions; i++) { + let s = ATNDeserializer.toInt(data[p++]); + let decState = atn.states[s]; + atn.decisionToState.push(decState); + decState.decision = i - 1; + } + // + // LEXER ACTIONS + // + if (atn.grammarType === 0 /* LEXER */) { + if (supportsLexerActions) { + atn.lexerActions = new Array(ATNDeserializer.toInt(data[p++])); + for (let i = 0; i < atn.lexerActions.length; i++) { + let actionType = ATNDeserializer.toInt(data[p++]); + let data1 = ATNDeserializer.toInt(data[p++]); + if (data1 === 0xFFFF) { + data1 = -1; + } + let data2 = ATNDeserializer.toInt(data[p++]); + if (data2 === 0xFFFF) { + data2 = -1; + } + let lexerAction = this.lexerActionFactory(actionType, data1, data2); + atn.lexerActions[i] = lexerAction; + } + } + else { + // for compatibility with older serialized ATNs, convert the old + // serialized action index for action transitions to the new + // form, which is the index of a LexerCustomAction + let legacyLexerActions = []; + for (let state of atn.states) { + for (let i = 0; i < state.numberOfTransitions; i++) { + let transition = state.transition(i); + if (!(transition instanceof ActionTransition_1.ActionTransition)) { + continue; + } + let ruleIndex = transition.ruleIndex; + let actionIndex = transition.actionIndex; + let lexerAction = new LexerCustomAction_1.LexerCustomAction(ruleIndex, actionIndex); + state.setTransition(i, new ActionTransition_1.ActionTransition(transition.target, ruleIndex, legacyLexerActions.length, false)); + legacyLexerActions.push(lexerAction); + } + } + atn.lexerActions = legacyLexerActions; + } + } + this.markPrecedenceDecisions(atn); + atn.decisionToDFA = new Array(ndecisions); + for (let i = 0; i < ndecisions; i++) { + atn.decisionToDFA[i] = new DFA_1.DFA(atn.decisionToState[i], i); + } + if (this.deserializationOptions.isVerifyATN) { + this.verifyATN(atn); + } + if (this.deserializationOptions.isGenerateRuleBypassTransitions && atn.grammarType === 1 /* PARSER */) { + atn.ruleToTokenType = new Int32Array(atn.ruleToStartState.length); + for (let i = 0; i < atn.ruleToStartState.length; i++) { + atn.ruleToTokenType[i] = atn.maxTokenType + i + 1; + } + for (let i = 0; i < atn.ruleToStartState.length; i++) { + let bypassStart = new BasicBlockStartState_1.BasicBlockStartState(); + bypassStart.ruleIndex = i; + atn.addState(bypassStart); + let bypassStop = new BlockEndState_1.BlockEndState(); + bypassStop.ruleIndex = i; + atn.addState(bypassStop); + bypassStart.endState = bypassStop; + atn.defineDecisionState(bypassStart); + bypassStop.startState = bypassStart; + let endState; + let excludeTransition; + if (atn.ruleToStartState[i].isPrecedenceRule) { + // wrap from the beginning of the rule to the StarLoopEntryState + endState = undefined; + for (let state of atn.states) { + if (state.ruleIndex !== i) { + continue; + } + if (!(state instanceof StarLoopEntryState_1.StarLoopEntryState)) { + continue; + } + let maybeLoopEndState = state.transition(state.numberOfTransitions - 1).target; + if (!(maybeLoopEndState instanceof LoopEndState_1.LoopEndState)) { + continue; + } + if (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target instanceof RuleStopState_1.RuleStopState) { + endState = state; + break; + } + } + if (!endState) { + throw new Error("Couldn't identify final state of the precedence rule prefix section."); + } + excludeTransition = endState.loopBackState.transition(0); + } + else { + endState = atn.ruleToStopState[i]; + } + // all non-excluded transitions that currently target end state need to target blockEnd instead + for (let state of atn.states) { + for (let i = 0; i < state.numberOfTransitions; i++) { + let transition = state.transition(i); + if (transition === excludeTransition) { + continue; + } + if (transition.target === endState) { + transition.target = bypassStop; + } + } + } + // all transitions leaving the rule start state need to leave blockStart instead + while (atn.ruleToStartState[i].numberOfTransitions > 0) { + let transition = atn.ruleToStartState[i].removeTransition(atn.ruleToStartState[i].numberOfTransitions - 1); + bypassStart.addTransition(transition); + } + // link the new states + atn.ruleToStartState[i].addTransition(new EpsilonTransition_1.EpsilonTransition(bypassStart)); + bypassStop.addTransition(new EpsilonTransition_1.EpsilonTransition(endState)); + let matchState = new BasicState_1.BasicState(); + atn.addState(matchState); + matchState.addTransition(new AtomTransition_1.AtomTransition(bypassStop, atn.ruleToTokenType[i])); + bypassStart.addTransition(new EpsilonTransition_1.EpsilonTransition(matchState)); + } + if (this.deserializationOptions.isVerifyATN) { + // reverify after modification + this.verifyATN(atn); + } + } + if (this.deserializationOptions.isOptimize) { + while (true) { + let optimizationCount = 0; + optimizationCount += ATNDeserializer.inlineSetRules(atn); + optimizationCount += ATNDeserializer.combineChainedEpsilons(atn); + let preserveOrder = atn.grammarType === 0 /* LEXER */; + optimizationCount += ATNDeserializer.optimizeSets(atn, preserveOrder); + if (optimizationCount === 0) { + break; + } + } + if (this.deserializationOptions.isVerifyATN) { + // reverify after modification + this.verifyATN(atn); + } + } + ATNDeserializer.identifyTailCalls(atn); + return atn; + } + deserializeSets(data, p, sets, unicodeDeserializer) { + let nsets = ATNDeserializer.toInt(data[p++]); + for (let i = 0; i < nsets; i++) { + let nintervals = ATNDeserializer.toInt(data[p]); + p++; + let set = new IntervalSet_1.IntervalSet(); + sets.push(set); + let containsEof = ATNDeserializer.toInt(data[p++]) !== 0; + if (containsEof) { + set.add(-1); + } + for (let j = 0; j < nintervals; j++) { + let a = unicodeDeserializer.readUnicode(data, p); + p += unicodeDeserializer.size; + let b = unicodeDeserializer.readUnicode(data, p); + p += unicodeDeserializer.size; + set.add(a, b); + } + } + return p; + } + /** + * Analyze the {@link StarLoopEntryState} states in the specified ATN to set + * the {@link StarLoopEntryState#precedenceRuleDecision} field to the + * correct value. + * + * @param atn The ATN. + */ + markPrecedenceDecisions(atn) { + // Map rule index -> precedence decision for that rule + let rulePrecedenceDecisions = new Map(); + for (let state of atn.states) { + if (!(state instanceof StarLoopEntryState_1.StarLoopEntryState)) { + continue; + } + /* We analyze the ATN to determine if this ATN decision state is the + * decision for the closure block that determines whether a + * precedence rule should continue or complete. + */ + if (atn.ruleToStartState[state.ruleIndex].isPrecedenceRule) { + let maybeLoopEndState = state.transition(state.numberOfTransitions - 1).target; + if (maybeLoopEndState instanceof LoopEndState_1.LoopEndState) { + if (maybeLoopEndState.epsilonOnlyTransitions && maybeLoopEndState.transition(0).target instanceof RuleStopState_1.RuleStopState) { + rulePrecedenceDecisions.set(state.ruleIndex, state); + state.precedenceRuleDecision = true; + state.precedenceLoopbackStates = new BitSet_1.BitSet(atn.states.length); + } + } + } + } + // After marking precedence decisions, we go back through and fill in + // StarLoopEntryState.precedenceLoopbackStates. + for (let precedenceDecision of rulePrecedenceDecisions) { + for (let transition of atn.ruleToStopState[precedenceDecision[0]].getTransitions()) { + if (transition.serializationType !== 1 /* EPSILON */) { + continue; + } + let epsilonTransition = transition; + if (epsilonTransition.outermostPrecedenceReturn !== -1) { + continue; + } + precedenceDecision[1].precedenceLoopbackStates.set(transition.target.stateNumber); + } + } + } + verifyATN(atn) { + // verify assumptions + for (let state of atn.states) { + this.checkCondition(state !== undefined, "ATN states should not be undefined."); + if (state.stateType === ATNStateType_1.ATNStateType.INVALID_TYPE) { + continue; + } + this.checkCondition(state.onlyHasEpsilonTransitions || state.numberOfTransitions <= 1); + if (state instanceof PlusBlockStartState_1.PlusBlockStartState) { + this.checkCondition(state.loopBackState !== undefined); + } + if (state instanceof StarLoopEntryState_1.StarLoopEntryState) { + let starLoopEntryState = state; + this.checkCondition(starLoopEntryState.loopBackState !== undefined); + this.checkCondition(starLoopEntryState.numberOfTransitions === 2); + if (starLoopEntryState.transition(0).target instanceof StarBlockStartState_1.StarBlockStartState) { + this.checkCondition(starLoopEntryState.transition(1).target instanceof LoopEndState_1.LoopEndState); + this.checkCondition(!starLoopEntryState.nonGreedy); + } + else if (starLoopEntryState.transition(0).target instanceof LoopEndState_1.LoopEndState) { + this.checkCondition(starLoopEntryState.transition(1).target instanceof StarBlockStartState_1.StarBlockStartState); + this.checkCondition(starLoopEntryState.nonGreedy); + } + else { + throw new Error("IllegalStateException"); + } + } + if (state instanceof StarLoopbackState_1.StarLoopbackState) { + this.checkCondition(state.numberOfTransitions === 1); + this.checkCondition(state.transition(0).target instanceof StarLoopEntryState_1.StarLoopEntryState); + } + if (state instanceof LoopEndState_1.LoopEndState) { + this.checkCondition(state.loopBackState !== undefined); + } + if (state instanceof RuleStartState_1.RuleStartState) { + this.checkCondition(state.stopState !== undefined); + } + if (state instanceof BlockStartState_1.BlockStartState) { + this.checkCondition(state.endState !== undefined); + } + if (state instanceof BlockEndState_1.BlockEndState) { + this.checkCondition(state.startState !== undefined); + } + if (state instanceof DecisionState_1.DecisionState) { + let decisionState = state; + this.checkCondition(decisionState.numberOfTransitions <= 1 || decisionState.decision >= 0); + } + else { + this.checkCondition(state.numberOfTransitions <= 1 || state instanceof RuleStopState_1.RuleStopState); + } + } + } + checkCondition(condition, message) { + if (!condition) { + throw new Error("IllegalStateException: " + message); + } + } + static inlineSetRules(atn) { + let inlinedCalls = 0; + let ruleToInlineTransition = new Array(atn.ruleToStartState.length); + for (let i = 0; i < atn.ruleToStartState.length; i++) { + let startState = atn.ruleToStartState[i]; + let middleState = startState; + while (middleState.onlyHasEpsilonTransitions + && middleState.numberOfOptimizedTransitions === 1 + && middleState.getOptimizedTransition(0).serializationType === 1 /* EPSILON */) { + middleState = middleState.getOptimizedTransition(0).target; + } + if (middleState.numberOfOptimizedTransitions !== 1) { + continue; + } + let matchTransition = middleState.getOptimizedTransition(0); + let matchTarget = matchTransition.target; + if (matchTransition.isEpsilon + || !matchTarget.onlyHasEpsilonTransitions + || matchTarget.numberOfOptimizedTransitions !== 1 + || !(matchTarget.getOptimizedTransition(0).target instanceof RuleStopState_1.RuleStopState)) { + continue; + } + switch (matchTransition.serializationType) { + case 5 /* ATOM */: + case 2 /* RANGE */: + case 7 /* SET */: + ruleToInlineTransition[i] = matchTransition; + break; + case 8 /* NOT_SET */: + case 9 /* WILDCARD */: + // not implemented yet + continue; + default: + continue; + } + } + for (let state of atn.states) { + if (state.ruleIndex < 0) { + continue; + } + let optimizedTransitions; + for (let i = 0; i < state.numberOfOptimizedTransitions; i++) { + let transition = state.getOptimizedTransition(i); + if (!(transition instanceof RuleTransition_1.RuleTransition)) { + if (optimizedTransitions !== undefined) { + optimizedTransitions.push(transition); + } + continue; + } + let ruleTransition = transition; + let effective = ruleToInlineTransition[ruleTransition.target.ruleIndex]; + if (effective === undefined) { + if (optimizedTransitions !== undefined) { + optimizedTransitions.push(transition); + } + continue; + } + if (optimizedTransitions === undefined) { + optimizedTransitions = []; + for (let j = 0; j < i; j++) { + optimizedTransitions.push(state.getOptimizedTransition(i)); + } + } + inlinedCalls++; + let target = ruleTransition.followState; + let intermediateState = new BasicState_1.BasicState(); + intermediateState.setRuleIndex(target.ruleIndex); + atn.addState(intermediateState); + optimizedTransitions.push(new EpsilonTransition_1.EpsilonTransition(intermediateState)); + switch (effective.serializationType) { + case 5 /* ATOM */: + intermediateState.addTransition(new AtomTransition_1.AtomTransition(target, effective._label)); + break; + case 2 /* RANGE */: + intermediateState.addTransition(new RangeTransition_1.RangeTransition(target, effective.from, effective.to)); + break; + case 7 /* SET */: + intermediateState.addTransition(new SetTransition_1.SetTransition(target, effective.label)); + break; + default: + throw new Error("UnsupportedOperationException"); + } + } + if (optimizedTransitions !== undefined) { + if (state.isOptimized) { + while (state.numberOfOptimizedTransitions > 0) { + state.removeOptimizedTransition(state.numberOfOptimizedTransitions - 1); + } + } + for (let transition of optimizedTransitions) { + state.addOptimizedTransition(transition); + } + } + } + if (ParserATNSimulator_1.ParserATNSimulator.debug) { + console.log("ATN runtime optimizer removed " + inlinedCalls + " rule invocations by inlining sets."); + } + return inlinedCalls; + } + static combineChainedEpsilons(atn) { + let removedEdges = 0; + for (let state of atn.states) { + if (!state.onlyHasEpsilonTransitions || state instanceof RuleStopState_1.RuleStopState) { + continue; + } + let optimizedTransitions; + nextTransition: for (let i = 0; i < state.numberOfOptimizedTransitions; i++) { + let transition = state.getOptimizedTransition(i); + let intermediate = transition.target; + if (transition.serializationType !== 1 /* EPSILON */ + || transition.outermostPrecedenceReturn !== -1 + || intermediate.stateType !== ATNStateType_1.ATNStateType.BASIC + || !intermediate.onlyHasEpsilonTransitions) { + if (optimizedTransitions !== undefined) { + optimizedTransitions.push(transition); + } + continue nextTransition; + } + for (let j = 0; j < intermediate.numberOfOptimizedTransitions; j++) { + if (intermediate.getOptimizedTransition(j).serializationType !== 1 /* EPSILON */ + || intermediate.getOptimizedTransition(j).outermostPrecedenceReturn !== -1) { + if (optimizedTransitions !== undefined) { + optimizedTransitions.push(transition); + } + continue nextTransition; + } + } + removedEdges++; + if (optimizedTransitions === undefined) { + optimizedTransitions = []; + for (let j = 0; j < i; j++) { + optimizedTransitions.push(state.getOptimizedTransition(j)); + } + } + for (let j = 0; j < intermediate.numberOfOptimizedTransitions; j++) { + let target = intermediate.getOptimizedTransition(j).target; + optimizedTransitions.push(new EpsilonTransition_1.EpsilonTransition(target)); + } + } + if (optimizedTransitions !== undefined) { + if (state.isOptimized) { + while (state.numberOfOptimizedTransitions > 0) { + state.removeOptimizedTransition(state.numberOfOptimizedTransitions - 1); + } + } + for (let transition of optimizedTransitions) { + state.addOptimizedTransition(transition); + } + } + } + if (ParserATNSimulator_1.ParserATNSimulator.debug) { + console.log("ATN runtime optimizer removed " + removedEdges + " transitions by combining chained epsilon transitions."); + } + return removedEdges; + } + static optimizeSets(atn, preserveOrder) { + if (preserveOrder) { + // this optimization currently doesn't preserve edge order. + return 0; + } + let removedPaths = 0; + let decisions = atn.decisionToState; + for (let decision of decisions) { + let setTransitions = new IntervalSet_1.IntervalSet(); + for (let i = 0; i < decision.numberOfOptimizedTransitions; i++) { + let epsTransition = decision.getOptimizedTransition(i); + if (!(epsTransition instanceof EpsilonTransition_1.EpsilonTransition)) { + continue; + } + if (epsTransition.target.numberOfOptimizedTransitions !== 1) { + continue; + } + let transition = epsTransition.target.getOptimizedTransition(0); + if (!(transition.target instanceof BlockEndState_1.BlockEndState)) { + continue; + } + if (transition instanceof NotSetTransition_1.NotSetTransition) { + // TODO: not yet implemented + continue; + } + if (transition instanceof AtomTransition_1.AtomTransition + || transition instanceof RangeTransition_1.RangeTransition + || transition instanceof SetTransition_1.SetTransition) { + setTransitions.add(i); + } + } + if (setTransitions.size <= 1) { + continue; + } + let optimizedTransitions = []; + for (let i = 0; i < decision.numberOfOptimizedTransitions; i++) { + if (!setTransitions.contains(i)) { + optimizedTransitions.push(decision.getOptimizedTransition(i)); + } + } + let blockEndState = decision.getOptimizedTransition(setTransitions.minElement).target.getOptimizedTransition(0).target; + let matchSet = new IntervalSet_1.IntervalSet(); + for (let interval of setTransitions.intervals) { + for (let j = interval.a; j <= interval.b; j++) { + let matchTransition = decision.getOptimizedTransition(j).target.getOptimizedTransition(0); + if (matchTransition instanceof NotSetTransition_1.NotSetTransition) { + throw new Error("Not yet implemented."); + } + else { + matchSet.addAll(matchTransition.label); + } + } + } + let newTransition; + if (matchSet.intervals.length === 1) { + if (matchSet.size === 1) { + newTransition = new AtomTransition_1.AtomTransition(blockEndState, matchSet.minElement); + } + else { + let matchInterval = matchSet.intervals[0]; + newTransition = new RangeTransition_1.RangeTransition(blockEndState, matchInterval.a, matchInterval.b); + } + } + else { + newTransition = new SetTransition_1.SetTransition(blockEndState, matchSet); + } + let setOptimizedState = new BasicState_1.BasicState(); + setOptimizedState.setRuleIndex(decision.ruleIndex); + atn.addState(setOptimizedState); + setOptimizedState.addTransition(newTransition); + optimizedTransitions.push(new EpsilonTransition_1.EpsilonTransition(setOptimizedState)); + removedPaths += decision.numberOfOptimizedTransitions - optimizedTransitions.length; + if (decision.isOptimized) { + while (decision.numberOfOptimizedTransitions > 0) { + decision.removeOptimizedTransition(decision.numberOfOptimizedTransitions - 1); + } + } + for (let transition of optimizedTransitions) { + decision.addOptimizedTransition(transition); + } + } + if (ParserATNSimulator_1.ParserATNSimulator.debug) { + console.log("ATN runtime optimizer removed " + removedPaths + " paths by collapsing sets."); + } + return removedPaths; + } + static identifyTailCalls(atn) { + for (let state of atn.states) { + for (let i = 0; i < state.numberOfTransitions; i++) { + let transition = state.transition(i); + if (!(transition instanceof RuleTransition_1.RuleTransition)) { + continue; + } + transition.tailCall = this.testTailCall(atn, transition, false); + transition.optimizedTailCall = this.testTailCall(atn, transition, true); + } + if (!state.isOptimized) { + continue; + } + for (let i = 0; i < state.numberOfOptimizedTransitions; i++) { + let transition = state.getOptimizedTransition(i); + if (!(transition instanceof RuleTransition_1.RuleTransition)) { + continue; + } + transition.tailCall = this.testTailCall(atn, transition, false); + transition.optimizedTailCall = this.testTailCall(atn, transition, true); + } + } + } + static testTailCall(atn, transition, optimizedPath) { + if (!optimizedPath && transition.tailCall) { + return true; + } + if (optimizedPath && transition.optimizedTailCall) { + return true; + } + let reachable = new BitSet_1.BitSet(atn.states.length); + let worklist = []; + worklist.push(transition.followState); + while (true) { + let state = worklist.pop(); + if (!state) { + break; + } + if (reachable.get(state.stateNumber)) { + continue; + } + if (state instanceof RuleStopState_1.RuleStopState) { + continue; + } + if (!state.onlyHasEpsilonTransitions) { + return false; + } + let transitionCount = optimizedPath ? state.numberOfOptimizedTransitions : state.numberOfTransitions; + for (let i = 0; i < transitionCount; i++) { + let t = optimizedPath ? state.getOptimizedTransition(i) : state.transition(i); + if (t.serializationType !== 1 /* EPSILON */) { + return false; + } + worklist.push(t.target); + } + } + return true; + } + static toInt(c) { + return c; + } + static toInt32(data, offset) { + return (data[offset] | (data[offset + 1] << 16)) >>> 0; + } + static toUUID(data, offset) { + let leastSigBits = ATNDeserializer.toInt32(data, offset); + let lessSigBits = ATNDeserializer.toInt32(data, offset + 2); + let moreSigBits = ATNDeserializer.toInt32(data, offset + 4); + let mostSigBits = ATNDeserializer.toInt32(data, offset + 6); + return new UUID_1.UUID(mostSigBits, moreSigBits, lessSigBits, leastSigBits); + } + edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets) { + let target = atn.states[trg]; + switch (type) { + case 1 /* EPSILON */: return new EpsilonTransition_1.EpsilonTransition(target); + case 2 /* RANGE */: + if (arg3 !== 0) { + return new RangeTransition_1.RangeTransition(target, Token_1.Token.EOF, arg2); + } + else { + return new RangeTransition_1.RangeTransition(target, arg1, arg2); + } + case 3 /* RULE */: + let rt = new RuleTransition_1.RuleTransition(atn.states[arg1], arg2, arg3, target); + return rt; + case 4 /* PREDICATE */: + let pt = new PredicateTransition_1.PredicateTransition(target, arg1, arg2, arg3 !== 0); + return pt; + case 10 /* PRECEDENCE */: + return new PrecedencePredicateTransition_1.PrecedencePredicateTransition(target, arg1); + case 5 /* ATOM */: + if (arg3 !== 0) { + return new AtomTransition_1.AtomTransition(target, Token_1.Token.EOF); + } + else { + return new AtomTransition_1.AtomTransition(target, arg1); + } + case 6 /* ACTION */: + let a = new ActionTransition_1.ActionTransition(target, arg1, arg2, arg3 !== 0); + return a; + case 7 /* SET */: return new SetTransition_1.SetTransition(target, sets[arg1]); + case 8 /* NOT_SET */: return new NotSetTransition_1.NotSetTransition(target, sets[arg1]); + case 9 /* WILDCARD */: return new WildcardTransition_1.WildcardTransition(target); + } + throw new Error("The specified transition type is not valid."); + } + stateFactory(type, ruleIndex) { + let s; + switch (type) { + case ATNStateType_1.ATNStateType.INVALID_TYPE: return new InvalidState_1.InvalidState(); + case ATNStateType_1.ATNStateType.BASIC: + s = new BasicState_1.BasicState(); + break; + case ATNStateType_1.ATNStateType.RULE_START: + s = new RuleStartState_1.RuleStartState(); + break; + case ATNStateType_1.ATNStateType.BLOCK_START: + s = new BasicBlockStartState_1.BasicBlockStartState(); + break; + case ATNStateType_1.ATNStateType.PLUS_BLOCK_START: + s = new PlusBlockStartState_1.PlusBlockStartState(); + break; + case ATNStateType_1.ATNStateType.STAR_BLOCK_START: + s = new StarBlockStartState_1.StarBlockStartState(); + break; + case ATNStateType_1.ATNStateType.TOKEN_START: + s = new TokensStartState_1.TokensStartState(); + break; + case ATNStateType_1.ATNStateType.RULE_STOP: + s = new RuleStopState_1.RuleStopState(); + break; + case ATNStateType_1.ATNStateType.BLOCK_END: + s = new BlockEndState_1.BlockEndState(); + break; + case ATNStateType_1.ATNStateType.STAR_LOOP_BACK: + s = new StarLoopbackState_1.StarLoopbackState(); + break; + case ATNStateType_1.ATNStateType.STAR_LOOP_ENTRY: + s = new StarLoopEntryState_1.StarLoopEntryState(); + break; + case ATNStateType_1.ATNStateType.PLUS_LOOP_BACK: + s = new PlusLoopbackState_1.PlusLoopbackState(); + break; + case ATNStateType_1.ATNStateType.LOOP_END: + s = new LoopEndState_1.LoopEndState(); + break; + default: + let message = `The specified state type ${type} is not valid.`; + throw new Error(message); + } + s.ruleIndex = ruleIndex; + return s; + } + lexerActionFactory(type, data1, data2) { + switch (type) { + case 0 /* CHANNEL */: + return new LexerChannelAction_1.LexerChannelAction(data1); + case 1 /* CUSTOM */: + return new LexerCustomAction_1.LexerCustomAction(data1, data2); + case 2 /* MODE */: + return new LexerModeAction_1.LexerModeAction(data1); + case 3 /* MORE */: + return LexerMoreAction_1.LexerMoreAction.INSTANCE; + case 4 /* POP_MODE */: + return LexerPopModeAction_1.LexerPopModeAction.INSTANCE; + case 5 /* PUSH_MODE */: + return new LexerPushModeAction_1.LexerPushModeAction(data1); + case 6 /* SKIP */: + return LexerSkipAction_1.LexerSkipAction.INSTANCE; + case 7 /* TYPE */: + return new LexerTypeAction_1.LexerTypeAction(data1); + default: + let message = `The specified lexer action type ${type} is not valid.`; + throw new Error(message); + } + } + }; + /* WARNING: DO NOT MERGE THESE LINES. If UUIDs differ during a merge, + * resolve the conflict by generating a new ID! + */ + /** + * This is the earliest supported serialized UUID. + */ + ATNDeserializer$1.BASE_SERIALIZED_UUID = UUID_1.UUID.fromString("E4178468-DF95-44D0-AD87-F22A5D5FB6D3"); + /** + * This UUID indicates an extension of {@link #ADDED_PRECEDENCE_TRANSITIONS} + * for the addition of lexer actions encoded as a sequence of + * {@link LexerAction} instances. + */ + ATNDeserializer$1.ADDED_LEXER_ACTIONS = UUID_1.UUID.fromString("AB35191A-1603-487E-B75A-479B831EAF6D"); + /** + * This UUID indicates the serialized ATN contains two sets of + * IntervalSets, where the second set's values are encoded as + * 32-bit integers to support the full Unicode SMP range up to U+10FFFF. + */ + ATNDeserializer$1.ADDED_UNICODE_SMP = UUID_1.UUID.fromString("C23FEA89-0605-4f51-AFB8-058BCAB8C91B"); + /** + * This list contains all of the currently supported UUIDs, ordered by when + * the feature first appeared in this branch. + */ + ATNDeserializer$1.SUPPORTED_UUIDS = [ + ATNDeserializer$1.BASE_SERIALIZED_UUID, + ATNDeserializer$1.ADDED_LEXER_ACTIONS, + ATNDeserializer$1.ADDED_UNICODE_SMP, + ]; + /** + * This is the current serialized UUID. + */ + ATNDeserializer$1.SERIALIZED_UUID = ATNDeserializer$1.ADDED_UNICODE_SMP; + __decorate([ + Decorators_1.NotNull + ], ATNDeserializer$1.prototype, "deserializationOptions", void 0); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ATNDeserializer$1.prototype, "deserialize", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ATNDeserializer$1.prototype, "markPrecedenceDecisions", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ATNDeserializer$1.prototype, "edgeFactory", null); + ATNDeserializer.ATNDeserializer = ATNDeserializer$1; + + return ATNDeserializer; +} + +var ParseInfo = {}; + +var hasRequiredParseInfo; + +function requireParseInfo () { + if (hasRequiredParseInfo) return ParseInfo; + hasRequiredParseInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParseInfo && ParseInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParseInfo && ParseInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ParseInfo, "__esModule", { value: true }); + ParseInfo.ParseInfo = void 0; + const Decorators_1 = requireDecorators(); + /** + * This class provides access to specific and aggregate statistics gathered + * during profiling of a parser. + * + * @since 4.3 + */ + let ParseInfo$1 = class ParseInfo { + constructor(atnSimulator) { + this.atnSimulator = atnSimulator; + } + /** + * Gets an array of {@link DecisionInfo} instances containing the profiling + * information gathered for each decision in the ATN. + * + * @returns An array of {@link DecisionInfo} instances, indexed by decision + * number. + */ + getDecisionInfo() { + return this.atnSimulator.getDecisionInfo(); + } + /** + * Gets the decision numbers for decisions that required one or more + * full-context predictions during parsing. These are decisions for which + * {@link DecisionInfo#LL_Fallback} is non-zero. + * + * @returns A list of decision numbers which required one or more + * full-context predictions during parsing. + */ + getLLDecisions() { + let decisions = this.atnSimulator.getDecisionInfo(); + let LL = []; + for (let i = 0; i < decisions.length; i++) { + let fallBack = decisions[i].LL_Fallback; + if (fallBack > 0) { + LL.push(i); + } + } + return LL; + } + /** + * Gets the total time spent during prediction across all decisions made + * during parsing. This value is the sum of + * {@link DecisionInfo#timeInPrediction} for all decisions. + */ + getTotalTimeInPrediction() { + let decisions = this.atnSimulator.getDecisionInfo(); + let t = 0; + for (let decision of decisions) { + t += decision.timeInPrediction; + } + return t; + } + /** + * Gets the total number of SLL lookahead operations across all decisions + * made during parsing. This value is the sum of + * {@link DecisionInfo#SLL_TotalLook} for all decisions. + */ + getTotalSLLLookaheadOps() { + let decisions = this.atnSimulator.getDecisionInfo(); + let k = 0; + for (let decision of decisions) { + k += decision.SLL_TotalLook; + } + return k; + } + /** + * Gets the total number of LL lookahead operations across all decisions + * made during parsing. This value is the sum of + * {@link DecisionInfo#LL_TotalLook} for all decisions. + */ + getTotalLLLookaheadOps() { + let decisions = this.atnSimulator.getDecisionInfo(); + let k = 0; + for (let decision of decisions) { + k += decision.LL_TotalLook; + } + return k; + } + /** + * Gets the total number of ATN lookahead operations for SLL prediction + * across all decisions made during parsing. + */ + getTotalSLLATNLookaheadOps() { + let decisions = this.atnSimulator.getDecisionInfo(); + let k = 0; + for (let decision of decisions) { + k += decision.SLL_ATNTransitions; + } + return k; + } + /** + * Gets the total number of ATN lookahead operations for LL prediction + * across all decisions made during parsing. + */ + getTotalLLATNLookaheadOps() { + let decisions = this.atnSimulator.getDecisionInfo(); + let k = 0; + for (let decision of decisions) { + k += decision.LL_ATNTransitions; + } + return k; + } + /** + * Gets the total number of ATN lookahead operations for SLL and LL + * prediction across all decisions made during parsing. + * + * This value is the sum of {@link #getTotalSLLATNLookaheadOps} and + * {@link #getTotalLLATNLookaheadOps}. + */ + getTotalATNLookaheadOps() { + let decisions = this.atnSimulator.getDecisionInfo(); + let k = 0; + for (let decision of decisions) { + k += decision.SLL_ATNTransitions; + k += decision.LL_ATNTransitions; + } + return k; + } + getDFASize(decision) { + if (decision) { + let decisionToDFA = this.atnSimulator.atn.decisionToDFA[decision]; + return decisionToDFA.states.size; + } + else { + let n = 0; + let decisionToDFA = this.atnSimulator.atn.decisionToDFA; + for (let i = 0; i < decisionToDFA.length; i++) { + n += this.getDFASize(i); + } + return n; + } + } + }; + __decorate([ + Decorators_1.NotNull + ], ParseInfo$1.prototype, "getDecisionInfo", null); + __decorate([ + Decorators_1.NotNull + ], ParseInfo$1.prototype, "getLLDecisions", null); + ParseInfo$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ParseInfo$1); + ParseInfo.ParseInfo = ParseInfo$1; + + return ParseInfo; +} + +var ProxyParserErrorListener = {}; + +var hasRequiredProxyParserErrorListener; + +function requireProxyParserErrorListener () { + if (hasRequiredProxyParserErrorListener) return ProxyParserErrorListener; + hasRequiredProxyParserErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ProxyParserErrorListener && ProxyParserErrorListener.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(ProxyParserErrorListener, "__esModule", { value: true }); + ProxyParserErrorListener.ProxyParserErrorListener = void 0; + const ProxyErrorListener_1 = requireProxyErrorListener(); + const Decorators_1 = requireDecorators(); + /** + * @author Sam Harwell + */ + let ProxyParserErrorListener$1 = class ProxyParserErrorListener extends ProxyErrorListener_1.ProxyErrorListener { + constructor(delegates) { + super(delegates); + } + reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) { + this.getDelegates() + .forEach((listener) => { + if (listener.reportAmbiguity) { + listener.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs); + } + }); + } + reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, conflictState) { + this.getDelegates() + .forEach((listener) => { + if (listener.reportAttemptingFullContext) { + listener.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, conflictState); + } + }); + } + reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, acceptState) { + this.getDelegates() + .forEach((listener) => { + if (listener.reportContextSensitivity) { + listener.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, acceptState); + } + }); + } + }; + __decorate([ + Decorators_1.Override + ], ProxyParserErrorListener$1.prototype, "reportAmbiguity", null); + __decorate([ + Decorators_1.Override + ], ProxyParserErrorListener$1.prototype, "reportAttemptingFullContext", null); + __decorate([ + Decorators_1.Override + ], ProxyParserErrorListener$1.prototype, "reportContextSensitivity", null); + ProxyParserErrorListener.ProxyParserErrorListener = ProxyParserErrorListener$1; + + return ProxyParserErrorListener; +} + +var ParseTreePatternMatcher = {}; + +var CharStreams = {}; + +var CodePointBuffer = {}; + +var Character = {}; + +var hasRequiredCharacter; + +function requireCharacter () { + if (hasRequiredCharacter) return Character; + hasRequiredCharacter = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Character, "__esModule", { value: true }); + Character.isSupplementaryCodePoint = Character.isLowSurrogate = Character.isHighSurrogate = void 0; + function isHighSurrogate(ch) { + return ch >= 0xD800 && ch <= 0xDBFF; + } + Character.isHighSurrogate = isHighSurrogate; + function isLowSurrogate(ch) { + return ch >= 0xDC00 && ch <= 0xDFFF; + } + Character.isLowSurrogate = isLowSurrogate; + function isSupplementaryCodePoint(ch) { + return ch >= 0x10000; + } + Character.isSupplementaryCodePoint = isSupplementaryCodePoint; + + return Character; +} + +var hasRequiredCodePointBuffer; + +function requireCodePointBuffer () { + if (hasRequiredCodePointBuffer) return CodePointBuffer; + hasRequiredCodePointBuffer = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodePointBuffer = void 0; + const assert = require$$0$9; + const Character = requireCharacter(); + /** + * Wrapper for `Uint8Array` / `Uint16Array` / `Int32Array`. + */ + class CodePointBuffer { + constructor(buffer, size) { + this.buffer = buffer; + this._position = 0; + this._size = size; + } + static withArray(buffer) { + return new CodePointBuffer(buffer, buffer.length); + } + get position() { + return this._position; + } + set position(newPosition) { + if (newPosition < 0 || newPosition > this._size) { + throw new RangeError(); + } + this._position = newPosition; + } + get remaining() { + return this._size - this.position; + } + get(offset) { + return this.buffer[offset]; + } + array() { + return this.buffer.slice(0, this._size); + } + static builder(initialBufferSize) { + return new CodePointBuffer.Builder(initialBufferSize); + } + } + exports.CodePointBuffer = CodePointBuffer; + (function (CodePointBuffer) { + let Type; + (function (Type) { + Type[Type["BYTE"] = 0] = "BYTE"; + Type[Type["CHAR"] = 1] = "CHAR"; + Type[Type["INT"] = 2] = "INT"; + })(Type || (Type = {})); + class Builder { + constructor(initialBufferSize) { + this.type = 0 /* BYTE */; + this.buffer = new Uint8Array(initialBufferSize); + this.prevHighSurrogate = -1; + this.position = 0; + } + build() { + return new CodePointBuffer(this.buffer, this.position); + } + static roundUpToNextPowerOfTwo(i) { + let nextPowerOfTwo = 32 - Math.clz32(i - 1); + return Math.pow(2, nextPowerOfTwo); + } + ensureRemaining(remainingNeeded) { + switch (this.type) { + case 0 /* BYTE */: + if (this.buffer.length - this.position < remainingNeeded) { + let newCapacity = Builder.roundUpToNextPowerOfTwo(this.buffer.length + remainingNeeded); + let newBuffer = new Uint8Array(newCapacity); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.buffer = newBuffer; + } + break; + case 1 /* CHAR */: + if (this.buffer.length - this.position < remainingNeeded) { + let newCapacity = Builder.roundUpToNextPowerOfTwo(this.buffer.length + remainingNeeded); + let newBuffer = new Uint16Array(newCapacity); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.buffer = newBuffer; + } + break; + case 2 /* INT */: + if (this.buffer.length - this.position < remainingNeeded) { + let newCapacity = Builder.roundUpToNextPowerOfTwo(this.buffer.length + remainingNeeded); + let newBuffer = new Int32Array(newCapacity); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.buffer = newBuffer; + } + break; + } + } + append(utf16In) { + this.ensureRemaining(utf16In.length); + this.appendArray(utf16In); + } + appendArray(utf16In) { + switch (this.type) { + case 0 /* BYTE */: + this.appendArrayByte(utf16In); + break; + case 1 /* CHAR */: + this.appendArrayChar(utf16In); + break; + case 2 /* INT */: + this.appendArrayInt(utf16In); + break; + } + } + appendArrayByte(utf16In) { + assert(this.prevHighSurrogate === -1); + let input = utf16In; + let inOffset = 0; + let inLimit = utf16In.length; + let outByte = this.buffer; + let outOffset = this.position; + while (inOffset < inLimit) { + let c = input[inOffset]; + if (c <= 0xFF) { + outByte[outOffset] = c; + } + else { + utf16In = utf16In.subarray(inOffset, inLimit); + this.position = outOffset; + if (!Character.isHighSurrogate(c)) { + this.byteToCharBuffer(utf16In.length); + this.appendArrayChar(utf16In); + return; + } + else { + this.byteToIntBuffer(utf16In.length); + this.appendArrayInt(utf16In); + return; + } + } + inOffset++; + outOffset++; + } + this.position = outOffset; + } + appendArrayChar(utf16In) { + assert(this.prevHighSurrogate === -1); + let input = utf16In; + let inOffset = 0; + let inLimit = utf16In.length; + let outChar = this.buffer; + let outOffset = this.position; + while (inOffset < inLimit) { + let c = input[inOffset]; + if (!Character.isHighSurrogate(c)) { + outChar[outOffset] = c; + } + else { + utf16In = utf16In.subarray(inOffset, inLimit); + this.position = outOffset; + this.charToIntBuffer(utf16In.length); + this.appendArrayInt(utf16In); + return; + } + inOffset++; + outOffset++; + } + this.position = outOffset; + } + appendArrayInt(utf16In) { + let input = utf16In; + let inOffset = 0; + let inLimit = utf16In.length; + let outInt = this.buffer; + let outOffset = this.position; + while (inOffset < inLimit) { + let c = input[inOffset]; + inOffset++; + if (this.prevHighSurrogate !== -1) { + if (Character.isLowSurrogate(c)) { + outInt[outOffset] = String.fromCharCode(this.prevHighSurrogate, c).codePointAt(0); + outOffset++; + this.prevHighSurrogate = -1; + } + else { + // Dangling high surrogate + outInt[outOffset] = this.prevHighSurrogate; + outOffset++; + if (Character.isHighSurrogate(c)) { + this.prevHighSurrogate = c; + } + else { + outInt[outOffset] = c; + outOffset++; + this.prevHighSurrogate = -1; + } + } + } + else if (Character.isHighSurrogate(c)) { + this.prevHighSurrogate = c; + } + else { + outInt[outOffset] = c; + outOffset++; + } + } + if (this.prevHighSurrogate !== -1) { + // Dangling high surrogate + outInt[outOffset] = this.prevHighSurrogate; + outOffset++; + } + this.position = outOffset; + } + byteToCharBuffer(toAppend) { + // CharBuffers hold twice as much per unit as ByteBuffers, so start with half the capacity. + let newBuffer = new Uint16Array(Math.max(this.position + toAppend, this.buffer.length >> 1)); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.type = 1 /* CHAR */; + this.buffer = newBuffer; + } + byteToIntBuffer(toAppend) { + // IntBuffers hold four times as much per unit as ByteBuffers, so start with one quarter the capacity. + let newBuffer = new Int32Array(Math.max(this.position + toAppend, this.buffer.length >> 2)); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.type = 2 /* INT */; + this.buffer = newBuffer; + } + charToIntBuffer(toAppend) { + // IntBuffers hold two times as much per unit as ByteBuffers, so start with one half the capacity. + let newBuffer = new Int32Array(Math.max(this.position + toAppend, this.buffer.length >> 1)); + newBuffer.set(this.buffer.subarray(0, this.position), 0); + this.type = 2 /* INT */; + this.buffer = newBuffer; + } + } + CodePointBuffer.Builder = Builder; + })(CodePointBuffer = exports.CodePointBuffer || (exports.CodePointBuffer = {})); + + } (CodePointBuffer)); + return CodePointBuffer; +} + +var CodePointCharStream = {}; + +var hasRequiredCodePointCharStream; + +function requireCodePointCharStream () { + if (hasRequiredCodePointCharStream) return CodePointCharStream; + hasRequiredCodePointCharStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (CodePointCharStream && CodePointCharStream.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(CodePointCharStream, "__esModule", { value: true }); + CodePointCharStream.CodePointCharStream = void 0; + const assert = require$$0$9; + const IntStream_1 = requireIntStream(); + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + /** + * Alternative to {@link ANTLRInputStream} which treats the input + * as a series of Unicode code points, instead of a series of UTF-16 + * code units. + * + * Use this if you need to parse input which potentially contains + * Unicode values > U+FFFF. + */ + let CodePointCharStream$1 = class CodePointCharStream { + // Use the factory method {@link #fromBuffer(CodePointBuffer)} to + // construct instances of this type. + constructor(array, position, remaining, name) { + // TODO + assert(position === 0); + this._array = array; + this._size = remaining; + this._name = name; + this._position = 0; + } + get internalStorage() { + return this._array; + } + static fromBuffer(codePointBuffer, name) { + if (name === undefined || name.length === 0) { + name = IntStream_1.IntStream.UNKNOWN_SOURCE_NAME; + } + // Java lacks generics on primitive types. + // + // To avoid lots of calls to virtual methods in the + // very hot codepath of LA() below, we construct one + // of three concrete subclasses. + // + // The concrete subclasses directly access the code + // points stored in the underlying array (byte[], + // char[], or int[]), so we can avoid lots of virtual + // method calls to ByteBuffer.get(offset). + return new CodePointCharStream(codePointBuffer.array(), codePointBuffer.position, codePointBuffer.remaining, name); + } + consume() { + if (this._size - this._position === 0) { + assert(this.LA(1) === IntStream_1.IntStream.EOF); + throw new RangeError("cannot consume EOF"); + } + this._position++; + } + get index() { + return this._position; + } + get size() { + return this._size; + } + /** mark/release do nothing; we have entire buffer */ + mark() { + return -1; + } + release(marker) { + // No default implementation since this stream buffers the entire input + } + seek(index) { + this._position = index; + } + get sourceName() { + return this._name; + } + toString() { + return this.getText(Interval_1.Interval.of(0, this.size - 1)); + } + LA(i) { + let offset; + switch (Math.sign(i)) { + case -1: + offset = this.index + i; + if (offset < 0) { + return IntStream_1.IntStream.EOF; + } + return this._array[offset]; + case 0: + // Undefined + return 0; + case 1: + offset = this.index + i - 1; + if (offset >= this.size) { + return IntStream_1.IntStream.EOF; + } + return this._array[offset]; + } + throw new RangeError("Not reached"); + } + /** Return the UTF-16 encoded string for the given interval */ + getText(interval) { + const startIdx = Math.min(interval.a, this.size); + const len = Math.min(interval.b - interval.a + 1, this.size - startIdx); + if (this._array instanceof Int32Array) { + return String.fromCodePoint(...Array.from(this._array.subarray(startIdx, startIdx + len))); + } + else { + return String.fromCharCode(...Array.from(this._array.subarray(startIdx, startIdx + len))); + } + } + }; + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "consume", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "index", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "mark", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "release", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "seek", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "sourceName", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "toString", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "LA", null); + __decorate([ + Decorators_1.Override + ], CodePointCharStream$1.prototype, "getText", null); + CodePointCharStream.CodePointCharStream = CodePointCharStream$1; + + return CodePointCharStream; +} + +var hasRequiredCharStreams; + +function requireCharStreams () { + if (hasRequiredCharStreams) return CharStreams; + hasRequiredCharStreams = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CharStreams = void 0; + const CodePointBuffer_1 = requireCodePointBuffer(); + const CodePointCharStream_1 = requireCodePointCharStream(); + const IntStream_1 = requireIntStream(); + (function (CharStreams) { + // /** + // * Creates a {@link CharStream} given a path to a UTF-8 + // * encoded file on disk. + // * + // * Reads the entire contents of the file into the result before returning. + // */ + // export function fromFile(file: File): CharStream; + // export function fromFile(file: File, charset: Charset): CharStream; + // export function fromFile(file: File, charset?: Charset): CharStream { + // if (charset === undefined) { + // charset = Charset.forName("UTF-8"); + // } + function fromString(s, sourceName) { + if (sourceName === undefined || sourceName.length === 0) { + sourceName = IntStream_1.IntStream.UNKNOWN_SOURCE_NAME; + } + // Initial guess assumes no code points > U+FFFF: one code + // point for each code unit in the string + let codePointBufferBuilder = CodePointBuffer_1.CodePointBuffer.builder(s.length); + // TODO: CharBuffer.wrap(String) rightfully returns a read-only buffer + // which doesn't expose its array, so we make a copy. + let cb = new Uint16Array(s.length); + for (let i = 0; i < s.length; i++) { + cb[i] = s.charCodeAt(i); + } + codePointBufferBuilder.append(cb); + return CodePointCharStream_1.CodePointCharStream.fromBuffer(codePointBufferBuilder.build(), sourceName); + } + CharStreams.fromString = fromString; + // export function bufferFromChannel( + // channel: ReadableByteChannel, + // charset: Charset, + // bufferSize: number, + // decodingErrorAction: CodingErrorAction, + // inputSize: number): CodePointBuffer { + // try { + // let utf8BytesIn: Uint8Array = new Uint8Array(bufferSize); + // let utf16CodeUnitsOut: Uint16Array = new Uint16Array(bufferSize); + // if (inputSize === -1) { + // inputSize = bufferSize; + // } else if (inputSize > Integer.MAX_VALUE) { + // // ByteBuffer et al don't support long sizes + // throw new RangeError(`inputSize ${inputSize} larger than max ${Integer.MAX_VALUE}`); + // } + // let codePointBufferBuilder: CodePointBuffer.Builder = CodePointBuffer.builder(inputSize); + // let decoder: CharsetDecoder = charset + // .newDecoder() + // .onMalformedInput(decodingErrorAction) + // .onUnmappableCharacter(decodingErrorAction); + // let endOfInput: boolean = false; + // while (!endOfInput) { + // let bytesRead: number = channel.read(utf8BytesIn); + // endOfInput = (bytesRead === -1); + // utf8BytesIn.flip(); + // let result: CoderResult = decoder.decode( + // utf8BytesIn, + // utf16CodeUnitsOut, + // endOfInput); + // if (result.isError() && decodingErrorAction === CodingErrorAction.REPORT) { + // result.throwException(); + // } + // utf16CodeUnitsOut.flip(); + // codePointBufferBuilder.append(utf16CodeUnitsOut); + // utf8BytesIn.compact(); + // utf16CodeUnitsOut.compact(); + // } + // // Handle any bytes at the end of the file which need to + // // be represented as errors or substitution characters. + // let flushResult: CoderResult = decoder.flush(utf16CodeUnitsOut); + // if (flushResult.isError() && decodingErrorAction === CodingErrorAction.REPORT) { + // flushResult.throwException(); + // } + // utf16CodeUnitsOut.flip(); + // codePointBufferBuilder.append(utf16CodeUnitsOut); + // return codePointBufferBuilder.build(); + // } + // finally { + // channel.close(); + // } + // } + })(exports.CharStreams || (exports.CharStreams = {})); + + } (CharStreams)); + return CharStreams; +} + +var CommonTokenStream = {}; + +var BufferedTokenStream = {}; + +var hasRequiredBufferedTokenStream; + +function requireBufferedTokenStream () { + if (hasRequiredBufferedTokenStream) return BufferedTokenStream; + hasRequiredBufferedTokenStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (BufferedTokenStream && BufferedTokenStream.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (BufferedTokenStream && BufferedTokenStream.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(BufferedTokenStream, "__esModule", { value: true }); + BufferedTokenStream.BufferedTokenStream = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:49.6074365-07:00 + const assert = require$$0$9; + const CommonToken_1 = requireCommonToken(); + const Interval_1 = requireInterval(); + const Lexer_1 = requireLexer(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * This implementation of {@link TokenStream} loads tokens from a + * {@link TokenSource} on-demand, and places the tokens in a buffer to provide + * access to any previous token by index. + * + * This token stream ignores the value of {@link Token#getChannel}. If your + * parser requires the token stream filter tokens to only those on a particular + * channel, such as {@link Token#DEFAULT_CHANNEL} or + * {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a + * {@link CommonTokenStream}. + */ + let BufferedTokenStream$1 = class BufferedTokenStream { + constructor(tokenSource) { + /** + * A collection of all tokens fetched from the token source. The list is + * considered a complete view of the input once {@link #fetchedEOF} is set + * to `true`. + */ + this.tokens = []; + /** + * The index into {@link #tokens} of the current token (next token to + * {@link #consume}). {@link #tokens}`[`{@link #p}`]` should be + * {@link #LT LT(1)}. + * + * This field is set to -1 when the stream is first constructed or when + * {@link #setTokenSource} is called, indicating that the first token has + * not yet been fetched from the token source. For additional information, + * see the documentation of {@link IntStream} for a description of + * Initializing Methods. + */ + this.p = -1; + /** + * Indicates whether the {@link Token#EOF} token has been fetched from + * {@link #tokenSource} and added to {@link #tokens}. This field improves + * performance for the following cases: + * + * * {@link #consume}: The lookahead check in {@link #consume} to prevent + * consuming the EOF symbol is optimized by checking the values of + * {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}. + * * {@link #fetch}: The check to prevent adding multiple EOF symbols into + * {@link #tokens} is trivial with this field. + */ + this.fetchedEOF = false; + if (tokenSource == null) { + throw new Error("tokenSource cannot be null"); + } + this._tokenSource = tokenSource; + } + get tokenSource() { + return this._tokenSource; + } + /** Reset this token stream by setting its token source. */ + set tokenSource(tokenSource) { + this._tokenSource = tokenSource; + this.tokens.length = 0; + this.p = -1; + this.fetchedEOF = false; + } + get index() { + return this.p; + } + mark() { + return 0; + } + release(marker) { + // no resources to release + } + seek(index) { + this.lazyInit(); + this.p = this.adjustSeekIndex(index); + } + get size() { + return this.tokens.length; + } + consume() { + let skipEofCheck; + if (this.p >= 0) { + if (this.fetchedEOF) { + // the last token in tokens is EOF. skip check if p indexes any + // fetched token except the last. + skipEofCheck = this.p < this.tokens.length - 1; + } + else { + // no EOF token in tokens. skip check if p indexes a fetched token. + skipEofCheck = this.p < this.tokens.length; + } + } + else { + // not yet initialized + skipEofCheck = false; + } + if (!skipEofCheck && this.LA(1) === Token_1.Token.EOF) { + throw new Error("cannot consume EOF"); + } + if (this.sync(this.p + 1)) { + this.p = this.adjustSeekIndex(this.p + 1); + } + } + /** Make sure index `i` in tokens has a token. + * + * @returns `true` if a token is located at index `i`, otherwise + * `false`. + * @see #get(int i) + */ + sync(i) { + assert(i >= 0); + let n = i - this.tokens.length + 1; // how many more elements we need? + //System.out.println("sync("+i+") needs "+n); + if (n > 0) { + let fetched = this.fetch(n); + return fetched >= n; + } + return true; + } + /** Add `n` elements to buffer. + * + * @returns The actual number of elements added to the buffer. + */ + fetch(n) { + if (this.fetchedEOF) { + return 0; + } + for (let i = 0; i < n; i++) { + let t = this.tokenSource.nextToken(); + if (this.isWritableToken(t)) { + t.tokenIndex = this.tokens.length; + } + this.tokens.push(t); + if (t.type === Token_1.Token.EOF) { + this.fetchedEOF = true; + return i + 1; + } + } + return n; + } + get(i) { + if (i < 0 || i >= this.tokens.length) { + throw new RangeError("token index " + i + " out of range 0.." + (this.tokens.length - 1)); + } + return this.tokens[i]; + } + /** Get all tokens from start..stop inclusively. */ + getRange(start, stop) { + if (start < 0 || stop < 0) { + return []; + } + this.lazyInit(); + let subset = new Array(); + if (stop >= this.tokens.length) { + stop = this.tokens.length - 1; + } + for (let i = start; i <= stop; i++) { + let t = this.tokens[i]; + if (t.type === Token_1.Token.EOF) { + break; + } + subset.push(t); + } + return subset; + } + LA(i) { + let token = this.LT(i); + if (!token) { + return Token_1.Token.INVALID_TYPE; + } + return token.type; + } + tryLB(k) { + if ((this.p - k) < 0) { + return undefined; + } + return this.tokens[this.p - k]; + } + LT(k) { + let result = this.tryLT(k); + if (result === undefined) { + throw new RangeError("requested lookback index out of range"); + } + return result; + } + tryLT(k) { + this.lazyInit(); + if (k === 0) { + throw new RangeError("0 is not a valid lookahead index"); + } + if (k < 0) { + return this.tryLB(-k); + } + let i = this.p + k - 1; + this.sync(i); + if (i >= this.tokens.length) { + // return EOF token + // EOF must be last token + return this.tokens[this.tokens.length - 1]; + } + // if ( i>range ) range = i; + return this.tokens[i]; + } + /** + * Allowed derived classes to modify the behavior of operations which change + * the current stream position by adjusting the target token index of a seek + * operation. The default implementation simply returns `i`. If an + * exception is thrown in this method, the current stream index should not be + * changed. + * + * For example, {@link CommonTokenStream} overrides this method to ensure that + * the seek target is always an on-channel token. + * + * @param i The target token index. + * @returns The adjusted target token index. + */ + adjustSeekIndex(i) { + return i; + } + lazyInit() { + if (this.p === -1) { + this.setup(); + } + } + setup() { + this.sync(0); + this.p = this.adjustSeekIndex(0); + } + /** Given a start and stop index, return a `List` of all tokens in + * the token type `BitSet`. Return an empty array if no tokens were found. This + * method looks at both on and off channel tokens. + */ + getTokens(start, stop, types) { + this.lazyInit(); + if (start === undefined) { + assert(stop === undefined && types === undefined); + return this.tokens; + } + else if (stop === undefined) { + stop = this.tokens.length - 1; + } + if (start < 0 || stop >= this.tokens.length || stop < 0 || start >= this.tokens.length) { + throw new RangeError("start " + start + " or stop " + stop + " not in 0.." + (this.tokens.length - 1)); + } + if (start > stop) { + return []; + } + if (types === undefined) { + return this.tokens.slice(start, stop + 1); + } + else if (typeof types === "number") { + types = new Set().add(types); + } + let typesSet = types; + // list = tokens[start:stop]:{T t, t.type in types} + let filteredTokens = this.tokens.slice(start, stop + 1); + filteredTokens = filteredTokens.filter((value) => typesSet.has(value.type)); + return filteredTokens; + } + /** + * Given a starting index, return the index of the next token on channel. + * Return `i` if `tokens[i]` is on channel. Return the index of + * the EOF token if there are no tokens on channel between `i` and + * EOF. + */ + nextTokenOnChannel(i, channel) { + this.sync(i); + if (i >= this.size) { + return this.size - 1; + } + let token = this.tokens[i]; + while (token.channel !== channel) { + if (token.type === Token_1.Token.EOF) { + return i; + } + i++; + this.sync(i); + token = this.tokens[i]; + } + return i; + } + /** + * Given a starting index, return the index of the previous token on + * channel. Return `i` if `tokens[i]` is on channel. Return -1 + * if there are no tokens on channel between `i` and 0. + * + * If `i` specifies an index at or after the EOF token, the EOF token + * index is returned. This is due to the fact that the EOF token is treated + * as though it were on every channel. + */ + previousTokenOnChannel(i, channel) { + this.sync(i); + if (i >= this.size) { + // the EOF token is on every channel + return this.size - 1; + } + while (i >= 0) { + let token = this.tokens[i]; + if (token.type === Token_1.Token.EOF || token.channel === channel) { + return i; + } + i--; + } + return i; + } + /** Collect all tokens on specified channel to the right of + * the current token up until we see a token on {@link Lexer#DEFAULT_TOKEN_CHANNEL} or + * EOF. If `channel` is `-1`, find any non default channel token. + */ + getHiddenTokensToRight(tokenIndex, channel = -1) { + this.lazyInit(); + if (tokenIndex < 0 || tokenIndex >= this.tokens.length) { + throw new RangeError(tokenIndex + " not in 0.." + (this.tokens.length - 1)); + } + let nextOnChannel = this.nextTokenOnChannel(tokenIndex + 1, Lexer_1.Lexer.DEFAULT_TOKEN_CHANNEL); + let to; + let from = tokenIndex + 1; + // if none onchannel to right, nextOnChannel=-1 so set to = last token + if (nextOnChannel === -1) { + to = this.size - 1; + } + else { + to = nextOnChannel; + } + return this.filterForChannel(from, to, channel); + } + /** Collect all tokens on specified channel to the left of + * the current token up until we see a token on {@link Lexer#DEFAULT_TOKEN_CHANNEL}. + * If `channel` is `-1`, find any non default channel token. + */ + getHiddenTokensToLeft(tokenIndex, channel = -1) { + this.lazyInit(); + if (tokenIndex < 0 || tokenIndex >= this.tokens.length) { + throw new RangeError(tokenIndex + " not in 0.." + (this.tokens.length - 1)); + } + if (tokenIndex === 0) { + // obviously no tokens can appear before the first token + return []; + } + let prevOnChannel = this.previousTokenOnChannel(tokenIndex - 1, Lexer_1.Lexer.DEFAULT_TOKEN_CHANNEL); + if (prevOnChannel === tokenIndex - 1) { + return []; + } + // if none onchannel to left, prevOnChannel=-1 then from=0 + let from = prevOnChannel + 1; + let to = tokenIndex - 1; + return this.filterForChannel(from, to, channel); + } + filterForChannel(from, to, channel) { + let hidden = new Array(); + for (let i = from; i <= to; i++) { + let t = this.tokens[i]; + if (channel === -1) { + if (t.channel !== Lexer_1.Lexer.DEFAULT_TOKEN_CHANNEL) { + hidden.push(t); + } + } + else { + if (t.channel === channel) { + hidden.push(t); + } + } + } + return hidden; + } + get sourceName() { + return this.tokenSource.sourceName; + } + getText(interval) { + if (interval === undefined) { + interval = Interval_1.Interval.of(0, this.size - 1); + } + else if (!(interval instanceof Interval_1.Interval)) { + // Note: the more obvious check for 'instanceof RuleContext' results in a circular dependency problem + interval = interval.sourceInterval; + } + let start = interval.a; + let stop = interval.b; + if (start < 0 || stop < 0) { + return ""; + } + this.fill(); + if (stop >= this.tokens.length) { + stop = this.tokens.length - 1; + } + let buf = ""; + for (let i = start; i <= stop; i++) { + let t = this.tokens[i]; + if (t.type === Token_1.Token.EOF) { + break; + } + buf += t.text; + } + return buf.toString(); + } + getTextFromRange(start, stop) { + if (this.isToken(start) && this.isToken(stop)) { + return this.getText(Interval_1.Interval.of(start.tokenIndex, stop.tokenIndex)); + } + return ""; + } + /** Get all tokens from lexer until EOF. */ + fill() { + this.lazyInit(); + const blockSize = 1000; + while (true) { + let fetched = this.fetch(blockSize); + if (fetched < blockSize) { + return; + } + } + } + // TODO: Figure out a way to make this more flexible? + isWritableToken(t) { + return t instanceof CommonToken_1.CommonToken; + } + // TODO: Figure out a way to make this more flexible? + isToken(t) { + return t instanceof CommonToken_1.CommonToken; + } + }; + __decorate([ + Decorators_1.NotNull + ], BufferedTokenStream$1.prototype, "_tokenSource", void 0); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "tokenSource", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "index", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "mark", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "release", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "seek", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "size", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "consume", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "get", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "LA", null); + __decorate([ + Decorators_1.NotNull, + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "LT", null); + __decorate([ + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "sourceName", null); + __decorate([ + Decorators_1.NotNull, + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "getText", null); + __decorate([ + Decorators_1.NotNull, + Decorators_1.Override + ], BufferedTokenStream$1.prototype, "getTextFromRange", null); + BufferedTokenStream$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], BufferedTokenStream$1); + BufferedTokenStream.BufferedTokenStream = BufferedTokenStream$1; + + return BufferedTokenStream; +} + +var hasRequiredCommonTokenStream; + +function requireCommonTokenStream () { + if (hasRequiredCommonTokenStream) return CommonTokenStream; + hasRequiredCommonTokenStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (CommonTokenStream && CommonTokenStream.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (CommonTokenStream && CommonTokenStream.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(CommonTokenStream, "__esModule", { value: true }); + CommonTokenStream.CommonTokenStream = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:50.3953157-07:00 + const BufferedTokenStream_1 = requireBufferedTokenStream(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * This class extends {@link BufferedTokenStream} with functionality to filter + * token streams to tokens on a particular channel (tokens where + * {@link Token#getChannel} returns a particular value). + * + * This token stream provides access to all tokens by index or when calling + * methods like {@link #getText}. The channel filtering is only used for code + * accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and + * {@link #LB}. + * + * By default, tokens are placed on the default channel + * ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the + * `->channel(HIDDEN)` lexer command, or by using an embedded action to + * call {@link Lexer#setChannel}. + * + * Note: lexer rules which use the `->skip` lexer command or call + * {@link Lexer#skip} do not produce tokens at all, so input text matched by + * such a rule will not be available as part of the token stream, regardless of + * channel. + */ + let CommonTokenStream$1 = class CommonTokenStream extends BufferedTokenStream_1.BufferedTokenStream { + /** + * Constructs a new {@link CommonTokenStream} using the specified token + * source and filtering tokens to the specified channel. Only tokens whose + * {@link Token#getChannel} matches `channel` or have the + * `Token.type` equal to {@link Token#EOF} will be returned by the + * token stream lookahead methods. + * + * @param tokenSource The token source. + * @param channel The channel to use for filtering tokens. + */ + constructor(tokenSource, channel = Token_1.Token.DEFAULT_CHANNEL) { + super(tokenSource); + this.channel = channel; + } + adjustSeekIndex(i) { + return this.nextTokenOnChannel(i, this.channel); + } + tryLB(k) { + if ((this.p - k) < 0) { + return undefined; + } + let i = this.p; + let n = 1; + // find k good tokens looking backwards + while (n <= k && i > 0) { + // skip off-channel tokens + i = this.previousTokenOnChannel(i - 1, this.channel); + n++; + } + if (i < 0) { + return undefined; + } + return this.tokens[i]; + } + tryLT(k) { + //System.out.println("enter LT("+k+")"); + this.lazyInit(); + if (k === 0) { + throw new RangeError("0 is not a valid lookahead index"); + } + if (k < 0) { + return this.tryLB(-k); + } + let i = this.p; + let n = 1; // we know tokens[p] is a good one + // find k good tokens + while (n < k) { + // skip off-channel tokens, but make sure to not look past EOF + if (this.sync(i + 1)) { + i = this.nextTokenOnChannel(i + 1, this.channel); + } + n++; + } + // if ( i>range ) range = i; + return this.tokens[i]; + } + /** Count EOF just once. */ + getNumberOfOnChannelTokens() { + let n = 0; + this.fill(); + for (let t of this.tokens) { + if (t.channel === this.channel) { + n++; + } + if (t.type === Token_1.Token.EOF) { + break; + } + } + return n; + } + }; + __decorate([ + Decorators_1.Override + ], CommonTokenStream$1.prototype, "adjustSeekIndex", null); + __decorate([ + Decorators_1.Override + ], CommonTokenStream$1.prototype, "tryLB", null); + __decorate([ + Decorators_1.Override + ], CommonTokenStream$1.prototype, "tryLT", null); + CommonTokenStream$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], CommonTokenStream$1); + CommonTokenStream.CommonTokenStream = CommonTokenStream$1; + + return CommonTokenStream; +} + +var ListTokenSource = {}; + +var hasRequiredListTokenSource; + +function requireListTokenSource () { + if (hasRequiredListTokenSource) return ListTokenSource; + hasRequiredListTokenSource = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ListTokenSource && ListTokenSource.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ListTokenSource && ListTokenSource.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ListTokenSource, "__esModule", { value: true }); + ListTokenSource.ListTokenSource = void 0; + const CommonTokenFactory_1 = requireCommonTokenFactory(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * Provides an implementation of {@link TokenSource} as a wrapper around a list + * of {@link Token} objects. + * + * If the final token in the list is an {@link Token#EOF} token, it will be used + * as the EOF token for every call to {@link #nextToken} after the end of the + * list is reached. Otherwise, an EOF token will be created. + */ + let ListTokenSource$1 = class ListTokenSource { + /** + * Constructs a new {@link ListTokenSource} instance from the specified + * collection of {@link Token} objects and source name. + * + * @param tokens The collection of {@link Token} objects to provide as a + * {@link TokenSource}. + * @param sourceName The name of the {@link TokenSource}. If this value is + * `undefined`, {@link #getSourceName} will attempt to infer the name from + * the next {@link Token} (or the previous token if the end of the input has + * been reached). + * + * @exception NullPointerException if `tokens` is `undefined` + */ + constructor(tokens, sourceName) { + /** + * The index into {@link #tokens} of token to return by the next call to + * {@link #nextToken}. The end of the input is indicated by this value + * being greater than or equal to the number of items in {@link #tokens}. + */ + this.i = 0; + /** + * This is the backing field for {@link #getTokenFactory} and + * {@link setTokenFactory}. + */ + this._factory = CommonTokenFactory_1.CommonTokenFactory.DEFAULT; + if (tokens == null) { + throw new Error("tokens cannot be null"); + } + this.tokens = tokens; + this._sourceName = sourceName; + } + /** + * {@inheritDoc} + */ + get charPositionInLine() { + if (this.i < this.tokens.length) { + return this.tokens[this.i].charPositionInLine; + } + else if (this.eofToken != null) { + return this.eofToken.charPositionInLine; + } + else if (this.tokens.length > 0) { + // have to calculate the result from the line/column of the previous + // token, along with the text of the token. + let lastToken = this.tokens[this.tokens.length - 1]; + let tokenText = lastToken.text; + if (tokenText != null) { + let lastNewLine = tokenText.lastIndexOf("\n"); + if (lastNewLine >= 0) { + return tokenText.length - lastNewLine - 1; + } + } + return lastToken.charPositionInLine + lastToken.stopIndex - lastToken.startIndex + 1; + } + // only reach this if tokens is empty, meaning EOF occurs at the first + // position in the input + return 0; + } + /** + * {@inheritDoc} + */ + nextToken() { + if (this.i >= this.tokens.length) { + if (this.eofToken == null) { + let start = -1; + if (this.tokens.length > 0) { + let previousStop = this.tokens[this.tokens.length - 1].stopIndex; + if (previousStop !== -1) { + start = previousStop + 1; + } + } + let stop = Math.max(-1, start - 1); + this.eofToken = this._factory.create({ source: this, stream: this.inputStream }, Token_1.Token.EOF, "EOF", Token_1.Token.DEFAULT_CHANNEL, start, stop, this.line, this.charPositionInLine); + } + return this.eofToken; + } + let t = this.tokens[this.i]; + if (this.i === this.tokens.length - 1 && t.type === Token_1.Token.EOF) { + this.eofToken = t; + } + this.i++; + return t; + } + /** + * {@inheritDoc} + */ + get line() { + if (this.i < this.tokens.length) { + return this.tokens[this.i].line; + } + else if (this.eofToken != null) { + return this.eofToken.line; + } + else if (this.tokens.length > 0) { + // have to calculate the result from the line/column of the previous + // token, along with the text of the token. + let lastToken = this.tokens[this.tokens.length - 1]; + let line = lastToken.line; + let tokenText = lastToken.text; + if (tokenText != null) { + for (let i = 0; i < tokenText.length; i++) { + if (tokenText.charAt(i) === "\n") { + line++; + } + } + } + // if no text is available, assume the token did not contain any newline characters. + return line; + } + // only reach this if tokens is empty, meaning EOF occurs at the first + // position in the input + return 1; + } + /** + * {@inheritDoc} + */ + get inputStream() { + if (this.i < this.tokens.length) { + return this.tokens[this.i].inputStream; + } + else if (this.eofToken != null) { + return this.eofToken.inputStream; + } + else if (this.tokens.length > 0) { + return this.tokens[this.tokens.length - 1].inputStream; + } + // no input stream information is available + return undefined; + } + /** + * {@inheritDoc} + */ + get sourceName() { + if (this._sourceName) { + return this._sourceName; + } + let inputStream = this.inputStream; + if (inputStream != null) { + return inputStream.sourceName; + } + return "List"; + } + /** + * {@inheritDoc} + */ + // @Override + set tokenFactory(factory) { + this._factory = factory; + } + /** + * {@inheritDoc} + */ + get tokenFactory() { + return this._factory; + } + }; + __decorate([ + Decorators_1.Override + ], ListTokenSource$1.prototype, "charPositionInLine", null); + __decorate([ + Decorators_1.Override + ], ListTokenSource$1.prototype, "nextToken", null); + __decorate([ + Decorators_1.Override + ], ListTokenSource$1.prototype, "line", null); + __decorate([ + Decorators_1.Override + ], ListTokenSource$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.Override + ], ListTokenSource$1.prototype, "sourceName", null); + __decorate([ + Decorators_1.Override, + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ListTokenSource$1.prototype, "tokenFactory", null); + ListTokenSource$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], ListTokenSource$1); + ListTokenSource.ListTokenSource = ListTokenSource$1; + + return ListTokenSource; +} + +var MultiMap = {}; + +var hasRequiredMultiMap; + +function requireMultiMap () { + if (hasRequiredMultiMap) return MultiMap; + hasRequiredMultiMap = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(MultiMap, "__esModule", { value: true }); + MultiMap.MultiMap = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:42.1346951-07:00 + let MultiMap$1 = class MultiMap extends Map { + constructor() { + super(); + } + map(key, value) { + let elementsForKey = super.get(key); + if (!elementsForKey) { + elementsForKey = []; + super.set(key, elementsForKey); + } + elementsForKey.push(value); + } + getPairs() { + let pairs = []; + this.forEach((values, key) => { + values.forEach((v) => { + pairs.push([key, v]); + }); + }); + return pairs; + } + }; + MultiMap.MultiMap = MultiMap$1; + + return MultiMap; +} + +var ParseCancellationException = {}; + +var hasRequiredParseCancellationException; + +function requireParseCancellationException () { + if (hasRequiredParseCancellationException) return ParseCancellationException; + hasRequiredParseCancellationException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParseCancellationException, "__esModule", { value: true }); + ParseCancellationException.ParseCancellationException = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:42.5447085-07:00 + /** + * This exception is thrown to cancel a parsing operation. This exception does + * not extend {@link RecognitionException}, allowing it to bypass the standard + * error recovery mechanisms. {@link BailErrorStrategy} throws this exception in + * response to a parse error. + * + * @author Sam Harwell + */ + let ParseCancellationException$1 = class ParseCancellationException extends Error { + constructor(cause) { + super(cause.message); + this.cause = cause; + this.stack = cause.stack; + } + getCause() { + return this.cause; + } + }; + ParseCancellationException.ParseCancellationException = ParseCancellationException$1; + + return ParseCancellationException; +} + +var ParserInterpreter = {}; + +var InterpreterRuleContext = {}; + +var hasRequiredInterpreterRuleContext; + +function requireInterpreterRuleContext () { + if (hasRequiredInterpreterRuleContext) return InterpreterRuleContext; + hasRequiredInterpreterRuleContext = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (InterpreterRuleContext && InterpreterRuleContext.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(InterpreterRuleContext, "__esModule", { value: true }); + InterpreterRuleContext.InterpreterRuleContext = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:51.5898546-07:00 + const Decorators_1 = requireDecorators(); + const ParserRuleContext_1 = requireParserRuleContext(); + /** + * This class extends {@link ParserRuleContext} by allowing the value of + * {@link #getRuleIndex} to be explicitly set for the context. + * + * {@link ParserRuleContext} does not include field storage for the rule index + * since the context classes created by the code generator override the + * {@link #getRuleIndex} method to return the correct value for that context. + * Since the parser interpreter does not use the context classes generated for a + * parser, this class (with slightly more memory overhead per node) is used to + * provide equivalent functionality. + */ + let InterpreterRuleContext$1 = class InterpreterRuleContext extends ParserRuleContext_1.ParserRuleContext { + constructor(ruleIndex, parent, invokingStateNumber) { + if (invokingStateNumber !== undefined) { + super(parent, invokingStateNumber); + } + else { + super(); + } + this._ruleIndex = ruleIndex; + } + get ruleIndex() { + return this._ruleIndex; + } + }; + __decorate([ + Decorators_1.Override + ], InterpreterRuleContext$1.prototype, "ruleIndex", null); + InterpreterRuleContext.InterpreterRuleContext = InterpreterRuleContext$1; + + return InterpreterRuleContext; +} + +var hasRequiredParserInterpreter; + +function requireParserInterpreter () { + if (hasRequiredParserInterpreter) return ParserInterpreter; + hasRequiredParserInterpreter = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParserInterpreter && ParserInterpreter.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParserInterpreter && ParserInterpreter.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ParserInterpreter, "__esModule", { value: true }); + ParserInterpreter.ParserInterpreter = void 0; + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const BitSet_1 = requireBitSet(); + const FailedPredicateException_1 = requireFailedPredicateException(); + const InputMismatchException_1 = requireInputMismatchException(); + const InterpreterRuleContext_1 = requireInterpreterRuleContext(); + const LoopEndState_1 = requireLoopEndState(); + const Decorators_1 = requireDecorators(); + const Decorators_2 = requireDecorators(); + const Parser_1 = requireParser$1(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const RecognitionException_1 = requireRecognitionException(); + const StarLoopEntryState_1 = requireStarLoopEntryState(); + const Token_1 = requireToken(); + /** A parser simulator that mimics what ANTLR's generated + * parser code does. A ParserATNSimulator is used to make + * predictions via adaptivePredict but this class moves a pointer through the + * ATN to simulate parsing. ParserATNSimulator just + * makes us efficient rather than having to backtrack, for example. + * + * This properly creates parse trees even for left recursive rules. + * + * We rely on the left recursive rule invocation and special predicate + * transitions to make left recursive rules work. + * + * See TestParserInterpreter for examples. + */ + let ParserInterpreter$1 = class ParserInterpreter extends Parser_1.Parser { + constructor(grammarFileName, vocabulary, ruleNames, atn, input) { + super(grammarFileName instanceof ParserInterpreter ? grammarFileName.inputStream : input); + /** This stack corresponds to the _parentctx, _parentState pair of locals + * that would exist on call stack frames with a recursive descent parser; + * in the generated function for a left-recursive rule you'd see: + * + * private EContext e(int _p) { + * ParserRuleContext _parentctx = _ctx; // Pair.a + * int _parentState = state; // Pair.b + * ... + * } + * + * Those values are used to create new recursive rule invocation contexts + * associated with left operand of an alt like "expr '*' expr". + */ + this._parentContextStack = []; + /** We need a map from (decision,inputIndex)->forced alt for computing ambiguous + * parse trees. For now, we allow exactly one override. + */ + this.overrideDecision = -1; + this.overrideDecisionInputIndex = -1; + this.overrideDecisionAlt = -1; + this.overrideDecisionReached = false; // latch and only override once; error might trigger infinite loop + /** What is the current context when we override a decisions? This tells + * us what the root of the parse tree is when using override + * for an ambiguity/lookahead check. + */ + this._overrideDecisionRoot = undefined; + if (grammarFileName instanceof ParserInterpreter) { + let old = grammarFileName; + this._grammarFileName = old._grammarFileName; + this._atn = old._atn; + this.pushRecursionContextStates = old.pushRecursionContextStates; + this._ruleNames = old._ruleNames; + this._vocabulary = old._vocabulary; + this.interpreter = new ParserATNSimulator_1.ParserATNSimulator(this._atn, this); + } + else { + // The second constructor requires non-null arguments + vocabulary = vocabulary; + ruleNames = ruleNames; + atn = atn; + this._grammarFileName = grammarFileName; + this._atn = atn; + this._ruleNames = ruleNames.slice(0); + this._vocabulary = vocabulary; + // identify the ATN states where pushNewRecursionContext() must be called + this.pushRecursionContextStates = new BitSet_1.BitSet(atn.states.length); + for (let state of atn.states) { + if (!(state instanceof StarLoopEntryState_1.StarLoopEntryState)) { + continue; + } + if (state.precedenceRuleDecision) { + this.pushRecursionContextStates.set(state.stateNumber); + } + } + // get atn simulator that knows how to do predictions + this.interpreter = new ParserATNSimulator_1.ParserATNSimulator(atn, this); + } + } + reset(resetInput) { + if (resetInput === undefined) { + super.reset(); + } + else { + super.reset(resetInput); + } + this.overrideDecisionReached = false; + this._overrideDecisionRoot = undefined; + } + get atn() { + return this._atn; + } + get vocabulary() { + return this._vocabulary; + } + get ruleNames() { + return this._ruleNames; + } + get grammarFileName() { + return this._grammarFileName; + } + /** Begin parsing at startRuleIndex */ + parse(startRuleIndex) { + let startRuleStartState = this._atn.ruleToStartState[startRuleIndex]; + this._rootContext = this.createInterpreterRuleContext(undefined, ATNState_1.ATNState.INVALID_STATE_NUMBER, startRuleIndex); + if (startRuleStartState.isPrecedenceRule) { + this.enterRecursionRule(this._rootContext, startRuleStartState.stateNumber, startRuleIndex, 0); + } + else { + this.enterRule(this._rootContext, startRuleStartState.stateNumber, startRuleIndex); + } + while (true) { + let p = this.atnState; + switch (p.stateType) { + case ATNStateType_1.ATNStateType.RULE_STOP: + // pop; return from rule + if (this._ctx.isEmpty) { + if (startRuleStartState.isPrecedenceRule) { + let result = this._ctx; + let parentContext = this._parentContextStack.pop(); + this.unrollRecursionContexts(parentContext[0]); + return result; + } + else { + this.exitRule(); + return this._rootContext; + } + } + this.visitRuleStopState(p); + break; + default: + try { + this.visitState(p); + } + catch (e) { + if (e instanceof RecognitionException_1.RecognitionException) { + this.state = this._atn.ruleToStopState[p.ruleIndex].stateNumber; + this.context.exception = e; + this.errorHandler.reportError(this, e); + this.recover(e); + } + else { + throw e; + } + } + break; + } + } + } + enterRecursionRule(localctx, state, ruleIndex, precedence) { + this._parentContextStack.push([this._ctx, localctx.invokingState]); + super.enterRecursionRule(localctx, state, ruleIndex, precedence); + } + get atnState() { + return this._atn.states[this.state]; + } + visitState(p) { + let predictedAlt = 1; + if (p.numberOfTransitions > 1) { + predictedAlt = this.visitDecisionState(p); + } + let transition = p.transition(predictedAlt - 1); + switch (transition.serializationType) { + case 1 /* EPSILON */: + if (this.pushRecursionContextStates.get(p.stateNumber) && + !(transition.target instanceof LoopEndState_1.LoopEndState)) { + // We are at the start of a left recursive rule's (...)* loop + // and we're not taking the exit branch of loop. + let parentContext = this._parentContextStack[this._parentContextStack.length - 1]; + let localctx = this.createInterpreterRuleContext(parentContext[0], parentContext[1], this._ctx.ruleIndex); + this.pushNewRecursionContext(localctx, this._atn.ruleToStartState[p.ruleIndex].stateNumber, this._ctx.ruleIndex); + } + break; + case 5 /* ATOM */: + this.match(transition._label); + break; + case 2 /* RANGE */: + case 7 /* SET */: + case 8 /* NOT_SET */: + if (!transition.matches(this._input.LA(1), Token_1.Token.MIN_USER_TOKEN_TYPE, 65535)) { + this.recoverInline(); + } + this.matchWildcard(); + break; + case 9 /* WILDCARD */: + this.matchWildcard(); + break; + case 3 /* RULE */: + let ruleStartState = transition.target; + let ruleIndex = ruleStartState.ruleIndex; + let newctx = this.createInterpreterRuleContext(this._ctx, p.stateNumber, ruleIndex); + if (ruleStartState.isPrecedenceRule) { + this.enterRecursionRule(newctx, ruleStartState.stateNumber, ruleIndex, transition.precedence); + } + else { + this.enterRule(newctx, transition.target.stateNumber, ruleIndex); + } + break; + case 4 /* PREDICATE */: + let predicateTransition = transition; + if (!this.sempred(this._ctx, predicateTransition.ruleIndex, predicateTransition.predIndex)) { + throw new FailedPredicateException_1.FailedPredicateException(this); + } + break; + case 6 /* ACTION */: + let actionTransition = transition; + this.action(this._ctx, actionTransition.ruleIndex, actionTransition.actionIndex); + break; + case 10 /* PRECEDENCE */: + if (!this.precpred(this._ctx, transition.precedence)) { + let precedence = transition.precedence; + throw new FailedPredicateException_1.FailedPredicateException(this, `precpred(_ctx, ${precedence})`); + } + break; + default: + throw new Error("UnsupportedOperationException: Unrecognized ATN transition type."); + } + this.state = transition.target.stateNumber; + } + /** Method visitDecisionState() is called when the interpreter reaches + * a decision state (instance of DecisionState). It gives an opportunity + * for subclasses to track interesting things. + */ + visitDecisionState(p) { + let predictedAlt; + this.errorHandler.sync(this); + let decision = p.decision; + if (decision === this.overrideDecision && this._input.index === this.overrideDecisionInputIndex && !this.overrideDecisionReached) { + predictedAlt = this.overrideDecisionAlt; + this.overrideDecisionReached = true; + } + else { + predictedAlt = this.interpreter.adaptivePredict(this._input, decision, this._ctx); + } + return predictedAlt; + } + /** Provide simple "factory" for InterpreterRuleContext's. + * @since 4.5.1 + */ + createInterpreterRuleContext(parent, invokingStateNumber, ruleIndex) { + return new InterpreterRuleContext_1.InterpreterRuleContext(ruleIndex, parent, invokingStateNumber); + } + visitRuleStopState(p) { + let ruleStartState = this._atn.ruleToStartState[p.ruleIndex]; + if (ruleStartState.isPrecedenceRule) { + let parentContext = this._parentContextStack.pop(); + this.unrollRecursionContexts(parentContext[0]); + this.state = parentContext[1]; + } + else { + this.exitRule(); + } + let ruleTransition = this._atn.states[this.state].transition(0); + this.state = ruleTransition.followState.stateNumber; + } + /** Override this parser interpreters normal decision-making process + * at a particular decision and input token index. Instead of + * allowing the adaptive prediction mechanism to choose the + * first alternative within a block that leads to a successful parse, + * force it to take the alternative, 1..n for n alternatives. + * + * As an implementation limitation right now, you can only specify one + * override. This is sufficient to allow construction of different + * parse trees for ambiguous input. It means re-parsing the entire input + * in general because you're never sure where an ambiguous sequence would + * live in the various parse trees. For example, in one interpretation, + * an ambiguous input sequence would be matched completely in expression + * but in another it could match all the way back to the root. + * + * s : e '!'? ; + * e : ID + * | ID '!' + * ; + * + * Here, x! can be matched as (s (e ID) !) or (s (e ID !)). In the first + * case, the ambiguous sequence is fully contained only by the root. + * In the second case, the ambiguous sequences fully contained within just + * e, as in: (e ID !). + * + * Rather than trying to optimize this and make + * some intelligent decisions for optimization purposes, I settled on + * just re-parsing the whole input and then using + * {link Trees#getRootOfSubtreeEnclosingRegion} to find the minimal + * subtree that contains the ambiguous sequence. I originally tried to + * record the call stack at the point the parser detected and ambiguity but + * left recursive rules create a parse tree stack that does not reflect + * the actual call stack. That impedance mismatch was enough to make + * it it challenging to restart the parser at a deeply nested rule + * invocation. + * + * Only parser interpreters can override decisions so as to avoid inserting + * override checking code in the critical ALL(*) prediction execution path. + * + * @since 4.5 + */ + addDecisionOverride(decision, tokenIndex, forcedAlt) { + this.overrideDecision = decision; + this.overrideDecisionInputIndex = tokenIndex; + this.overrideDecisionAlt = forcedAlt; + } + get overrideDecisionRoot() { + return this._overrideDecisionRoot; + } + /** Rely on the error handler for this parser but, if no tokens are consumed + * to recover, add an error node. Otherwise, nothing is seen in the parse + * tree. + */ + recover(e) { + let i = this._input.index; + this.errorHandler.recover(this, e); + if (this._input.index === i) { + // no input consumed, better add an error node + let tok = e.getOffendingToken(); + if (!tok) { + throw new Error("Expected exception to have an offending token"); + } + let source = tok.tokenSource; + let stream = source !== undefined ? source.inputStream : undefined; + let sourcePair = { source, stream }; + if (e instanceof InputMismatchException_1.InputMismatchException) { + let expectedTokens = e.expectedTokens; + if (expectedTokens === undefined) { + throw new Error("Expected the exception to provide expected tokens"); + } + let expectedTokenType = Token_1.Token.INVALID_TYPE; + if (!expectedTokens.isNil) { + // get any element + expectedTokenType = expectedTokens.minElement; + } + let errToken = this.tokenFactory.create(sourcePair, expectedTokenType, tok.text, Token_1.Token.DEFAULT_CHANNEL, -1, -1, // invalid start/stop + tok.line, tok.charPositionInLine); + this._ctx.addErrorNode(this.createErrorNode(this._ctx, errToken)); + } + else { // NoViableAlt + tok.tokenSource; + let errToken = this.tokenFactory.create(sourcePair, Token_1.Token.INVALID_TYPE, tok.text, Token_1.Token.DEFAULT_CHANNEL, -1, -1, // invalid start/stop + tok.line, tok.charPositionInLine); + this._ctx.addErrorNode(this.createErrorNode(this._ctx, errToken)); + } + } + } + recoverInline() { + return this._errHandler.recoverInline(this); + } + /** Return the root of the parse, which can be useful if the parser + * bails out. You still can access the top node. Note that, + * because of the way left recursive rules add children, it's possible + * that the root will not have any children if the start rule immediately + * called and left recursive rule that fails. + * + * @since 4.5.1 + */ + get rootContext() { + return this._rootContext; + } + }; + __decorate([ + Decorators_1.NotNull + ], ParserInterpreter$1.prototype, "_vocabulary", void 0); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "reset", null); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "atn", null); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "vocabulary", null); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "ruleNames", null); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "grammarFileName", null); + __decorate([ + Decorators_2.Override + ], ParserInterpreter$1.prototype, "enterRecursionRule", null); + ParserInterpreter$1 = __decorate([ + __param(1, Decorators_1.NotNull) + ], ParserInterpreter$1); + ParserInterpreter.ParserInterpreter = ParserInterpreter$1; + + return ParserInterpreter; +} + +var ParseTreeMatch = {}; + +var hasRequiredParseTreeMatch; + +function requireParseTreeMatch () { + if (hasRequiredParseTreeMatch) return ParseTreeMatch; + hasRequiredParseTreeMatch = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParseTreeMatch && ParseTreeMatch.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParseTreeMatch && ParseTreeMatch.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ParseTreeMatch, "__esModule", { value: true }); + ParseTreeMatch.ParseTreeMatch = void 0; + const Decorators_1 = requireDecorators(); + /** + * Represents the result of matching a {@link ParseTree} against a tree pattern. + */ + let ParseTreeMatch$1 = class ParseTreeMatch { + /** + * Constructs a new instance of {@link ParseTreeMatch} from the specified + * parse tree and pattern. + * + * @param tree The parse tree to match against the pattern. + * @param pattern The parse tree pattern. + * @param labels A mapping from label names to collections of + * {@link ParseTree} objects located by the tree pattern matching process. + * @param mismatchedNode The first node which failed to match the tree + * pattern during the matching process. + * + * @throws {@link Error} if `tree` is not defined + * @throws {@link Error} if `pattern` is not defined + * @throws {@link Error} if `labels` is not defined + */ + constructor(tree, pattern, labels, mismatchedNode) { + if (!tree) { + throw new Error("tree cannot be null"); + } + if (!pattern) { + throw new Error("pattern cannot be null"); + } + if (!labels) { + throw new Error("labels cannot be null"); + } + this._tree = tree; + this._pattern = pattern; + this._labels = labels; + this._mismatchedNode = mismatchedNode; + } + /** + * Get the last node associated with a specific `label`. + * + * For example, for pattern ``, `get("id")` returns the + * node matched for that `ID`. If more than one node + * matched the specified label, only the last is returned. If there is + * no node associated with the label, this returns `undefined`. + * + * Pattern tags like `` and `` without labels are + * considered to be labeled with `ID` and `expr`, respectively. + * + * @param label The label to check. + * + * @returns The last {@link ParseTree} to match a tag with the specified + * label, or `undefined` if no parse tree matched a tag with the label. + */ + get(label) { + let parseTrees = this._labels.get(label); + if (!parseTrees || parseTrees.length === 0) { + return undefined; + } + return parseTrees[parseTrees.length - 1]; // return last if multiple + } + /** + * Return all nodes matching a rule or token tag with the specified label. + * + * If the `label` is the name of a parser rule or token in the + * grammar, the resulting list will contain both the parse trees matching + * rule or tags explicitly labeled with the label and the complete set of + * parse trees matching the labeled and unlabeled tags in the pattern for + * the parser rule or token. For example, if `label` is `"foo"`, + * the result will contain *all* of the following. + * + * * Parse tree nodes matching tags of the form `` and + * ``. + * * Parse tree nodes matching tags of the form ``. + * * Parse tree nodes matching tags of the form ``. + * + * @param label The label. + * + * @returns A collection of all {@link ParseTree} nodes matching tags with + * the specified `label`. If no nodes matched the label, an empty list + * is returned. + */ + getAll(label) { + const nodes = this._labels.get(label); + if (!nodes) { + return []; + } + return nodes; + } + /** + * Return a mapping from label → [list of nodes]. + * + * The map includes special entries corresponding to the names of rules and + * tokens referenced in tags in the original pattern. For additional + * information, see the description of {@link #getAll(String)}. + * + * @returns A mapping from labels to parse tree nodes. If the parse tree + * pattern did not contain any rule or token tags, this map will be empty. + */ + get labels() { + return this._labels; + } + /** + * Get the node at which we first detected a mismatch. + * + * @returns the node at which we first detected a mismatch, or `undefined` + * if the match was successful. + */ + get mismatchedNode() { + return this._mismatchedNode; + } + /** + * Gets a value indicating whether the match operation succeeded. + * + * @returns `true` if the match operation succeeded; otherwise, + * `false`. + */ + get succeeded() { + return !this._mismatchedNode; + } + /** + * Get the tree pattern we are matching against. + * + * @returns The tree pattern we are matching against. + */ + get pattern() { + return this._pattern; + } + /** + * Get the parse tree we are trying to match to a pattern. + * + * @returns The {@link ParseTree} we are trying to match to a pattern. + */ + get tree() { + return this._tree; + } + /** + * {@inheritDoc} + */ + toString() { + return `Match ${this.succeeded ? "succeeded" : "failed"}; found ${this.labels.size} labels`; + } + }; + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ParseTreeMatch$1.prototype, "getAll", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreeMatch$1.prototype, "labels", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreeMatch$1.prototype, "pattern", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreeMatch$1.prototype, "tree", null); + __decorate([ + Decorators_1.Override + ], ParseTreeMatch$1.prototype, "toString", null); + ParseTreeMatch$1 = __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ParseTreeMatch$1); + ParseTreeMatch.ParseTreeMatch = ParseTreeMatch$1; + + return ParseTreeMatch; +} + +var ParseTreePattern = {}; + +var XPath = {}; + +var XPathLexer = {}; + +var hasRequiredXPathLexer; + +function requireXPathLexer () { + if (hasRequiredXPathLexer) return XPathLexer; + hasRequiredXPathLexer = 1; + // Generated from XPathLexer.g4 by ANTLR 4.9.0-SNAPSHOT + Object.defineProperty(XPathLexer, "__esModule", { value: true }); + XPathLexer.XPathLexer = void 0; + const ATNDeserializer_1 = requireATNDeserializer(); + const Lexer_1 = requireLexer(); + const LexerATNSimulator_1 = requireLexerATNSimulator(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const Utils = requireUtils(); + let XPathLexer$1 = class XPathLexer extends Lexer_1.Lexer { + // tslint:enable:no-trailing-whitespace + constructor(input) { + super(input); + this._interp = new LexerATNSimulator_1.LexerATNSimulator(XPathLexer._ATN, this); + } + // @Override + // @NotNull + get vocabulary() { + return XPathLexer.VOCABULARY; + } + // @Override + get grammarFileName() { return "XPathLexer.g4"; } + // @Override + get ruleNames() { return XPathLexer.ruleNames; } + // @Override + get serializedATN() { return XPathLexer._serializedATN; } + // @Override + get channelNames() { return XPathLexer.channelNames; } + // @Override + get modeNames() { return XPathLexer.modeNames; } + // @Override + action(_localctx, ruleIndex, actionIndex) { + switch (ruleIndex) { + case 4: + this.ID_action(_localctx, actionIndex); + break; + } + } + ID_action(_localctx, actionIndex) { + switch (actionIndex) { + case 0: + let text = this.text; + if (text.charAt(0) === text.charAt(0).toUpperCase()) { + this.type = XPathLexer.TOKEN_REF; + } + else { + this.type = XPathLexer.RULE_REF; + } + break; + } + } + static get _ATN() { + if (!XPathLexer.__ATN) { + XPathLexer.__ATN = new ATNDeserializer_1.ATNDeserializer().deserialize(Utils.toCharArray(XPathLexer._serializedATN)); + } + return XPathLexer.__ATN; + } + }; + XPathLexer.XPathLexer = XPathLexer$1; + XPathLexer$1.TOKEN_REF = 1; + XPathLexer$1.RULE_REF = 2; + XPathLexer$1.ANYWHERE = 3; + XPathLexer$1.ROOT = 4; + XPathLexer$1.WILDCARD = 5; + XPathLexer$1.BANG = 6; + XPathLexer$1.ID = 7; + XPathLexer$1.STRING = 8; + // tslint:disable:no-trailing-whitespace + XPathLexer$1.channelNames = [ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + ]; + // tslint:disable:no-trailing-whitespace + XPathLexer$1.modeNames = [ + "DEFAULT_MODE", + ]; + XPathLexer$1.ruleNames = [ + "ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", "NameStartChar", + "STRING", + ]; + XPathLexer$1._LITERAL_NAMES = [ + undefined, undefined, undefined, "'//'", "'/'", "'*'", "'!'", + ]; + XPathLexer$1._SYMBOLIC_NAMES = [ + undefined, "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG", + "ID", "STRING", + ]; + XPathLexer$1.VOCABULARY = new VocabularyImpl_1.VocabularyImpl(XPathLexer$1._LITERAL_NAMES, XPathLexer$1._SYMBOLIC_NAMES, []); + XPathLexer$1._serializedATNSegments = 2; + XPathLexer$1._serializedATNSegment0 = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02\n2\b\x01\x04" + + "\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04" + + "\x07\t\x07\x04\b\t\b\x04\t\t\t\x03\x02\x03\x02\x03\x02\x03\x03\x03\x03" + + "\x03\x04\x03\x04\x03\x05\x03\x05\x03\x06\x03\x06\x07\x06\x1F\n\x06\f\x06" + + "\x0E\x06\"\v\x06\x03\x06\x03\x06\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03" + + "\t\x07\t,\n\t\f\t\x0E\t/\v\t\x03\t\x03\t\x03-\x02\x02\n\x03\x02\x05\x05" + + "\x02\x06\x07\x02\x07\t\x02\b\v\x02\t\r\x02\x02\x0F\x02\x02\x11\x02\n\x03" + + "\x02\x02\x04\u02B6\x02\x02\x02\n\x02\x10\x02\x1D\x022\x02;\x02C\x02\\" + + "\x02a\x02a\x02c\x02|\x02\x81\x02\xA1\x02\xAC\x02\xAC\x02\xAF\x02\xAF\x02" + + "\xB7\x02\xB7\x02\xBC\x02\xBC\x02\xC2\x02\xD8\x02\xDA\x02\xF8\x02\xFA\x02" + + "\u02C3\x02\u02C8\x02\u02D3\x02\u02E2\x02\u02E6\x02\u02EE\x02\u02EE\x02" + + "\u02F0\x02\u02F0\x02\u0302\x02\u0376\x02\u0378\x02\u0379\x02\u037C\x02" + + "\u037F\x02\u0381\x02\u0381\x02\u0388\x02\u0388\x02\u038A\x02\u038C\x02" + + "\u038E\x02\u038E\x02\u0390\x02\u03A3\x02\u03A5\x02\u03F7\x02\u03F9\x02" + + "\u0483\x02\u0485\x02\u0489\x02\u048C\x02\u0531\x02\u0533\x02\u0558\x02" + + "\u055B\x02\u055B\x02\u0563\x02\u0589\x02\u0593\x02\u05BF\x02\u05C1\x02" + + "\u05C1\x02\u05C3\x02\u05C4\x02\u05C6\x02\u05C7\x02\u05C9\x02\u05C9\x02" + + "\u05D2\x02\u05EC\x02\u05F2\x02\u05F4\x02\u0602\x02\u0607\x02\u0612\x02" + + "\u061C\x02\u061E\x02\u061E\x02\u0622\x02\u066B\x02\u0670\x02\u06D5\x02" + + "\u06D7\x02\u06DF\x02\u06E1\x02\u06EA\x02\u06EC\x02\u06FE\x02\u0701\x02" + + "\u0701\x02\u0711\x02\u074C\x02\u074F\x02\u07B3\x02\u07C2\x02\u07F7\x02" + + "\u07FC\x02\u07FC\x02\u0802\x02\u082F\x02\u0842\x02\u085D\x02\u08A2\x02" + + "\u08B6\x02\u08B8\x02\u08BF\x02\u08D6\x02\u0965\x02\u0968\x02\u0971\x02" + + "\u0973\x02\u0985\x02\u0987\x02\u098E\x02\u0991\x02\u0992\x02\u0995\x02" + + "\u09AA\x02\u09AC\x02\u09B2\x02\u09B4\x02\u09B4\x02\u09B8\x02\u09BB\x02" + + "\u09BE\x02\u09C6\x02\u09C9\x02\u09CA\x02\u09CD\x02\u09D0\x02\u09D9\x02" + + "\u09D9\x02\u09DE\x02\u09DF\x02\u09E1\x02\u09E5\x02\u09E8\x02\u09F3\x02" + + "\u0A03\x02\u0A05\x02\u0A07\x02\u0A0C\x02\u0A11\x02\u0A12\x02\u0A15\x02" + + "\u0A2A\x02\u0A2C\x02\u0A32\x02\u0A34\x02\u0A35\x02\u0A37\x02\u0A38\x02" + + "\u0A3A\x02\u0A3B\x02\u0A3E\x02\u0A3E\x02\u0A40\x02\u0A44\x02\u0A49\x02" + + "\u0A4A\x02\u0A4D\x02\u0A4F\x02\u0A53\x02\u0A53\x02\u0A5B\x02\u0A5E\x02" + + "\u0A60\x02\u0A60\x02\u0A68\x02\u0A77\x02\u0A83\x02\u0A85\x02\u0A87\x02" + + "\u0A8F\x02\u0A91\x02\u0A93\x02\u0A95\x02\u0AAA\x02\u0AAC\x02\u0AB2\x02" + + "\u0AB4\x02\u0AB5\x02\u0AB7\x02\u0ABB\x02\u0ABE\x02\u0AC7\x02\u0AC9\x02" + + "\u0ACB\x02\u0ACD\x02\u0ACF\x02\u0AD2\x02\u0AD2\x02\u0AE2\x02\u0AE5\x02" + + "\u0AE8\x02\u0AF1\x02\u0AFB\x02\u0AFB\x02\u0B03\x02\u0B05\x02\u0B07\x02" + + "\u0B0E\x02\u0B11\x02\u0B12\x02\u0B15\x02\u0B2A\x02\u0B2C\x02\u0B32\x02" + + "\u0B34\x02\u0B35\x02\u0B37\x02\u0B3B\x02\u0B3E\x02\u0B46\x02\u0B49\x02" + + "\u0B4A\x02\u0B4D\x02\u0B4F\x02\u0B58\x02\u0B59\x02\u0B5E\x02\u0B5F\x02" + + "\u0B61\x02\u0B65\x02\u0B68\x02\u0B71\x02\u0B73\x02\u0B73\x02\u0B84\x02" + + "\u0B85\x02\u0B87\x02\u0B8C\x02\u0B90\x02\u0B92\x02\u0B94\x02\u0B97\x02" + + "\u0B9B\x02\u0B9C\x02\u0B9E\x02\u0B9E\x02\u0BA0\x02\u0BA1\x02\u0BA5\x02" + + "\u0BA6\x02\u0BAA\x02\u0BAC\x02\u0BB0\x02\u0BBB\x02\u0BC0\x02\u0BC4\x02" + + "\u0BC8\x02\u0BCA\x02\u0BCC\x02\u0BCF\x02\u0BD2\x02\u0BD2\x02\u0BD9\x02" + + "\u0BD9\x02\u0BE8\x02\u0BF1\x02\u0C02\x02\u0C05\x02\u0C07\x02\u0C0E\x02" + + "\u0C10\x02\u0C12\x02\u0C14\x02\u0C2A\x02\u0C2C\x02\u0C3B\x02\u0C3F\x02" + + "\u0C46\x02\u0C48\x02\u0C4A\x02\u0C4C\x02\u0C4F\x02\u0C57\x02\u0C58\x02" + + "\u0C5A\x02\u0C5C\x02\u0C62\x02\u0C65\x02\u0C68\x02\u0C71\x02\u0C82\x02" + + "\u0C85\x02\u0C87\x02\u0C8E\x02\u0C90\x02\u0C92\x02\u0C94\x02\u0CAA\x02" + + "\u0CAC\x02\u0CB5\x02\u0CB7\x02\u0CBB\x02\u0CBE\x02\u0CC6\x02\u0CC8\x02" + + "\u0CCA\x02\u0CCC\x02\u0CCF\x02\u0CD7\x02\u0CD8\x02\u0CE0\x02\u0CE0\x02" + + "\u0CE2\x02\u0CE5\x02\u0CE8\x02\u0CF1\x02\u0CF3\x02\u0CF4\x02\u0D03\x02" + + "\u0D05\x02\u0D07\x02\u0D0E\x02\u0D10\x02\u0D12\x02\u0D14\x02\u0D3C\x02" + + "\u0D3F\x02\u0D46\x02\u0D48\x02\u0D4A\x02\u0D4C\x02\u0D50\x02\u0D56\x02" + + "\u0D59\x02\u0D61\x02\u0D65\x02\u0D68\x02\u0D71\x02\u0D7C\x02\u0D81\x02" + + "\u0D84\x02\u0D85\x02\u0D87\x02\u0D98\x02\u0D9C\x02\u0DB3\x02\u0DB5\x02" + + "\u0DBD\x02\u0DBF\x02\u0DBF\x02\u0DC2\x02\u0DC8\x02\u0DCC\x02\u0DCC\x02" + + "\u0DD1\x02\u0DD6\x02\u0DD8\x02\u0DD8\x02\u0DDA\x02\u0DE1\x02\u0DE8\x02" + + "\u0DF1\x02\u0DF4\x02\u0DF5\x02\u0E03\x02\u0E3C\x02\u0E42\x02\u0E50\x02" + + "\u0E52\x02\u0E5B\x02\u0E83\x02\u0E84\x02\u0E86\x02\u0E86\x02\u0E89\x02" + + "\u0E8A\x02\u0E8C\x02\u0E8C\x02\u0E8F\x02\u0E8F\x02\u0E96\x02\u0E99\x02" + + "\u0E9B\x02\u0EA1\x02\u0EA3\x02\u0EA5\x02\u0EA7\x02\u0EA7\x02\u0EA9\x02" + + "\u0EA9\x02\u0EAC\x02\u0EAD\x02\u0EAF\x02\u0EBB\x02\u0EBD\x02\u0EBF\x02" + + "\u0EC2\x02\u0EC6\x02\u0EC8\x02\u0EC8\x02\u0ECA\x02\u0ECF\x02\u0ED2\x02" + + "\u0EDB\x02\u0EDE\x02\u0EE1\x02\u0F02\x02\u0F02\x02\u0F1A\x02\u0F1B\x02" + + "\u0F22\x02\u0F2B\x02\u0F37\x02\u0F37\x02\u0F39\x02\u0F39\x02\u0F3B\x02" + + "\u0F3B\x02\u0F40\x02\u0F49\x02\u0F4B\x02\u0F6E\x02\u0F73\x02\u0F86\x02" + + "\u0F88\x02\u0F99\x02\u0F9B\x02\u0FBE\x02\u0FC8\x02\u0FC8\x02\u1002\x02" + + "\u104B\x02\u1052\x02\u109F\x02\u10A2\x02\u10C7\x02\u10C9\x02\u10C9\x02" + + "\u10CF\x02\u10CF\x02\u10D2\x02\u10FC\x02\u10FE\x02\u124A\x02\u124C\x02" + + "\u124F\x02\u1252\x02\u1258\x02\u125A\x02\u125A\x02\u125C\x02\u125F\x02" + + "\u1262\x02\u128A\x02\u128C\x02\u128F\x02\u1292\x02\u12B2\x02\u12B4\x02" + + "\u12B7\x02\u12BA\x02\u12C0\x02\u12C2\x02\u12C2\x02\u12C4\x02\u12C7\x02" + + "\u12CA\x02\u12D8\x02\u12DA\x02\u1312\x02\u1314\x02\u1317\x02\u131A\x02" + + "\u135C\x02\u135F\x02\u1361\x02\u1382\x02\u1391\x02\u13A2\x02\u13F7\x02" + + "\u13FA\x02\u13FF\x02\u1403\x02\u166E\x02\u1671\x02\u1681\x02\u1683\x02" + + "\u169C\x02\u16A2\x02\u16EC\x02\u16F0\x02\u16FA\x02\u1702\x02\u170E\x02" + + "\u1710\x02\u1716\x02\u1722\x02\u1736\x02\u1742\x02\u1755\x02\u1762\x02" + + "\u176E\x02\u1770\x02\u1772\x02\u1774\x02\u1775\x02\u1782\x02\u17D5\x02" + + "\u17D9\x02\u17D9\x02\u17DE\x02\u17DF\x02\u17E2\x02\u17EB\x02\u180D\x02" + + "\u1810\x02\u1812\x02\u181B\x02\u1822\x02\u1879\x02\u1882\x02\u18AC\x02" + + "\u18B2\x02\u18F7\x02\u1902\x02\u1920\x02\u1922\x02\u192D\x02\u1932\x02" + + "\u193D\x02\u1948\x02\u196F\x02\u1972\x02\u1976\x02\u1982\x02\u19AD\x02" + + "\u19B2\x02\u19CB\x02\u19D2\x02\u19DB\x02\u1A02\x02\u1A1D\x02\u1A22\x02" + + "\u1A60\x02\u1A62\x02\u1A7E\x02\u1A81\x02\u1A8B\x02\u1A92\x02\u1A9B\x02" + + "\u1AA9\x02\u1AA9\x02\u1AB2\x02\u1ABF\x02\u1B02\x02\u1B4D\x02\u1B52\x02" + + "\u1B5B\x02\u1B6D\x02\u1B75\x02\u1B82\x02\u1BF5\x02\u1C02\x02\u1C39\x02" + + "\u1C42\x02\u1C4B\x02\u1C4F\x02\u1C7F\x02\u1C82\x02\u1C8A\x02\u1CD2\x02" + + "\u1CD4\x02\u1CD6\x02\u1CF8\x02\u1CFA\x02\u1CFB\x02\u1D02\x02\u1DF7\x02" + + "\u1DFD\x02\u1F17\x02\u1F1A\x02\u1F1F\x02\u1F22\x02\u1F47\x02\u1F4A\x02" + + "\u1F4F\x02\u1F52\x02\u1F59\x02\u1F5B\x02\u1F5B\x02\u1F5D\x02\u1F5D\x02" + + "\u1F5F\x02\u1F5F\x02\u1F61\x02\u1F7F\x02\u1F82\x02\u1FB6\x02\u1FB8\x02" + + "\u1FBE\x02\u1FC0\x02\u1FC0\x02\u1FC4\x02\u1FC6\x02\u1FC8\x02\u1FCE\x02" + + "\u1FD2\x02\u1FD5\x02\u1FD8\x02\u1FDD\x02\u1FE2\x02\u1FEE\x02\u1FF4\x02" + + "\u1FF6\x02\u1FF8\x02\u1FFE\x02\u200D\x02\u2011\x02\u202C\x02\u2030\x02" + + "\u2041\x02\u2042\x02\u2056\x02\u2056\x02\u2062\x02\u2066\x02\u2068\x02" + + "\u2071\x02\u2073\x02\u2073\x02\u2081\x02\u2081\x02\u2092\x02\u209E\x02" + + "\u20D2\x02\u20DE\x02\u20E3\x02\u20E3\x02\u20E7\x02\u20F2\x02\u2104\x02" + + "\u2104\x02\u2109\x02\u2109\x02\u210C\x02\u2115\x02\u2117\x02\u2117\x02" + + "\u211B\x02\u211F\x02\u2126\x02\u2126\x02\u2128\x02\u2128\x02\u212A\x02" + + "\u212A\x02\u212C\x02\u212F\x02\u2131\x02\u213B\x02\u213E\x02\u2141\x02" + + "\u2147\x02\u214B\x02\u2150\x02\u2150\x02\u2162\x02\u218A\x02\u2C02\x02" + + "\u2C30\x02\u2C32\x02\u2C60\x02\u2C62\x02\u2CE6\x02\u2CED\x02\u2CF5\x02" + + "\u2D02\x02\u2D27\x02\u2D29\x02\u2D29\x02\u2D2F\x02\u2D2F\x02\u2D32\x02" + + "\u2D69\x02\u2D71\x02\u2D71\x02\u2D81\x02\u2D98\x02\u2DA2\x02\u2DA8\x02" + + "\u2DAA\x02\u2DB0\x02\u2DB2\x02\u2DB8\x02\u2DBA\x02\u2DC0\x02\u2DC2\x02" + + "\u2DC8\x02\u2DCA\x02\u2DD0\x02\u2DD2\x02\u2DD8\x02\u2DDA\x02\u2DE0\x02" + + "\u2DE2\x02\u2E01\x02\u2E31\x02\u2E31\x02\u3007\x02\u3009\x02\u3023\x02" + + "\u3031\x02\u3033\x02\u3037\x02\u303A\x02\u303E\x02\u3043\x02\u3098\x02" + + "\u309B\x02\u309C\x02\u309F\x02\u30A1\x02\u30A3\x02\u30FC\x02\u30FE\x02" + + "\u3101\x02\u3107\x02\u312F\x02\u3133\x02\u3190\x02\u31A2\x02\u31BC\x02" + + "\u31F2\x02\u3201\x02\u3402\x02\u4DB7\x02\u4E02\x02\u9FD7\x02\uA002\x02" + + "\uA48E\x02\uA4D2\x02\uA4FF\x02\uA502\x02\uA60E\x02\uA612\x02\uA62D\x02" + + "\uA642\x02\uA671\x02\uA676\x02\uA67F\x02\uA681\x02\uA6F3\x02\uA719\x02" + + "\uA721\x02\uA724\x02\uA78A\x02\uA78D\x02\uA7B0\x02\uA7B2\x02\uA7B9\x02" + + "\uA7F9\x02\uA829\x02\uA842\x02\uA875\x02\uA882\x02\uA8C7\x02\uA8D2\x02" + + "\uA8DB\x02\uA8E2\x02\uA8F9\x02\uA8FD\x02\uA8FD\x02\uA8FF\x02\uA8FF\x02" + + "\uA902\x02\uA92F\x02\uA932\x02\uA955\x02\uA962\x02\uA97E\x02\uA982\x02" + + "\uA9C2\x02\uA9D1\x02\uA9DB\x02\uA9E2\x02\uAA00\x02\uAA02\x02\uAA38\x02" + + "\uAA42\x02\uAA4F\x02\uAA52\x02\uAA5B\x02\uAA62\x02\uAA78\x02\uAA7C\x02" + + "\uAAC4\x02\uAADD\x02\uAADF\x02\uAAE2\x02\uAAF1\x02\uAAF4\x02\uAAF8\x02" + + "\uAB03\x02\uAB08\x02\uAB0B\x02\uAB10\x02\uAB13\x02\uAB18\x02\uAB22\x02" + + "\uAB28\x02\uAB2A\x02\uAB30\x02\uAB32\x02\uAB5C\x02\uAB5E\x02\uAB67\x02" + + "\uAB72\x02\uABEC\x02\uABEE\x02\uABEF\x02\uABF2\x02\uABFB\x02\uAC02\x02" + + "\uD7A5\x02\uD7B2\x02\uD7C8\x02\uD7CD\x02\uD7FD\x02\uF902\x02\uFA6F\x02" + + "\uFA72\x02\uFADB\x02\uFB02\x02\uFB08\x02\uFB15\x02\uFB19\x02\uFB1F\x02" + + "\uFB2A\x02\uFB2C\x02\uFB38\x02\uFB3A\x02\uFB3E\x02\uFB40\x02\uFB40\x02" + + "\uFB42\x02\uFB43\x02\uFB45\x02\uFB46\x02\uFB48\x02\uFBB3\x02\uFBD5\x02" + + "\uFD3F\x02\uFD52\x02\uFD91\x02\uFD94\x02\uFDC9\x02\uFDF2\x02\uFDFD\x02" + + "\uFE02\x02\uFE11\x02\uFE22\x02\uFE31\x02\uFE35\x02\uFE36\x02\uFE4F\x02" + + "\uFE51\x02\uFE72\x02\uFE76\x02\uFE78\x02\uFEFE\x02\uFF01\x02\uFF01\x02" + + "\uFF12\x02\uFF1B\x02\uFF23\x02\uFF3C\x02\uFF41\x02\uFF41\x02\uFF43\x02" + + "\uFF5C\x02\uFF68\x02\uFFC0\x02\uFFC4\x02\uFFC9\x02\uFFCC\x02\uFFD1\x02" + + "\uFFD4\x02\uFFD9\x02\uFFDC\x02\uFFDE\x02\uFFFB\x02\uFFFD\x02\x02\x03\r" + + "\x03\x0F\x03(\x03*\x03<\x03>\x03?\x03A\x03O\x03R\x03_\x03\x82\x03\xFC" + + "\x03\u0142\x03\u0176\x03\u01FF\x03\u01FF\x03\u0282\x03\u029E\x03\u02A2" + + "\x03\u02D2\x03\u02E2\x03\u02E2\x03\u0302\x03\u0321\x03\u0332\x03\u034C" + + "\x03\u0352\x03\u037C\x03\u0382\x03\u039F\x03\u03A2\x03\u03C5\x03\u03CA" + + "\x03\u03D1\x03\u03D3\x03\u03D7\x03\u0402\x03\u049F\x03\u04A2\x03\u04AB" + + "\x03\u04B2\x03\u04D5\x03\u04DA\x03\u04FD\x03\u0502\x03\u0529\x03\u0532" + + "\x03\u0565\x03\u0602\x03\u0738\x03\u0742\x03\u0757\x03\u0762\x03\u0769" + + "\x03\u0802\x03\u0807\x03\u080A\x03\u080A\x03\u080C\x03\u0837\x03\u0839" + + "\x03\u083A\x03\u083E\x03\u083E\x03\u0841\x03\u0857\x03\u0862\x03\u0878" + + "\x03\u0882\x03\u08A0\x03\u08E2\x03\u08F4\x03\u08F6\x03\u08F7\x03\u0902" + + "\x03\u0917\x03\u0922\x03\u093B\x03\u0982\x03\u09B9\x03\u09C0\x03\u09C1" + + "\x03\u0A02\x03\u0A05\x03\u0A07\x03\u0A08\x03\u0A0E\x03\u0A15\x03\u0A17" + + "\x03\u0A19\x03\u0A1B\x03\u0A35\x03\u0A3A\x03\u0A3C\x03\u0A41\x03\u0A41" + + "\x03\u0A62\x03\u0A7E\x03\u0A82\x03\u0A9E\x03\u0AC2\x03\u0AC9\x03\u0ACB" + + "\x03\u0AE8\x03\u0B02\x03\u0B37\x03\u0B42\x03\u0B57\x03\u0B62\x03\u0B74" + + "\x03\u0B82\x03\u0B93\x03\u0C02\x03\u0C4A\x03\u0C82\x03\u0CB4\x03\u0CC2" + + "\x03\u0CF4\x03\u1002\x03\u1048\x03\u1068\x03\u1071\x03\u1081\x03\u10BC" + + "\x03\u10BF\x03\u10BF\x03\u10D2\x03\u10EA\x03\u10F2\x03\u10FB\x03\u1102" + + "\x03\u1136\x03\u1138\x03\u1141\x03\u1152\x03\u1175\x03\u1178\x03\u1178" + + "\x03\u1182\x03\u11C6\x03\u11CC\x03\u11CE\x03\u11D2\x03\u11DC\x03\u11DE" + + "\x03\u11DE\x03\u1202\x03\u1213\x03\u1215\x03\u1239\x03\u1240\x03\u1240" + + "\x03\u1282\x03\u1288\x03\u128A\x03\u128A\x03\u128C\x03\u128F\x03\u1291" + + "\x03\u129F\x03\u12A1\x03\u12AA\x03\u12B2\x03\u12EC\x03\u12F2\x03\u12FB" + + "\x03\u1302\x03\u1305\x03\u1307\x03\u130E\x03\u1311\x03\u1312\x03\u1315" + + "\x03\u132A\x03\u132C\x03\u1332\x03\u1334\x03\u1335\x03\u1337\x03\u133B" + + "\x03\u133E\x03\u1346\x03\u1349\x03\u134A\x03\u134D\x03\u134F\x03\u1352" + + "\x03\u1352\x03\u1359\x03\u1359\x03\u135F\x03\u1365\x03\u1368\x03\u136E" + + "\x03\u1372\x03\u1376\x03\u1402\x03\u144C\x03\u1452\x03\u145B\x03\u1482" + + "\x03\u14C7\x03\u14C9\x03\u14C9\x03\u14D2\x03\u14DB\x03\u1582\x03\u15B7" + + "\x03\u15BA\x03\u15C2\x03\u15DA\x03\u15DF\x03\u1602\x03\u1642\x03\u1646" + + "\x03\u1646\x03\u1652\x03\u165B\x03\u1682\x03\u16B9\x03\u16C2\x03\u16CB" + + "\x03\u1702\x03\u171B\x03\u171F\x03\u172D\x03\u1732\x03\u173B\x03\u18A2" + + "\x03\u18EB\x03\u1901\x03\u1901\x03\u1AC2\x03\u1AFA\x03\u1C02\x03\u1C0A" + + "\x03\u1C0C\x03\u1C38\x03\u1C3A\x03\u1C42\x03\u1C52\x03\u1C5B\x03\u1C74" + + "\x03\u1C91\x03\u1C94\x03\u1CA9\x03\u1CAB\x03\u1CB8\x03\u2002\x03\u239B" + + "\x03\u2402\x03\u2470\x03\u2482\x03\u2545\x03\u3002\x03\u3430\x03\u4402" + + "\x03\u4648\x03\u6802\x03\u6A3A\x03\u6A42\x03\u6A60\x03\u6A62\x03\u6A6B" + + "\x03\u6AD2\x03\u6AEF\x03\u6AF2\x03\u6AF6\x03\u6B02\x03\u6B38\x03\u6B42" + + "\x03\u6B45\x03\u6B52\x03\u6B5B\x03\u6B65\x03\u6B79\x03\u6B7F\x03\u6B91" + + "\x03\u6F02\x03\u6F46\x03\u6F52\x03\u6F80\x03\u6F91\x03\u6FA1\x03\u6FE2" + + "\x03\u6FE2\x03\u7002\x03\u87EE\x03\u8802\x03\u8AF4\x03\uB002\x03\uB003" + + "\x03\uBC02\x03\uBC6C\x03\uBC72\x03\uBC7E\x03\uBC82\x03\uBC8A\x03\uBC92" + + "\x03\uBC9B\x03\uBC9F\x03\uBCA0\x03\uBCA2\x03\uBCA5\x03\uD167\x03\uD16B" + + "\x03\uD16F\x03\uD184\x03\uD187\x03\uD18D\x03\uD1AC\x03\uD1AF\x03\uD244" + + "\x03\uD246\x03\uD402\x03\uD456\x03\uD458\x03\uD49E\x03\uD4A0\x03\uD4A1" + + "\x03\uD4A4\x03\uD4A4\x03\uD4A7\x03\uD4A8\x03\uD4AB\x03\uD4AE\x03\uD4B0" + + "\x03\uD4BB\x03\uD4BD\x03\uD4BD\x03\uD4BF\x03\uD4C5\x03\uD4C7\x03\uD507" + + "\x03\uD509\x03\uD50C\x03\uD50F\x03\uD516\x03\uD518\x03\uD51E\x03\uD520" + + "\x03\uD53B\x03\uD53D\x03\uD540\x03\uD542\x03\uD546\x03\uD548\x03\uD548" + + "\x03\uD54C\x03\uD552\x03\uD554\x03\uD6A7\x03\uD6AA\x03\uD6C2\x03\uD6C4" + + "\x03\uD6DC\x03\uD6DE\x03\uD6FC\x03\uD6FE\x03\uD716\x03\uD718\x03\uD736" + + "\x03\uD738\x03\uD750\x03\uD752\x03\uD770\x03\uD772\x03\uD78A\x03\uD78C" + + "\x03\uD7AA\x03\uD7AC\x03\uD7C4\x03\uD7C6\x03\uD7CD\x03\uD7D0\x03\uD801" + + "\x03\uDA02\x03\uDA38\x03\uDA3D\x03\uDA6E\x03\uDA77\x03\uDA77\x03\uDA86" + + "\x03\uDA86\x03\uDA9D\x03\uDAA1\x03\uDAA3\x03\uDAB1\x03\uE002\x03\uE008" + + "\x03\uE00A\x03\uE01A\x03\uE01D\x03\uE023\x03\uE025\x03\uE026\x03\uE028" + + "\x03\uE02C\x03\uE802\x03\uE8C6\x03\uE8D2\x03\uE8D8\x03\uE902\x03\uE94C" + + "\x03\uE952\x03\uE95B\x03\uEE02\x03\uEE05\x03\uEE07\x03\uEE21\x03\uEE23" + + "\x03\uEE24\x03\uEE26\x03\uEE26\x03\uEE29\x03\uEE29\x03\uEE2B\x03\uEE34" + + "\x03\uEE36\x03\uEE39\x03\uEE3B\x03\uEE3B\x03\uEE3D\x03\uEE3D\x03\uEE44" + + "\x03\uEE44\x03\uEE49\x03\uEE49\x03\uEE4B\x03\uEE4B\x03\uEE4D\x03\uEE4D" + + "\x03\uEE4F\x03\uEE51\x03\uEE53\x03\uEE54\x03\uEE56\x03\uEE56\x03\uEE59" + + "\x03\uEE59\x03\uEE5B\x03\uEE5B\x03\uEE5D\x03\uEE5D\x03\uEE5F\x03\uEE5F" + + "\x03\uEE61\x03\uEE61\x03\uEE63\x03\uEE64\x03\uEE66\x03\uEE66\x03\uEE69" + + "\x03\uEE6C\x03\uEE6E\x03\uEE74\x03\uEE76\x03\uEE79\x03\uEE7B\x03\uEE7E" + + "\x03\uEE80\x03\uEE80\x03\uEE82\x03\uEE8B\x03\uEE8D\x03\uEE9D\x03\uEEA3" + + "\x03\uEEA5\x03\uEEA7\x03\uEEAB\x03\uEEAD\x03\uEEBD\x03\x02\x04\uA6D8\x04" + + "\uA702\x04\uB736\x04\uB742\x04\uB81F\x04\uB822\x04\uCEA3\x04\uF802\x04" + + "\uFA1F\x04\x03\x10\x03\x10\"\x10\x81\x10\u0102\x10\u01F1\x10\u0240\x02" + + "C\x02\\\x02c\x02|\x02\xAC\x02\xAC\x02\xB7\x02\xB7\x02\xBC\x02\xBC\x02" + + "\xC2\x02\xD8\x02\xDA\x02\xF8\x02\xFA\x02\u02C3\x02\u02C8\x02\u02D3\x02" + + "\u02E2\x02\u02E6\x02\u02EE\x02\u02EE\x02\u02F0\x02\u02F0\x02\u0372\x02" + + "\u0376\x02\u0378\x02\u0379\x02\u037C\x02\u037F\x02\u0381\x02\u0381\x02" + + "\u0388\x02\u0388\x02\u038A\x02\u038C\x02\u038E\x02\u038E\x02\u0390\x02" + + "\u03A3\x02\u03A5\x02\u03F7\x02\u03F9\x02\u0483\x02\u048C\x02\u0531\x02" + + "\u0533\x02\u0558\x02\u055B\x02\u055B\x02\u0563\x02\u0589\x02\u05D2\x02" + + "\u05EC\x02\u05F2\x02\u05F4\x02\u0622\x02\u064C\x02\u0670\x02\u0671\x02" + + "\u0673\x02\u06D5\x02\u06D7\x02\u06D7\x02\u06E7\x02\u06E8\x02\u06F0\x02" + + "\u06F1\x02\u06FC\x02\u06FE\x02\u0701\x02\u0701\x02\u0712\x02\u0712\x02" + + "\u0714\x02\u0731\x02\u074F\x02\u07A7\x02\u07B3\x02\u07B3\x02\u07CC\x02" + + "\u07EC\x02\u07F6\x02\u07F7\x02\u07FC\x02\u07FC\x02\u0802\x02\u0817\x02" + + "\u081C\x02\u081C\x02\u0826\x02\u0826\x02\u082A\x02\u082A\x02\u0842\x02" + + "\u085A\x02\u08A2\x02\u08B6\x02\u08B8\x02\u08BF\x02\u0906\x02\u093B\x02" + + "\u093F\x02\u093F\x02\u0952\x02\u0952\x02\u095A\x02\u0963\x02\u0973\x02" + + "\u0982\x02\u0987\x02\u098E\x02\u0991\x02\u0992\x02\u0995\x02\u09AA\x02" + + "\u09AC\x02\u09B2\x02\u09B4\x02\u09B4\x02\u09B8\x02\u09BB\x02\u09BF\x02" + + "\u09BF\x02\u09D0\x02\u09D0\x02\u09DE\x02\u09DF\x02\u09E1\x02\u09E3\x02" + + "\u09F2\x02\u09F3\x02\u0A07\x02\u0A0C\x02\u0A11\x02\u0A12\x02\u0A15\x02" + + "\u0A2A\x02\u0A2C\x02\u0A32\x02\u0A34\x02\u0A35\x02\u0A37\x02\u0A38\x02" + + "\u0A3A\x02\u0A3B\x02\u0A5B\x02\u0A5E\x02\u0A60\x02\u0A60\x02\u0A74\x02" + + "\u0A76\x02\u0A87\x02\u0A8F\x02\u0A91\x02\u0A93\x02\u0A95\x02\u0AAA\x02" + + "\u0AAC\x02\u0AB2\x02\u0AB4\x02\u0AB5\x02\u0AB7\x02\u0ABB\x02\u0ABF\x02" + + "\u0ABF\x02\u0AD2\x02\u0AD2\x02\u0AE2\x02\u0AE3\x02\u0AFB\x02\u0AFB\x02" + + "\u0B07\x02\u0B0E\x02\u0B11\x02\u0B12\x02\u0B15\x02\u0B2A\x02\u0B2C\x02" + + "\u0B32\x02\u0B34\x02\u0B35\x02\u0B37\x02\u0B3B\x02\u0B3F\x02\u0B3F\x02" + + "\u0B5E\x02\u0B5F\x02\u0B61\x02\u0B63\x02\u0B73\x02\u0B73\x02\u0B85\x02" + + "\u0B85\x02\u0B87\x02\u0B8C\x02\u0B90\x02\u0B92\x02\u0B94\x02\u0B97\x02" + + "\u0B9B\x02\u0B9C\x02\u0B9E\x02\u0B9E\x02\u0BA0\x02\u0BA1\x02\u0BA5\x02" + + "\u0BA6\x02\u0BAA\x02\u0BAC\x02\u0BB0\x02\u0BBB\x02\u0BD2\x02\u0BD2\x02" + + "\u0C07\x02\u0C0E\x02\u0C10\x02\u0C12\x02\u0C14\x02\u0C2A\x02\u0C2C\x02" + + "\u0C3B\x02\u0C3F\x02\u0C3F\x02\u0C5A\x02\u0C5C\x02\u0C62\x02\u0C63\x02" + + "\u0C82\x02\u0C82\x02\u0C87\x02\u0C8E\x02\u0C90\x02\u0C92\x02\u0C94\x02" + + "\u0CAA\x02\u0CAC\x02\u0CB5\x02\u0CB7\x02\u0CBB\x02\u0CBF\x02\u0CBF\x02" + + "\u0CE0\x02\u0CE0\x02\u0CE2\x02\u0CE3\x02\u0CF3\x02\u0CF4\x02\u0D07\x02" + + "\u0D0E\x02\u0D10\x02\u0D12\x02\u0D14\x02\u0D3C\x02\u0D3F\x02\u0D3F\x02" + + "\u0D50\x02\u0D50\x02\u0D56\x02\u0D58\x02\u0D61\x02\u0D63\x02\u0D7C\x02" + + "\u0D81\x02\u0D87\x02\u0D98\x02\u0D9C\x02\u0DB3\x02\u0DB5\x02\u0DBD\x02" + + "\u0DBF\x02\u0DBF\x02\u0DC2\x02\u0DC8\x02\u0E03\x02\u0E32\x02\u0E34\x02" + + "\u0E35\x02\u0E42\x02\u0E48\x02\u0E83\x02\u0E84\x02\u0E86\x02\u0E86\x02" + + "\u0E89\x02\u0E8A\x02\u0E8C\x02\u0E8C\x02\u0E8F\x02\u0E8F\x02\u0E96\x02" + + "\u0E99\x02\u0E9B\x02\u0EA1\x02\u0EA3\x02\u0EA5\x02\u0EA7\x02\u0EA7\x02" + + "\u0EA9\x02\u0EA9\x02\u0EAC\x02\u0EAD\x02\u0EAF\x02\u0EB2\x02\u0EB4\x02" + + "\u0EB5\x02\u0EBF\x02\u0EBF\x02\u0EC2\x02\u0EC6\x02\u0EC8\x02\u0EC8\x02" + + "\u0EDE\x02\u0EE1\x02\u0F02\x02\u0F02\x02\u0F42\x02\u0F49\x02\u0F4B\x02" + + "\u0F6E\x02\u0F8A\x02\u0F8E\x02\u1002\x02\u102C\x02\u1041\x02\u1041\x02" + + "\u1052\x02\u1057\x02\u105C\x02\u105F\x02\u1063\x02\u1063\x02\u1067\x02" + + "\u1068\x02\u1070\x02\u1072\x02\u1077\x02\u1083\x02\u1090\x02\u1090\x02" + + "\u10A2\x02\u10C7\x02\u10C9\x02\u10C9\x02\u10CF\x02\u10CF\x02\u10D2\x02" + + "\u10FC\x02\u10FE\x02\u124A\x02\u124C\x02\u124F\x02\u1252\x02\u1258\x02" + + "\u125A\x02\u125A\x02\u125C\x02\u125F\x02\u1262\x02\u128A\x02\u128C\x02" + + "\u128F\x02\u1292\x02\u12B2\x02\u12B4\x02\u12B7\x02\u12BA\x02\u12C0\x02" + + "\u12C2\x02\u12C2\x02\u12C4\x02\u12C7\x02\u12CA\x02\u12D8\x02\u12DA\x02" + + "\u1312\x02\u1314\x02\u1317\x02\u131A\x02\u135C\x02\u1382\x02\u1391\x02" + + "\u13A2\x02\u13F7\x02\u13FA\x02\u13FF\x02\u1403\x02\u166E\x02\u1671\x02" + + "\u1681\x02\u1683\x02\u169C\x02\u16A2\x02\u16EC\x02\u16F0\x02\u16FA\x02" + + "\u1702\x02\u170E\x02\u1710\x02\u1713\x02\u1722\x02\u1733\x02\u1742\x02" + + "\u1753\x02\u1762\x02\u176E\x02\u1770\x02\u1772\x02\u1782\x02\u17B5\x02" + + "\u17D9\x02\u17D9\x02\u17DE\x02\u17DE\x02\u1822\x02\u1879\x02\u1882\x02" + + "\u1886\x02\u1889\x02\u18AA\x02\u18AC\x02\u18AC\x02\u18B2\x02\u18F7\x02" + + "\u1902\x02\u1920\x02\u1952\x02\u196F\x02\u1972\x02\u1976\x02\u1982\x02" + + "\u19AD\x02\u19B2\x02\u19CB\x02\u1A02\x02\u1A18\x02\u1A22\x02\u1A56\x02" + + "\u1AA9\x02\u1AA9\x02\u1B07\x02\u1B35\x02\u1B47\x02\u1B4D\x02\u1B85\x02" + + "\u1BA2\x02\u1BB0\x02\u1BB1\x02\u1BBC\x02\u1BE7\x02\u1C02\x02\u1C25\x02" + + "\u1C4F\x02\u1C51\x02\u1C5C\x02\u1C7F\x02\u1C82\x02\u1C8A\x02\u1CEB\x02" + + "\u1CEE\x02\u1CF0\x02\u1CF3\x02\u1CF7\x02\u1CF8\x02\u1D02\x02\u1DC1\x02" + + "\u1E02\x02\u1F17\x02\u1F1A\x02\u1F1F\x02\u1F22\x02\u1F47\x02\u1F4A\x02" + + "\u1F4F\x02\u1F52\x02\u1F59\x02\u1F5B\x02\u1F5B\x02\u1F5D\x02\u1F5D\x02" + + "\u1F5F\x02\u1F5F\x02\u1F61\x02\u1F7F\x02\u1F82\x02\u1FB6\x02\u1FB8\x02" + + "\u1FBE\x02\u1FC0\x02\u1FC0\x02\u1FC4\x02\u1FC6\x02\u1FC8\x02\u1FCE\x02" + + "\u1FD2\x02\u1FD5\x02\u1FD8\x02\u1FDD\x02\u1FE2\x02\u1FEE\x02\u1FF4\x02" + + "\u1FF6\x02\u1FF8\x02\u1FFE\x02\u2073\x02\u2073\x02\u2081\x02\u2081\x02" + + "\u2092\x02\u209E\x02\u2104\x02\u2104\x02\u2109\x02\u2109\x02\u210C\x02" + + "\u2115\x02\u2117\x02\u2117\x02\u211B\x02\u211F\x02\u2126\x02\u2126\x02" + + "\u2128\x02\u2128\x02\u212A\x02\u212A\x02\u212C\x02\u212F\x02\u2131\x02" + + "\u213B\x02\u213E\x02\u2141\x02\u2147\x02\u214B\x02\u2150\x02\u2150\x02" + + "\u2162\x02\u218A\x02\u2C02\x02\u2C30\x02\u2C32\x02\u2C60\x02\u2C62\x02" + + "\u2CE6\x02\u2CED\x02\u2CF0\x02\u2CF4\x02\u2CF5\x02\u2D02\x02\u2D27\x02" + + "\u2D29\x02\u2D29\x02\u2D2F\x02\u2D2F\x02\u2D32\x02\u2D69\x02\u2D71\x02" + + "\u2D71\x02\u2D82\x02\u2D98\x02\u2DA2\x02\u2DA8\x02\u2DAA\x02\u2DB0\x02" + + "\u2DB2\x02\u2DB8\x02\u2DBA\x02\u2DC0\x02\u2DC2\x02\u2DC8\x02\u2DCA\x02" + + "\u2DD0\x02\u2DD2\x02\u2DD8\x02\u2DDA\x02\u2DE0\x02\u2E31\x02\u2E31\x02" + + "\u3007\x02\u3009\x02\u3023\x02\u302B\x02\u3033\x02\u3037\x02\u303A\x02" + + "\u303E\x02\u3043\x02\u3098\x02\u309F\x02\u30A1\x02\u30A3\x02\u30FC\x02" + + "\u30FE\x02\u3101\x02\u3107\x02\u312F\x02\u3133\x02\u3190\x02\u31A2\x02" + + "\u31BC\x02\u31F2\x02\u3201\x02\u3402\x02\u4DB7\x02\u4E02\x02\u9FD7\x02" + + "\uA002\x02\uA48E\x02\uA4D2\x02\uA4FF\x02\uA502\x02\uA60E\x02\uA612\x02" + + "\uA621\x02\uA62C\x02\uA62D\x02\uA642\x02\uA670\x02\uA681\x02\uA69F\x02" + + "\uA6A2\x02\uA6F1\x02\uA719\x02\uA721\x02\uA724\x02\uA78A\x02\uA78D\x02" + + "\uA7B0\x02\uA7B2\x02\uA7B9\x02\uA7F9\x02\uA803\x02\uA805\x02\uA807\x02" + + "\uA809\x02\uA80C\x02\uA80E\x02\uA824\x02\uA842\x02\uA875\x02\uA884\x02" + + "\uA8B5\x02\uA8F4\x02\uA8F9\x02\uA8FD\x02\uA8FD\x02\uA8FF\x02\uA8FF\x02" + + "\uA90C\x02\uA927\x02\uA932\x02\uA948\x02\uA962\x02\uA97E\x02\uA986\x02" + + "\uA9B4\x02\uA9D1\x02\uA9D1\x02\uA9E2\x02\uA9E6\x02\uA9E8\x02\uA9F1\x02" + + "\uA9FC\x02\uAA00\x02\uAA02\x02\uAA2A\x02\uAA42\x02\uAA44\x02\uAA46\x02" + + "\uAA4D\x02\uAA62\x02\uAA78\x02\uAA7C\x02\uAA7C\x02\uAA80\x02\uAAB1\x02" + + "\uAAB3\x02\uAAB3\x02\uAAB7\x02\uAAB8\x02\uAABB\x02\uAABF\x02\uAAC2\x02" + + "\uAAC2\x02\uAAC4\x02\uAAC4\x02\uAADD\x02\uAADF\x02\uAAE2\x02\uAAEC\x02" + + "\uAAF4\x02\uAAF6\x02\uAB03\x02\uAB08\x02\uAB0B\x02\uAB10\x02\uAB13\x02" + + "\uAB18\x02\uAB22\x02\uAB28\x02\uAB2A\x02\uAB30\x02\uAB32\x02\uAB5C\x02" + + "\uAB5E\x02\uAB67\x02\uAB72\x02\uABE4\x02\uAC02\x02\uD7A5\x02\uD7B2\x02" + + "\uD7C8\x02\uD7CD\x02\uD7FD\x02\uF902\x02\uFA6F\x02\uFA72\x02\uFADB\x02" + + "\uFB02\x02\uFB08\x02\uFB15\x02\uFB19\x02\uFB1F\x02\uFB1F\x02\uFB21\x02" + + "\uFB2A\x02\uFB2C\x02\uFB38\x02\uFB3A\x02\uFB3E\x02\uFB40\x02\uFB40\x02" + + "\uFB42\x02\uFB43\x02\uFB45\x02\uFB46\x02\uFB48\x02\uFBB3\x02\uFBD5\x02" + + "\uFD3F\x02\uFD52\x02\uFD91\x02\uFD94\x02\uFDC9\x02\uFDF2\x02\uFDFD\x02" + + "\uFE72\x02\uFE76\x02\uFE78\x02\uFEFE\x02\uFF23\x02\uFF3C\x02\uFF43\x02" + + "\uFF5C\x02\uFF68\x02\uFFC0\x02\uFFC4\x02\uFFC9\x02\uFFCC\x02\uFFD1\x02" + + "\uFFD4\x02\uFFD9\x02\uFFDC\x02\uFFDE\x02\x02\x03\r\x03\x0F\x03(\x03*\x03" + + "<\x03>\x03?\x03A\x03O\x03R\x03_\x03\x82\x03\xFC\x03\u0142\x03\u0176\x03" + + "\u0282\x03\u029E\x03\u02A2\x03\u02D2\x03\u0302\x03\u0321\x03\u0332\x03" + + "\u034C\x03\u0352\x03\u0377\x03\u0382\x03\u039F\x03\u03A2\x03\u03C5\x03" + + "\u03CA\x03\u03D1\x03\u03D3\x03\u03D7\x03\u0402\x03\u049F\x03\u04B2\x03" + + "\u04D5\x03\u04DA\x03\u04FD\x03\u0502\x03\u0529\x03\u0532\x03\u0565\x03" + + "\u0602\x03\u0738\x03\u0742\x03\u0757\x03\u0762\x03\u0769\x03\u0802\x03" + + "\u0807\x03\u080A\x03\u080A\x03\u080C\x03\u0837\x03\u0839\x03\u083A\x03" + + "\u083E\x03\u083E\x03\u0841\x03\u0857\x03\u0862\x03\u0878\x03\u0882\x03" + + "\u08A0\x03\u08E2\x03\u08F4\x03\u08F6\x03\u08F7\x03\u0902\x03\u0917\x03" + + "\u0922\x03\u093B\x03\u0982\x03\u09B9\x03\u09C0\x03\u09C1\x03\u0A02\x03" + + "\u0A02\x03\u0A12\x03\u0A15\x03\u0A17\x03\u0A19\x03\u0A1B\x03\u0A35\x03" + + "\u0A62\x03\u0A7E\x03\u0A82\x03\u0A9E\x03\u0AC2\x03\u0AC9\x03\u0ACB\x03" + + "\u0AE6\x03\u0B02\x03\u0B37\x03\u0B42\x03\u0B57\x03\u0B62\x03\u0B74\x03" + + "\u0B82\x03\u0B93\x03\u0C02\x03\u0C4A\x03\u0C82\x03\u0CB4\x03\u0CC2\x03" + + "\u0CF4\x03\u1005\x03\u1039\x03\u1085\x03\u10B1\x03\u10D2\x03\u10EA\x03" + + "\u1105\x03\u1128\x03\u1152\x03\u1174\x03\u1178\x03\u1178\x03\u1185\x03" + + "\u11B4\x03\u11C3\x03\u11C6\x03\u11DC\x03\u11DC\x03\u11DE\x03\u11DE\x03" + + "\u1202\x03\u1213\x03\u1215\x03\u122D\x03\u1282\x03\u1288\x03\u128A\x03" + + "\u128A\x03\u128C\x03\u128F\x03\u1291\x03\u129F\x03\u12A1\x03\u12AA\x03" + + "\u12B2\x03\u12E0\x03\u1307\x03\u130E\x03\u1311\x03\u1312\x03\u1315\x03" + + "\u132A\x03\u132C\x03\u1332\x03\u1334\x03\u1335\x03\u1337\x03\u133B\x03" + + "\u133F\x03\u133F\x03\u1352\x03\u1352\x03\u135F\x03\u1363\x03\u1402\x03" + + "\u1436\x03\u1449\x03\u144C\x03\u1482\x03\u14B1\x03\u14C6\x03\u14C7\x03" + + "\u14C9\x03\u14C9\x03\u1582\x03\u15B0\x03\u15DA\x03\u15DD\x03\u1602\x03" + + "\u1631\x03\u1646\x03\u1646\x03\u1682\x03\u16AC\x03\u1702\x03\u171B\x03" + + "\u18A2\x03\u18E1\x03\u1901\x03\u1901\x03\u1AC2\x03\u1AFA\x03\u1C02\x03" + + "\u1C0A\x03\u1C0C\x03\u1C30\x03\u1C42\x03\u1C42\x03\u1C74\x03\u1C91\x03" + + "\u2002\x03\u239B\x03\u2402\x03\u2470\x03\u2482\x03\u2545\x03\u3002\x03" + + "\u3430\x03\u4402\x03\u4648\x03\u6802\x03\u6A3A\x03\u6A42\x03\u6A60\x03" + + "\u6AD2\x03\u6AEF\x03\u6B02\x03\u6B31\x03\u6B42\x03\u6B45\x03\u6B65\x03" + + "\u6B79\x03\u6B7F\x03\u6B91\x03\u6F02\x03\u6F46\x03\u6F52\x03\u6F52\x03" + + "\u6F95\x03\u6FA1\x03\u6FE2\x03\u6FE2\x03\u7002\x03\u87EE\x03\u8802\x03" + + "\u8AF4\x03\uB002\x03\uB003\x03\uBC02\x03\uBC6C\x03\uBC72\x03\uBC7E\x03" + + "\uBC82\x03\uBC8A\x03\uBC92\x03\uBC9B\x03\uD402\x03\uD456\x03\uD458\x03" + + "\uD49E\x03\uD4A0\x03\uD4A1\x03\uD4A4\x03\uD4A4\x03\uD4A7\x03\uD4A8\x03" + + "\uD4AB\x03\uD4AE\x03\uD4B0\x03\uD4BB\x03\uD4BD\x03\uD4BD\x03\uD4BF\x03" + + "\uD4C5\x03\uD4C7\x03\uD507\x03\uD509\x03\uD50C\x03\uD50F\x03\uD516\x03" + + "\uD518\x03\uD51E\x03\uD520\x03\uD53B\x03\uD53D\x03\uD540\x03\uD542\x03" + + "\uD546\x03\uD548\x03\uD548"; + XPathLexer$1._serializedATNSegment1 = "\x03\uD54C\x03\uD552\x03\uD554\x03\uD6A7\x03\uD6AA\x03\uD6C2\x03\uD6C4" + + "\x03\uD6DC\x03\uD6DE\x03\uD6FC\x03\uD6FE\x03\uD716\x03\uD718\x03\uD736" + + "\x03\uD738\x03\uD750\x03\uD752\x03\uD770\x03\uD772\x03\uD78A\x03\uD78C" + + "\x03\uD7AA\x03\uD7AC\x03\uD7C4\x03\uD7C6\x03\uD7CD\x03\uE802\x03\uE8C6" + + "\x03\uE902\x03\uE945\x03\uEE02\x03\uEE05\x03\uEE07\x03\uEE21\x03\uEE23" + + "\x03\uEE24\x03\uEE26\x03\uEE26\x03\uEE29\x03\uEE29\x03\uEE2B\x03\uEE34" + + "\x03\uEE36\x03\uEE39\x03\uEE3B\x03\uEE3B\x03\uEE3D\x03\uEE3D\x03\uEE44" + + "\x03\uEE44\x03\uEE49\x03\uEE49\x03\uEE4B\x03\uEE4B\x03\uEE4D\x03\uEE4D" + + "\x03\uEE4F\x03\uEE51\x03\uEE53\x03\uEE54\x03\uEE56\x03\uEE56\x03\uEE59" + + "\x03\uEE59\x03\uEE5B\x03\uEE5B\x03\uEE5D\x03\uEE5D\x03\uEE5F\x03\uEE5F" + + "\x03\uEE61\x03\uEE61\x03\uEE63\x03\uEE64\x03\uEE66\x03\uEE66\x03\uEE69" + + "\x03\uEE6C\x03\uEE6E\x03\uEE74\x03\uEE76\x03\uEE79\x03\uEE7B\x03\uEE7E" + + "\x03\uEE80\x03\uEE80\x03\uEE82\x03\uEE8B\x03\uEE8D\x03\uEE9D\x03\uEEA3" + + "\x03\uEEA5\x03\uEEA7\x03\uEEAB\x03\uEEAD\x03\uEEBD\x03\x02\x04\uA6D8\x04" + + "\uA702\x04\uB736\x04\uB742\x04\uB81F\x04\uB822\x04\uCEA3\x04\uF802\x04" + + "\uFA1F\x041\x02\x03\x03\x02\x02\x02\x02\x05\x03\x02\x02\x02\x02\x07\x03" + + "\x02\x02\x02\x02\t\x03\x02\x02\x02\x02\v\x03\x02\x02\x02\x02\x11\x03\x02" + + "\x02\x02\x03\x13\x03\x02\x02\x02\x05\x16\x03\x02\x02\x02\x07\x18\x03\x02" + + "\x02\x02\t\x1A\x03\x02\x02\x02\v\x1C\x03\x02\x02\x02\r%\x03\x02\x02\x02" + + "\x0F\'\x03\x02\x02\x02\x11)\x03\x02\x02\x02\x13\x14\x071\x02\x02\x14\x15" + + "\x071\x02\x02\x15\x04\x03\x02\x02\x02\x16\x17\x071\x02\x02\x17\x06\x03" + + "\x02\x02\x02\x18\x19\x07,\x02\x02\x19\b\x03\x02\x02\x02\x1A\x1B\x07#\x02" + + "\x02\x1B\n\x03\x02\x02\x02\x1C \x05\x0F\b\x02\x1D\x1F\x05\r\x07\x02\x1E" + + "\x1D\x03\x02\x02\x02\x1F\"\x03\x02\x02\x02 \x1E\x03\x02\x02\x02 !\x03" + + "\x02\x02\x02!#\x03\x02\x02\x02\" \x03\x02\x02\x02#$\b\x06\x02\x02$\f\x03" + + "\x02\x02\x02%&\t\x02\x02\x02&\x0E\x03\x02\x02\x02\'(\t\x03\x02\x02(\x10" + + "\x03\x02\x02\x02)-\x07)\x02\x02*,\v\x02\x02\x02+*\x03\x02\x02\x02,/\x03" + + "\x02\x02\x02-.\x03\x02\x02\x02-+\x03\x02\x02\x02.0\x03\x02\x02\x02/-\x03" + + "\x02\x02\x0201\x07)\x02\x021\x12\x03\x02\x02\x02\x05\x02 -\x03\x03\x06" + + "\x02"; + XPathLexer$1._serializedATN = Utils.join([ + XPathLexer$1._serializedATNSegment0, + XPathLexer$1._serializedATNSegment1, + ], ""); + + return XPathLexer; +} + +var XPathLexerErrorListener = {}; + +var hasRequiredXPathLexerErrorListener; + +function requireXPathLexerErrorListener () { + if (hasRequiredXPathLexerErrorListener) return XPathLexerErrorListener; + hasRequiredXPathLexerErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathLexerErrorListener && XPathLexerErrorListener.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathLexerErrorListener, "__esModule", { value: true }); + XPathLexerErrorListener.XPathLexerErrorListener = void 0; + const Decorators_1 = requireDecorators(); + let XPathLexerErrorListener$1 = class XPathLexerErrorListener { + syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) { + // intentionally empty + } + }; + __decorate([ + Decorators_1.Override + ], XPathLexerErrorListener$1.prototype, "syntaxError", null); + XPathLexerErrorListener.XPathLexerErrorListener = XPathLexerErrorListener$1; + + return XPathLexerErrorListener; +} + +var XPathRuleAnywhereElement = {}; + +var XPathElement = {}; + +var hasRequiredXPathElement; + +function requireXPathElement () { + if (hasRequiredXPathElement) return XPathElement; + hasRequiredXPathElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathElement && XPathElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathElement, "__esModule", { value: true }); + XPathElement.XPathElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + let XPathElement$1 = class XPathElement { + /** Construct element like `/ID` or `ID` or `/*` etc... + * op is null if just node + */ + constructor(nodeName) { + this.nodeName = nodeName; + this.invert = false; + } + toString() { + let inv = this.invert ? "!" : ""; + let className = Object.constructor.name; + return className + "[" + inv + this.nodeName + "]"; + } + }; + __decorate([ + Decorators_1.Override + ], XPathElement$1.prototype, "toString", null); + XPathElement.XPathElement = XPathElement$1; + + return XPathElement; +} + +var hasRequiredXPathRuleAnywhereElement; + +function requireXPathRuleAnywhereElement () { + if (hasRequiredXPathRuleAnywhereElement) return XPathRuleAnywhereElement; + hasRequiredXPathRuleAnywhereElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathRuleAnywhereElement && XPathRuleAnywhereElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathRuleAnywhereElement, "__esModule", { value: true }); + XPathRuleAnywhereElement.XPathRuleAnywhereElement = void 0; + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const XPathElement_1 = requireXPathElement(); + /** + * Either `ID` at start of path or `...//ID` in middle of path. + */ + let XPathRuleAnywhereElement$1 = class XPathRuleAnywhereElement extends XPathElement_1.XPathElement { + constructor(ruleName, ruleIndex) { + super(ruleName); + this.ruleIndex = ruleIndex; + } + evaluate(t) { + return Trees_1.Trees.findAllRuleNodes(t, this.ruleIndex); + } + }; + __decorate([ + Decorators_1.Override + ], XPathRuleAnywhereElement$1.prototype, "evaluate", null); + XPathRuleAnywhereElement.XPathRuleAnywhereElement = XPathRuleAnywhereElement$1; + + return XPathRuleAnywhereElement; +} + +var XPathRuleElement = {}; + +var hasRequiredXPathRuleElement; + +function requireXPathRuleElement () { + if (hasRequiredXPathRuleElement) return XPathRuleElement; + hasRequiredXPathRuleElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathRuleElement && XPathRuleElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathRuleElement, "__esModule", { value: true }); + XPathRuleElement.XPathRuleElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const ParserRuleContext_1 = requireParserRuleContext(); + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const XPathElement_1 = requireXPathElement(); + let XPathRuleElement$1 = class XPathRuleElement extends XPathElement_1.XPathElement { + constructor(ruleName, ruleIndex) { + super(ruleName); + this.ruleIndex = ruleIndex; + } + evaluate(t) { + // return all children of t that match nodeName + let nodes = []; + for (let c of Trees_1.Trees.getChildren(t)) { + if (c instanceof ParserRuleContext_1.ParserRuleContext) { + if ((c.ruleIndex === this.ruleIndex && !this.invert) || + (c.ruleIndex !== this.ruleIndex && this.invert)) { + nodes.push(c); + } + } + } + return nodes; + } + }; + __decorate([ + Decorators_1.Override + ], XPathRuleElement$1.prototype, "evaluate", null); + XPathRuleElement.XPathRuleElement = XPathRuleElement$1; + + return XPathRuleElement; +} + +var XPathTokenAnywhereElement = {}; + +var hasRequiredXPathTokenAnywhereElement; + +function requireXPathTokenAnywhereElement () { + if (hasRequiredXPathTokenAnywhereElement) return XPathTokenAnywhereElement; + hasRequiredXPathTokenAnywhereElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathTokenAnywhereElement && XPathTokenAnywhereElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathTokenAnywhereElement, "__esModule", { value: true }); + XPathTokenAnywhereElement.XPathTokenAnywhereElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const XPathElement_1 = requireXPathElement(); + let XPathTokenAnywhereElement$1 = class XPathTokenAnywhereElement extends XPathElement_1.XPathElement { + constructor(tokenName, tokenType) { + super(tokenName); + this.tokenType = tokenType; + } + evaluate(t) { + return Trees_1.Trees.findAllTokenNodes(t, this.tokenType); + } + }; + __decorate([ + Decorators_1.Override + ], XPathTokenAnywhereElement$1.prototype, "evaluate", null); + XPathTokenAnywhereElement.XPathTokenAnywhereElement = XPathTokenAnywhereElement$1; + + return XPathTokenAnywhereElement; +} + +var XPathTokenElement = {}; + +var hasRequiredXPathTokenElement; + +function requireXPathTokenElement () { + if (hasRequiredXPathTokenElement) return XPathTokenElement; + hasRequiredXPathTokenElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathTokenElement && XPathTokenElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathTokenElement, "__esModule", { value: true }); + XPathTokenElement.XPathTokenElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + const TerminalNode_1 = requireTerminalNode(); + const Trees_1 = requireTrees(); + const XPathElement_1 = requireXPathElement(); + let XPathTokenElement$1 = class XPathTokenElement extends XPathElement_1.XPathElement { + constructor(tokenName, tokenType) { + super(tokenName); + this.tokenType = tokenType; + } + evaluate(t) { + // return all children of t that match nodeName + let nodes = []; + for (let c of Trees_1.Trees.getChildren(t)) { + if (c instanceof TerminalNode_1.TerminalNode) { + if ((c.symbol.type === this.tokenType && !this.invert) || + (c.symbol.type !== this.tokenType && this.invert)) { + nodes.push(c); + } + } + } + return nodes; + } + }; + __decorate([ + Decorators_1.Override + ], XPathTokenElement$1.prototype, "evaluate", null); + XPathTokenElement.XPathTokenElement = XPathTokenElement$1; + + return XPathTokenElement; +} + +var XPathWildcardAnywhereElement = {}; + +var hasRequiredXPathWildcardAnywhereElement; + +function requireXPathWildcardAnywhereElement () { + if (hasRequiredXPathWildcardAnywhereElement) return XPathWildcardAnywhereElement; + hasRequiredXPathWildcardAnywhereElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathWildcardAnywhereElement && XPathWildcardAnywhereElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathWildcardAnywhereElement, "__esModule", { value: true }); + XPathWildcardAnywhereElement.XPathWildcardAnywhereElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const XPath_1 = requireXPath(); + const XPathElement_1 = requireXPathElement(); + let XPathWildcardAnywhereElement$1 = class XPathWildcardAnywhereElement extends XPathElement_1.XPathElement { + constructor() { + super(XPath_1.XPath.WILDCARD); + } + evaluate(t) { + if (this.invert) { + // !* is weird but valid (empty) + return []; + } + return Trees_1.Trees.getDescendants(t); + } + }; + __decorate([ + Decorators_1.Override + ], XPathWildcardAnywhereElement$1.prototype, "evaluate", null); + XPathWildcardAnywhereElement.XPathWildcardAnywhereElement = XPathWildcardAnywhereElement$1; + + return XPathWildcardAnywhereElement; +} + +var XPathWildcardElement = {}; + +var hasRequiredXPathWildcardElement; + +function requireXPathWildcardElement () { + if (hasRequiredXPathWildcardElement) return XPathWildcardElement; + hasRequiredXPathWildcardElement = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (XPathWildcardElement && XPathWildcardElement.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(XPathWildcardElement, "__esModule", { value: true }); + XPathWildcardElement.XPathWildcardElement = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + const Trees_1 = requireTrees(); + const XPath_1 = requireXPath(); + const XPathElement_1 = requireXPathElement(); + let XPathWildcardElement$1 = class XPathWildcardElement extends XPathElement_1.XPathElement { + constructor() { + super(XPath_1.XPath.WILDCARD); + } + evaluate(t) { + let kids = []; + if (this.invert) { + // !* is weird but valid (empty) + return kids; + } + for (let c of Trees_1.Trees.getChildren(t)) { + kids.push(c); + } + return kids; + } + }; + __decorate([ + Decorators_1.Override + ], XPathWildcardElement$1.prototype, "evaluate", null); + XPathWildcardElement.XPathWildcardElement = XPathWildcardElement$1; + + return XPathWildcardElement; +} + +var hasRequiredXPath; + +function requireXPath () { + if (hasRequiredXPath) return XPath; + hasRequiredXPath = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(XPath, "__esModule", { value: true }); + XPath.XPath = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:46.4373888-07:00 + const CharStreams_1 = requireCharStreams(); + const CommonTokenStream_1 = requireCommonTokenStream(); + const LexerNoViableAltException_1 = requireLexerNoViableAltException(); + const ParserRuleContext_1 = requireParserRuleContext(); + const Token_1 = requireToken(); + const XPathLexer_1 = requireXPathLexer(); + const XPathLexerErrorListener_1 = requireXPathLexerErrorListener(); + const XPathRuleAnywhereElement_1 = requireXPathRuleAnywhereElement(); + const XPathRuleElement_1 = requireXPathRuleElement(); + const XPathTokenAnywhereElement_1 = requireXPathTokenAnywhereElement(); + const XPathTokenElement_1 = requireXPathTokenElement(); + const XPathWildcardAnywhereElement_1 = requireXPathWildcardAnywhereElement(); + const XPathWildcardElement_1 = requireXPathWildcardElement(); + /** + * Represent a subset of XPath XML path syntax for use in identifying nodes in + * parse trees. + * + * Split path into words and separators `/` and `//` via ANTLR + * itself then walk path elements from left to right. At each separator-word + * pair, find set of nodes. Next stage uses those as work list. + * + * The basic interface is + * {@link XPath#findAll ParseTree.findAll}`(tree, pathString, parser)`. + * But that is just shorthand for: + * + * ``` + * let p = new XPath(parser, pathString); + * return p.evaluate(tree); + * ``` + * + * See `TestXPath` for descriptions. In short, this + * allows operators: + * + * | | | + * | --- | --- | + * | `/` | root | + * | `//` | anywhere | + * | `!` | invert; this much appear directly after root or anywhere operator | + * + * and path elements: + * + * | | | + * | --- | --- | + * | `ID` | token name | + * | `'string'` | any string literal token from the grammar | + * | `expr` | rule name | + * | `*` | wildcard matching any node | + * + * Whitespace is not allowed. + */ + let XPath$1 = class XPath { + constructor(parser, path) { + this.parser = parser; + this.path = path; + this.elements = this.split(path); + // console.log(this.elements.toString()); + } + // TODO: check for invalid token/rule names, bad syntax + split(path) { + let lexer = new XPathLexer_1.XPathLexer(CharStreams_1.CharStreams.fromString(path)); + lexer.recover = (e) => { throw e; }; + lexer.removeErrorListeners(); + lexer.addErrorListener(new XPathLexerErrorListener_1.XPathLexerErrorListener()); + let tokenStream = new CommonTokenStream_1.CommonTokenStream(lexer); + try { + tokenStream.fill(); + } + catch (e) { + if (e instanceof LexerNoViableAltException_1.LexerNoViableAltException) { + let pos = lexer.charPositionInLine; + let msg = "Invalid tokens or characters at index " + pos + " in path '" + path + "' -- " + e.message; + throw new RangeError(msg); + } + throw e; + } + let tokens = tokenStream.getTokens(); + // console.log("path=" + path + "=>" + tokens); + let elements = []; + let n = tokens.length; + let i = 0; + loop: while (i < n) { + let el = tokens[i]; + let next; + switch (el.type) { + case XPathLexer_1.XPathLexer.ROOT: + case XPathLexer_1.XPathLexer.ANYWHERE: + let anywhere = el.type === XPathLexer_1.XPathLexer.ANYWHERE; + i++; + next = tokens[i]; + let invert = next.type === XPathLexer_1.XPathLexer.BANG; + if (invert) { + i++; + next = tokens[i]; + } + let pathElement = this.getXPathElement(next, anywhere); + pathElement.invert = invert; + elements.push(pathElement); + i++; + break; + case XPathLexer_1.XPathLexer.TOKEN_REF: + case XPathLexer_1.XPathLexer.RULE_REF: + case XPathLexer_1.XPathLexer.WILDCARD: + elements.push(this.getXPathElement(el, false)); + i++; + break; + case Token_1.Token.EOF: + break loop; + default: + throw new Error("Unknowth path element " + el); + } + } + return elements; + } + /** + * Convert word like `*` or `ID` or `expr` to a path + * element. `anywhere` is `true` if `//` precedes the + * word. + */ + getXPathElement(wordToken, anywhere) { + if (wordToken.type === Token_1.Token.EOF) { + throw new Error("Missing path element at end of path"); + } + let word = wordToken.text; + if (word == null) { + throw new Error("Expected wordToken to have text content."); + } + let ttype = this.parser.getTokenType(word); + let ruleIndex = this.parser.getRuleIndex(word); + switch (wordToken.type) { + case XPathLexer_1.XPathLexer.WILDCARD: + return anywhere ? + new XPathWildcardAnywhereElement_1.XPathWildcardAnywhereElement() : + new XPathWildcardElement_1.XPathWildcardElement(); + case XPathLexer_1.XPathLexer.TOKEN_REF: + case XPathLexer_1.XPathLexer.STRING: + if (ttype === Token_1.Token.INVALID_TYPE) { + throw new Error(word + " at index " + + wordToken.startIndex + + " isn't a valid token name"); + } + return anywhere ? + new XPathTokenAnywhereElement_1.XPathTokenAnywhereElement(word, ttype) : + new XPathTokenElement_1.XPathTokenElement(word, ttype); + default: + if (ruleIndex === -1) { + throw new Error(word + " at index " + + wordToken.startIndex + + " isn't a valid rule name"); + } + return anywhere ? + new XPathRuleAnywhereElement_1.XPathRuleAnywhereElement(word, ruleIndex) : + new XPathRuleElement_1.XPathRuleElement(word, ruleIndex); + } + } + static findAll(tree, xpath, parser) { + let p = new XPath(parser, xpath); + return p.evaluate(tree); + } + /** + * Return a list of all nodes starting at `t` as root that satisfy the + * path. The root `/` is relative to the node passed to {@link evaluate}. + */ + evaluate(t) { + let dummyRoot = new ParserRuleContext_1.ParserRuleContext(); + dummyRoot.addChild(t); + let work = new Set([dummyRoot]); + let i = 0; + while (i < this.elements.length) { + let next = new Set(); + for (let node of work) { + if (node.childCount > 0) { + // only try to match next element if it has children + // e.g., //func/*/stat might have a token node for which + // we can't go looking for stat nodes. + let matching = this.elements[i].evaluate(node); + matching.forEach(next.add, next); + } + } + i++; + work = next; + } + return work; + } + }; + XPath.XPath = XPath$1; + XPath$1.WILDCARD = "*"; // word not operator/separator + XPath$1.NOT = "!"; // word for invert operator + + return XPath; +} + +var hasRequiredParseTreePattern; + +function requireParseTreePattern () { + if (hasRequiredParseTreePattern) return ParseTreePattern; + hasRequiredParseTreePattern = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParseTreePattern && ParseTreePattern.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParseTreePattern && ParseTreePattern.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ParseTreePattern, "__esModule", { value: true }); + ParseTreePattern.ParseTreePattern = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const Decorators_1 = requireDecorators(); + const XPath_1 = requireXPath(); + /** + * A pattern like ` = ;` converted to a {@link ParseTree} by + * {@link ParseTreePatternMatcher#compile(String, int)}. + */ + let ParseTreePattern$1 = class ParseTreePattern { + /** + * Construct a new instance of the {@link ParseTreePattern} class. + * + * @param matcher The {@link ParseTreePatternMatcher} which created this + * tree pattern. + * @param pattern The tree pattern in concrete syntax form. + * @param patternRuleIndex The parser rule which serves as the root of the + * tree pattern. + * @param patternTree The tree pattern in {@link ParseTree} form. + */ + constructor(matcher, pattern, patternRuleIndex, patternTree) { + this._matcher = matcher; + this._patternRuleIndex = patternRuleIndex; + this._pattern = pattern; + this._patternTree = patternTree; + } + /** + * Match a specific parse tree against this tree pattern. + * + * @param tree The parse tree to match against this tree pattern. + * @returns A {@link ParseTreeMatch} object describing the result of the + * match operation. The `ParseTreeMatch.succeeded` method can be + * used to determine whether or not the match was successful. + */ + match(tree) { + return this._matcher.match(tree, this); + } + /** + * Determine whether or not a parse tree matches this tree pattern. + * + * @param tree The parse tree to match against this tree pattern. + * @returns `true` if `tree` is a match for the current tree + * pattern; otherwise, `false`. + */ + matches(tree) { + return this._matcher.match(tree, this).succeeded; + } + /** + * Find all nodes using XPath and then try to match those subtrees against + * this tree pattern. + * + * @param tree The {@link ParseTree} to match against this pattern. + * @param xpath An expression matching the nodes + * + * @returns A collection of {@link ParseTreeMatch} objects describing the + * successful matches. Unsuccessful matches are omitted from the result, + * regardless of the reason for the failure. + */ + findAll(tree, xpath) { + let subtrees = XPath_1.XPath.findAll(tree, xpath, this._matcher.parser); + let matches = []; + for (let t of subtrees) { + let match = this.match(t); + if (match.succeeded) { + matches.push(match); + } + } + return matches; + } + /** + * Get the {@link ParseTreePatternMatcher} which created this tree pattern. + * + * @returns The {@link ParseTreePatternMatcher} which created this tree + * pattern. + */ + get matcher() { + return this._matcher; + } + /** + * Get the tree pattern in concrete syntax form. + * + * @returns The tree pattern in concrete syntax form. + */ + get pattern() { + return this._pattern; + } + /** + * Get the parser rule which serves as the outermost rule for the tree + * pattern. + * + * @returns The parser rule which serves as the outermost rule for the tree + * pattern. + */ + get patternRuleIndex() { + return this._patternRuleIndex; + } + /** + * Get the tree pattern as a {@link ParseTree}. The rule and token tags from + * the pattern are present in the parse tree as terminal nodes with a symbol + * of type {@link RuleTagToken} or {@link TokenTagToken}. + * + * @returns The tree pattern as a {@link ParseTree}. + */ + get patternTree() { + return this._patternTree; + } + }; + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "_pattern", void 0); + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "_patternTree", void 0); + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "_matcher", void 0); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], ParseTreePattern$1.prototype, "match", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], ParseTreePattern$1.prototype, "matches", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], ParseTreePattern$1.prototype, "findAll", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "matcher", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "pattern", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreePattern$1.prototype, "patternTree", null); + ParseTreePattern$1 = __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull) + ], ParseTreePattern$1); + ParseTreePattern.ParseTreePattern = ParseTreePattern$1; + + return ParseTreePattern; +} + +var RuleTagToken = {}; + +var hasRequiredRuleTagToken; + +function requireRuleTagToken () { + if (hasRequiredRuleTagToken) return RuleTagToken; + hasRequiredRuleTagToken = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleTagToken && RuleTagToken.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (RuleTagToken && RuleTagToken.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(RuleTagToken, "__esModule", { value: true }); + RuleTagToken.RuleTagToken = void 0; + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * A {@link Token} object representing an entire subtree matched by a parser + * rule; e.g., ``. These tokens are created for {@link TagChunk} + * chunks where the tag corresponds to a parser rule. + */ + let RuleTagToken$1 = class RuleTagToken { + /** + * Constructs a new instance of {@link RuleTagToken} with the specified rule + * name, bypass token type, and label. + * + * @param ruleName The name of the parser rule this rule tag matches. + * @param bypassTokenType The bypass token type assigned to the parser rule. + * @param label The label associated with the rule tag, or `undefined` if + * the rule tag is unlabeled. + * + * @exception IllegalArgumentException if `ruleName` is not defined + * or empty. + */ + constructor(ruleName, bypassTokenType, label) { + if (ruleName == null || ruleName.length === 0) { + throw new Error("ruleName cannot be null or empty."); + } + this._ruleName = ruleName; + this.bypassTokenType = bypassTokenType; + this._label = label; + } + /** + * Gets the name of the rule associated with this rule tag. + * + * @returns The name of the parser rule associated with this rule tag. + */ + get ruleName() { + return this._ruleName; + } + /** + * Gets the label associated with the rule tag. + * + * @returns The name of the label associated with the rule tag, or + * `undefined` if this is an unlabeled rule tag. + */ + get label() { + return this._label; + } + /** + * {@inheritDoc} + * + * Rule tag tokens are always placed on the {@link #DEFAULT_CHANNEL}. + */ + get channel() { + return Token_1.Token.DEFAULT_CHANNEL; + } + /** + * {@inheritDoc} + * + * This method returns the rule tag formatted with `<` and `>` + * delimiters. + */ + get text() { + if (this._label != null) { + return "<" + this._label + ":" + this._ruleName + ">"; + } + return "<" + this._ruleName + ">"; + } + /** + * {@inheritDoc} + * + * Rule tag tokens have types assigned according to the rule bypass + * transitions created during ATN deserialization. + */ + get type() { + return this.bypassTokenType; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns 0. + */ + get line() { + return 0; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns -1. + */ + get charPositionInLine() { + return -1; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns -1. + */ + get tokenIndex() { + return -1; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns -1. + */ + get startIndex() { + return -1; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns -1. + */ + get stopIndex() { + return -1; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns `undefined`. + */ + get tokenSource() { + return undefined; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} always returns `undefined`. + */ + get inputStream() { + return undefined; + } + /** + * {@inheritDoc} + * + * The implementation for {@link RuleTagToken} returns a string of the form + * `ruleName:bypassTokenType`. + */ + toString() { + return this._ruleName + ":" + this.bypassTokenType; + } + }; + __decorate([ + Decorators_1.NotNull + ], RuleTagToken$1.prototype, "ruleName", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "channel", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "type", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "line", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "charPositionInLine", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "tokenIndex", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "startIndex", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "stopIndex", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "tokenSource", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.Override + ], RuleTagToken$1.prototype, "toString", null); + RuleTagToken$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], RuleTagToken$1); + RuleTagToken.RuleTagToken = RuleTagToken$1; + + return RuleTagToken; +} + +var TagChunk = {}; + +var Chunk = {}; + +var hasRequiredChunk; + +function requireChunk () { + if (hasRequiredChunk) return Chunk; + hasRequiredChunk = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Chunk, "__esModule", { value: true }); + Chunk.Chunk = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:45.2799060-07:00 + /** + * A chunk is either a token tag, a rule tag, or a span of literal text within a + * tree pattern. + * + * The method {@link ParseTreePatternMatcher#split(String)} returns a list of + * chunks in preparation for creating a token stream by + * {@link ParseTreePatternMatcher#tokenize(String)}. From there, we get a parse + * tree from with {@link ParseTreePatternMatcher#compile(String, int)}. These + * chunks are converted to {@link RuleTagToken}, {@link TokenTagToken}, or the + * regular tokens of the text surrounding the tags. + */ + let Chunk$1 = class Chunk { + }; + Chunk.Chunk = Chunk$1; + + return Chunk; +} + +var hasRequiredTagChunk; + +function requireTagChunk () { + if (hasRequiredTagChunk) return TagChunk; + hasRequiredTagChunk = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TagChunk && TagChunk.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(TagChunk, "__esModule", { value: true }); + TagChunk.TagChunk = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:46.1670669-07:00 + const Chunk_1 = requireChunk(); + const Decorators_1 = requireDecorators(); + /** + * Represents a placeholder tag in a tree pattern. A tag can have any of the + * following forms. + * + * * `expr`: An unlabeled placeholder for a parser rule `expr`. + * * `ID`: An unlabeled placeholder for a token of type `ID`. + * * `e:expr`: A labeled placeholder for a parser rule `expr`. + * * `id:ID`: A labeled placeholder for a token of type `ID`. + * + * This class does not perform any validation on the tag or label names aside + * from ensuring that the tag is a defined, non-empty string. + */ + let TagChunk$1 = class TagChunk extends Chunk_1.Chunk { + /** + * Construct a new instance of {@link TagChunk} using the specified label + * and tag. + * + * @param label The label for the tag. If this is `undefined`, the + * {@link TagChunk} represents an unlabeled tag. + * @param tag The tag, which should be the name of a parser rule or token + * type. + * + * @exception IllegalArgumentException if `tag` is not defined or + * empty. + */ + constructor(tag, label) { + super(); + if (tag == null || tag.length === 0) { + throw new Error("tag cannot be null or empty"); + } + this._tag = tag; + this._label = label; + } + /** + * Get the tag for this chunk. + * + * @returns The tag for the chunk. + */ + get tag() { + return this._tag; + } + /** + * Get the label, if any, assigned to this chunk. + * + * @returns The label assigned to this chunk, or `undefined` if no label is + * assigned to the chunk. + */ + get label() { + return this._label; + } + /** + * This method returns a text representation of the tag chunk. Labeled tags + * are returned in the form `label:tag`, and unlabeled tags are + * returned as just the tag name. + */ + toString() { + if (this._label != null) { + return this._label + ":" + this._tag; + } + return this._tag; + } + }; + __decorate([ + Decorators_1.NotNull + ], TagChunk$1.prototype, "tag", null); + __decorate([ + Decorators_1.Override + ], TagChunk$1.prototype, "toString", null); + TagChunk.TagChunk = TagChunk$1; + + return TagChunk; +} + +var TextChunk = {}; + +var hasRequiredTextChunk; + +function requireTextChunk () { + if (hasRequiredTextChunk) return TextChunk; + hasRequiredTextChunk = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TextChunk && TextChunk.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (TextChunk && TextChunk.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(TextChunk, "__esModule", { value: true }); + TextChunk.TextChunk = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:46.2521448-07:00 + const Chunk_1 = requireChunk(); + const Decorators_1 = requireDecorators(); + /** + * Represents a span of raw text (concrete syntax) between tags in a tree + * pattern string. + */ + let TextChunk$1 = class TextChunk extends Chunk_1.Chunk { + /** + * Constructs a new instance of {@link TextChunk} with the specified text. + * + * @param text The text of this chunk. + * @exception IllegalArgumentException if `text` is not defined. + */ + constructor(text) { + super(); + if (text == null) { + throw new Error("text cannot be null"); + } + this._text = text; + } + /** + * Gets the raw text of this chunk. + * + * @returns The text of the chunk. + */ + get text() { + return this._text; + } + /** + * {@inheritDoc} + * + * The implementation for {@link TextChunk} returns the result of + * `text` in single quotes. + */ + toString() { + return "'" + this._text + "'"; + } + }; + __decorate([ + Decorators_1.NotNull + ], TextChunk$1.prototype, "_text", void 0); + __decorate([ + Decorators_1.NotNull + ], TextChunk$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], TextChunk$1.prototype, "toString", null); + TextChunk$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], TextChunk$1); + TextChunk.TextChunk = TextChunk$1; + + return TextChunk; +} + +var TokenTagToken = {}; + +var hasRequiredTokenTagToken; + +function requireTokenTagToken () { + if (hasRequiredTokenTagToken) return TokenTagToken; + hasRequiredTokenTagToken = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TokenTagToken && TokenTagToken.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (TokenTagToken && TokenTagToken.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(TokenTagToken, "__esModule", { value: true }); + TokenTagToken.TokenTagToken = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:46.3281988-07:00 + const CommonToken_1 = requireCommonToken(); + const Decorators_1 = requireDecorators(); + /** + * A {@link Token} object representing a token of a particular type; e.g., + * ``. These tokens are created for {@link TagChunk} chunks where the + * tag corresponds to a lexer rule or token type. + */ + let TokenTagToken$1 = class TokenTagToken extends CommonToken_1.CommonToken { + /** + * Constructs a new instance of {@link TokenTagToken} with the specified + * token name, type, and label. + * + * @param tokenName The token name. + * @param type The token type. + * @param label The label associated with the token tag, or `undefined` if + * the token tag is unlabeled. + */ + constructor(tokenName, type, label) { + super(type); + this._tokenName = tokenName; + this._label = label; + } + /** + * Gets the token name. + * @returns The token name. + */ + get tokenName() { + return this._tokenName; + } + /** + * Gets the label associated with the rule tag. + * + * @returns The name of the label associated with the rule tag, or + * `undefined` if this is an unlabeled rule tag. + */ + get label() { + return this._label; + } + /** + * {@inheritDoc} + * + * The implementation for {@link TokenTagToken} returns the token tag + * formatted with `<` and `>` delimiters. + */ + get text() { + if (this._label != null) { + return "<" + this._label + ":" + this._tokenName + ">"; + } + return "<" + this._tokenName + ">"; + } + /** + * {@inheritDoc} + * + * The implementation for {@link TokenTagToken} returns a string of the form + * `tokenName:type`. + */ + toString() { + return this._tokenName + ":" + this.type; + } + }; + __decorate([ + Decorators_1.NotNull + ], TokenTagToken$1.prototype, "_tokenName", void 0); + __decorate([ + Decorators_1.NotNull + ], TokenTagToken$1.prototype, "tokenName", null); + __decorate([ + Decorators_1.Override + ], TokenTagToken$1.prototype, "text", null); + __decorate([ + Decorators_1.Override + ], TokenTagToken$1.prototype, "toString", null); + TokenTagToken$1 = __decorate([ + __param(0, Decorators_1.NotNull) + ], TokenTagToken$1); + TokenTagToken.TokenTagToken = TokenTagToken$1; + + return TokenTagToken; +} + +var hasRequiredParseTreePatternMatcher; + +function requireParseTreePatternMatcher () { + if (hasRequiredParseTreePatternMatcher) return ParseTreePatternMatcher; + hasRequiredParseTreePatternMatcher = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ParseTreePatternMatcher && ParseTreePatternMatcher.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ParseTreePatternMatcher && ParseTreePatternMatcher.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ParseTreePatternMatcher = void 0; + // CONVERSTION complete, Burt Harris 10/14/2016 + const BailErrorStrategy_1 = requireBailErrorStrategy(); + const CharStreams_1 = requireCharStreams(); + const CommonTokenStream_1 = requireCommonTokenStream(); + const ListTokenSource_1 = requireListTokenSource(); + const MultiMap_1 = requireMultiMap(); + const Decorators_1 = requireDecorators(); + const ParseCancellationException_1 = requireParseCancellationException(); + const ParserInterpreter_1 = requireParserInterpreter(); + const ParserRuleContext_1 = requireParserRuleContext(); + const ParseTreeMatch_1 = requireParseTreeMatch(); + const ParseTreePattern_1 = requireParseTreePattern(); + const RecognitionException_1 = requireRecognitionException(); + const RuleNode_1 = requireRuleNode(); + const RuleTagToken_1 = requireRuleTagToken(); + const TagChunk_1 = requireTagChunk(); + const TerminalNode_1 = requireTerminalNode(); + const TextChunk_1 = requireTextChunk(); + const Token_1 = requireToken(); + const TokenTagToken_1 = requireTokenTagToken(); + /** + * A tree pattern matching mechanism for ANTLR {@link ParseTree}s. + * + * Patterns are strings of source input text with special tags representing + * token or rule references such as: + * + * ``` + * = ; + * ``` + * + * Given a pattern start rule such as `statement`, this object constructs + * a {@link ParseTree} with placeholders for the `ID` and `expr` + * subtree. Then the {@link #match} routines can compare an actual + * {@link ParseTree} from a parse with this pattern. Tag `` matches + * any `ID` token and tag `` references the result of the + * `expr` rule (generally an instance of `ExprContext`. + * + * Pattern `x = 0;` is a similar pattern that matches the same pattern + * except that it requires the identifier to be `x` and the expression to + * be `0`. + * + * The {@link #matches} routines return `true` or `false` based + * upon a match for the tree rooted at the parameter sent in. The + * {@link #match} routines return a {@link ParseTreeMatch} object that + * contains the parse tree, the parse tree pattern, and a map from tag name to + * matched nodes (more below). A subtree that fails to match, returns with + * {@link ParseTreeMatch#mismatchedNode} set to the first tree node that did not + * match. + * + * For efficiency, you can compile a tree pattern in string form to a + * {@link ParseTreePattern} object. + * + * See `TestParseTreeMatcher` for lots of examples. + * {@link ParseTreePattern} has two static helper methods: + * {@link ParseTreePattern#findAll} and {@link ParseTreePattern#match} that + * are easy to use but not super efficient because they create new + * {@link ParseTreePatternMatcher} objects each time and have to compile the + * pattern in string form before using it. + * + * The lexer and parser that you pass into the {@link ParseTreePatternMatcher} + * constructor are used to parse the pattern in string form. The lexer converts + * the ` = ;` into a sequence of four tokens (assuming lexer + * throws out whitespace or puts it on a hidden channel). Be aware that the + * input stream is reset for the lexer (but not the parser; a + * {@link ParserInterpreter} is created to parse the input.). Any user-defined + * fields you have put into the lexer might get changed when this mechanism asks + * it to scan the pattern string. + * + * Normally a parser does not accept token `` as a valid + * `expr` but, from the parser passed in, we create a special version of + * the underlying grammar representation (an {@link ATN}) that allows imaginary + * tokens representing rules (``) to match entire rules. We call + * these *bypass alternatives*. + * + * Delimiters are `<`} and `>`}, with `\` as the escape string + * by default, but you can set them to whatever you want using + * {@link #setDelimiters}. You must escape both start and stop strings + * `\<` and `\>`. + */ + let ParseTreePatternMatcher$1 = class ParseTreePatternMatcher { + /** + * Constructs a {@link ParseTreePatternMatcher} or from a {@link Lexer} and + * {@link Parser} object. The lexer input stream is altered for tokenizing + * the tree patterns. The parser is used as a convenient mechanism to get + * the grammar name, plus token, rule names. + */ + constructor(lexer, parser) { + this.start = "<"; + this.stop = ">"; + this.escape = "\\"; // e.g., \< and \> must escape BOTH! + /** + * Regular expression corresponding to escape, for global replace + */ + this.escapeRE = /\\/g; + this._lexer = lexer; + this._parser = parser; + } + /** + * Set the delimiters used for marking rule and token tags within concrete + * syntax used by the tree pattern parser. + * + * @param start The start delimiter. + * @param stop The stop delimiter. + * @param escapeLeft The escape sequence to use for escaping a start or stop delimiter. + * + * @throws {@link Error} if `start` is not defined or empty. + * @throws {@link Error} if `stop` is not defined or empty. + */ + setDelimiters(start, stop, escapeLeft) { + if (!start) { + throw new Error("start cannot be null or empty"); + } + if (!stop) { + throw new Error("stop cannot be null or empty"); + } + this.start = start; + this.stop = stop; + this.escape = escapeLeft; + this.escapeRE = new RegExp(escapeLeft.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"); + } + matches(tree, pattern, patternRuleIndex = 0) { + if (typeof pattern === "string") { + let p = this.compile(pattern, patternRuleIndex); + return this.matches(tree, p); + } + else { + let labels = new MultiMap_1.MultiMap(); + let mismatchedNode = this.matchImpl(tree, pattern.patternTree, labels); + return !mismatchedNode; + } + } + // Implementation of match + match(tree, pattern, patternRuleIndex = 0) { + if (typeof pattern === "string") { + let p = this.compile(pattern, patternRuleIndex); + return this.match(tree, p); + } + else { + let labels = new MultiMap_1.MultiMap(); + let mismatchedNode = this.matchImpl(tree, pattern.patternTree, labels); + return new ParseTreeMatch_1.ParseTreeMatch(tree, pattern, labels, mismatchedNode); + } + } + /** + * For repeated use of a tree pattern, compile it to a + * {@link ParseTreePattern} using this method. + */ + compile(pattern, patternRuleIndex) { + let tokenList = this.tokenize(pattern); + let tokenSrc = new ListTokenSource_1.ListTokenSource(tokenList); + let tokens = new CommonTokenStream_1.CommonTokenStream(tokenSrc); + const parser = this._parser; + let parserInterp = new ParserInterpreter_1.ParserInterpreter(parser.grammarFileName, parser.vocabulary, parser.ruleNames, parser.getATNWithBypassAlts(), tokens); + let tree; + try { + parserInterp.errorHandler = new BailErrorStrategy_1.BailErrorStrategy(); + tree = parserInterp.parse(patternRuleIndex); + // System.out.println("pattern tree = "+tree.toStringTree(parserInterp)); + } + catch (e) { + if (e instanceof ParseCancellationException_1.ParseCancellationException) { + throw e.getCause(); + } + else if (e instanceof RecognitionException_1.RecognitionException) { + throw e; + } + else if (e instanceof Error) { + throw new ParseTreePatternMatcher.CannotInvokeStartRule(e); + } + else { + throw e; + } + } + // Make sure tree pattern compilation checks for a complete parse + if (tokens.LA(1) !== Token_1.Token.EOF) { + throw new ParseTreePatternMatcher.StartRuleDoesNotConsumeFullPattern(); + } + return new ParseTreePattern_1.ParseTreePattern(this, pattern, patternRuleIndex, tree); + } + /** + * Used to convert the tree pattern string into a series of tokens. The + * input stream is reset. + */ + get lexer() { + return this._lexer; + } + /** + * Used to collect to the grammar file name, token names, rule names for + * used to parse the pattern into a parse tree. + */ + get parser() { + return this._parser; + } + // ---- SUPPORT CODE ---- + /** + * Recursively walk `tree` against `patternTree`, filling + * `match.`{@link ParseTreeMatch#labels labels}. + * + * @returns the first node encountered in `tree` which does not match + * a corresponding node in `patternTree`, or `undefined` if the match + * was successful. The specific node returned depends on the matching + * algorithm used by the implementation, and may be overridden. + */ + matchImpl(tree, patternTree, labels) { + if (!tree) { + throw new TypeError("tree cannot be null"); + } + if (!patternTree) { + throw new TypeError("patternTree cannot be null"); + } + // x and , x and y, or x and x; or could be mismatched types + if (tree instanceof TerminalNode_1.TerminalNode && patternTree instanceof TerminalNode_1.TerminalNode) { + let mismatchedNode; + // both are tokens and they have same type + if (tree.symbol.type === patternTree.symbol.type) { + if (patternTree.symbol instanceof TokenTagToken_1.TokenTagToken) { // x and + let tokenTagToken = patternTree.symbol; + // track label->list-of-nodes for both token name and label (if any) + labels.map(tokenTagToken.tokenName, tree); + const l = tokenTagToken.label; + if (l) { + labels.map(l, tree); + } + } + else if (tree.text === patternTree.text) ; + else { + // x and y + if (!mismatchedNode) { + mismatchedNode = tree; + } + } + } + else { + if (!mismatchedNode) { + mismatchedNode = tree; + } + } + return mismatchedNode; + } + if (tree instanceof ParserRuleContext_1.ParserRuleContext + && patternTree instanceof ParserRuleContext_1.ParserRuleContext) { + let mismatchedNode; + // (expr ...) and + let ruleTagToken = this.getRuleTagToken(patternTree); + if (ruleTagToken) { + if (tree.ruleContext.ruleIndex === patternTree.ruleContext.ruleIndex) { + // track label->list-of-nodes for both rule name and label (if any) + labels.map(ruleTagToken.ruleName, tree); + const l = ruleTagToken.label; + if (l) { + labels.map(l, tree); + } + } + else { + if (!mismatchedNode) { + mismatchedNode = tree; + } + } + return mismatchedNode; + } + // (expr ...) and (expr ...) + if (tree.childCount !== patternTree.childCount) { + if (!mismatchedNode) { + mismatchedNode = tree; + } + return mismatchedNode; + } + let n = tree.childCount; + for (let i = 0; i < n; i++) { + let childMatch = this.matchImpl(tree.getChild(i), patternTree.getChild(i), labels); + if (childMatch) { + return childMatch; + } + } + return mismatchedNode; + } + // if nodes aren't both tokens or both rule nodes, can't match + return tree; + } + /** Is `t` `(expr )` subtree? */ + getRuleTagToken(t) { + if (t instanceof RuleNode_1.RuleNode) { + if (t.childCount === 1 && t.getChild(0) instanceof TerminalNode_1.TerminalNode) { + let c = t.getChild(0); + if (c.symbol instanceof RuleTagToken_1.RuleTagToken) { + // System.out.println("rule tag subtree "+t.toStringTree(parser)); + return c.symbol; + } + } + } + return undefined; + } + tokenize(pattern) { + // split pattern into chunks: sea (raw input) and islands (, ) + let chunks = this.split(pattern); + // create token stream from text and tags + let tokens = []; + for (let chunk of chunks) { + if (chunk instanceof TagChunk_1.TagChunk) { + let tagChunk = chunk; + const firstChar = tagChunk.tag.substr(0, 1); + // add special rule token or conjure up new token from name + if (firstChar === firstChar.toUpperCase()) { + let ttype = this._parser.getTokenType(tagChunk.tag); + if (ttype === Token_1.Token.INVALID_TYPE) { + throw new Error("Unknown token " + tagChunk.tag + " in pattern: " + pattern); + } + let t = new TokenTagToken_1.TokenTagToken(tagChunk.tag, ttype, tagChunk.label); + tokens.push(t); + } + else if (firstChar === firstChar.toLowerCase()) { + let ruleIndex = this._parser.getRuleIndex(tagChunk.tag); + if (ruleIndex === -1) { + throw new Error("Unknown rule " + tagChunk.tag + " in pattern: " + pattern); + } + let ruleImaginaryTokenType = this._parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex]; + tokens.push(new RuleTagToken_1.RuleTagToken(tagChunk.tag, ruleImaginaryTokenType, tagChunk.label)); + } + else { + throw new Error("invalid tag: " + tagChunk.tag + " in pattern: " + pattern); + } + } + else { + let textChunk = chunk; + this._lexer.inputStream = CharStreams_1.CharStreams.fromString(textChunk.text); + let t = this._lexer.nextToken(); + while (t.type !== Token_1.Token.EOF) { + tokens.push(t); + t = this._lexer.nextToken(); + } + } + } + // System.out.println("tokens="+tokens); + return tokens; + } + /** Split ` = ;` into 4 chunks for tokenizing by {@link #tokenize}. */ + split(pattern) { + let p = 0; + let n = pattern.length; + let chunks = []; + // find all start and stop indexes first, then collect + let starts = []; + let stops = []; + while (p < n) { + if (p === pattern.indexOf(this.escape + this.start, p)) { + p += this.escape.length + this.start.length; + } + else if (p === pattern.indexOf(this.escape + this.stop, p)) { + p += this.escape.length + this.stop.length; + } + else if (p === pattern.indexOf(this.start, p)) { + starts.push(p); + p += this.start.length; + } + else if (p === pattern.indexOf(this.stop, p)) { + stops.push(p); + p += this.stop.length; + } + else { + p++; + } + } + // System.out.println(""); + // System.out.println(starts); + // System.out.println(stops); + if (starts.length > stops.length) { + throw new Error("unterminated tag in pattern: " + pattern); + } + if (starts.length < stops.length) { + throw new Error("missing start tag in pattern: " + pattern); + } + let ntags = starts.length; + for (let i = 0; i < ntags; i++) { + if (starts[i] >= stops[i]) { + throw new Error("tag delimiters out of order in pattern: " + pattern); + } + } + // collect into chunks now + if (ntags === 0) { + let text = pattern.substring(0, n); + chunks.push(new TextChunk_1.TextChunk(text)); + } + if (ntags > 0 && starts[0] > 0) { // copy text up to first tag into chunks + let text = pattern.substring(0, starts[0]); + chunks.push(new TextChunk_1.TextChunk(text)); + } + for (let i = 0; i < ntags; i++) { + // copy inside of + let tag = pattern.substring(starts[i] + this.start.length, stops[i]); + let ruleOrToken = tag; + let label; + let colon = tag.indexOf(":"); + if (colon >= 0) { + label = tag.substring(0, colon); + ruleOrToken = tag.substring(colon + 1, tag.length); + } + chunks.push(new TagChunk_1.TagChunk(ruleOrToken, label)); + if (i + 1 < ntags) { + // copy from end of to start of next + let text = pattern.substring(stops[i] + this.stop.length, starts[i + 1]); + chunks.push(new TextChunk_1.TextChunk(text)); + } + } + if (ntags > 0) { + let afterLastTag = stops[ntags - 1] + this.stop.length; + if (afterLastTag < n) { // copy text from end of last tag to end + let text = pattern.substring(afterLastTag, n); + chunks.push(new TextChunk_1.TextChunk(text)); + } + } + // strip out the escape sequences from text chunks but not tags + for (let i = 0; i < chunks.length; i++) { + let c = chunks[i]; + if (c instanceof TextChunk_1.TextChunk) { + let unescaped = c.text.replace(this.escapeRE, ""); + if (unescaped.length < c.text.length) { + chunks[i] = new TextChunk_1.TextChunk(unescaped); + } + } + } + return chunks; + } + }; + __decorate([ + Decorators_1.NotNull, + __param(1, Decorators_1.NotNull) + ], ParseTreePatternMatcher$1.prototype, "match", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreePatternMatcher$1.prototype, "lexer", null); + __decorate([ + Decorators_1.NotNull + ], ParseTreePatternMatcher$1.prototype, "parser", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ParseTreePatternMatcher$1.prototype, "matchImpl", null); + exports.ParseTreePatternMatcher = ParseTreePatternMatcher$1; + (function (ParseTreePatternMatcher) { + class CannotInvokeStartRule extends Error { + constructor(error) { + super(`CannotInvokeStartRule: ${error}`); + this.error = error; + } + } + ParseTreePatternMatcher.CannotInvokeStartRule = CannotInvokeStartRule; + // Fixes https://github.com/antlr/antlr4/issues/413 + // "Tree pattern compilation doesn't check for a complete parse" + class StartRuleDoesNotConsumeFullPattern extends Error { + constructor() { + super("StartRuleDoesNotConsumeFullPattern"); + } + } + ParseTreePatternMatcher.StartRuleDoesNotConsumeFullPattern = StartRuleDoesNotConsumeFullPattern; + })(ParseTreePatternMatcher$1 = exports.ParseTreePatternMatcher || (exports.ParseTreePatternMatcher = {})); + + } (ParseTreePatternMatcher)); + return ParseTreePatternMatcher; +} + +var ProfilingATNSimulator = {}; + +var AmbiguityInfo = {}; + +var DecisionEventInfo = {}; + +var hasRequiredDecisionEventInfo; + +function requireDecisionEventInfo () { + if (hasRequiredDecisionEventInfo) return DecisionEventInfo; + hasRequiredDecisionEventInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DecisionEventInfo && DecisionEventInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (DecisionEventInfo && DecisionEventInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(DecisionEventInfo, "__esModule", { value: true }); + DecisionEventInfo.DecisionEventInfo = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:28.2401032-07:00 + const Decorators_1 = requireDecorators(); + /** + * This is the base class for gathering detailed information about prediction + * events which occur during parsing. + * + * Note that we could record the parser call stack at the time this event + * occurred but in the presence of left recursive rules, the stack is kind of + * meaningless. It's better to look at the individual configurations for their + * individual stacks. Of course that is a {@link PredictionContext} object + * not a parse tree node and so it does not have information about the extent + * (start...stop) of the various subtrees. Examining the stack tops of all + * configurations provide the return states for the rule invocations. + * From there you can get the enclosing rule. + * + * @since 4.3 + */ + let DecisionEventInfo$1 = class DecisionEventInfo { + constructor(decision, state, input, startIndex, stopIndex, fullCtx) { + this.decision = decision; + this.fullCtx = fullCtx; + this.stopIndex = stopIndex; + this.input = input; + this.startIndex = startIndex; + this.state = state; + } + }; + __decorate([ + Decorators_1.NotNull + ], DecisionEventInfo$1.prototype, "input", void 0); + DecisionEventInfo$1 = __decorate([ + __param(2, Decorators_1.NotNull) + ], DecisionEventInfo$1); + DecisionEventInfo.DecisionEventInfo = DecisionEventInfo$1; + + return DecisionEventInfo; +} + +var hasRequiredAmbiguityInfo; + +function requireAmbiguityInfo () { + if (hasRequiredAmbiguityInfo) return AmbiguityInfo; + hasRequiredAmbiguityInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (AmbiguityInfo && AmbiguityInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (AmbiguityInfo && AmbiguityInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(AmbiguityInfo, "__esModule", { value: true }); + AmbiguityInfo.AmbiguityInfo = void 0; + const DecisionEventInfo_1 = requireDecisionEventInfo(); + const Decorators_1 = requireDecorators(); + /** + * This class represents profiling event information for an ambiguity. + * Ambiguities are decisions where a particular input resulted in an SLL + * conflict, followed by LL prediction also reaching a conflict state + * (indicating a true ambiguity in the grammar). + * + * This event may be reported during SLL prediction in cases where the + * conflicting SLL configuration set provides sufficient information to + * determine that the SLL conflict is truly an ambiguity. For example, if none + * of the ATN configurations in the conflicting SLL configuration set have + * traversed a global follow transition (i.e. + * {@link ATNConfig#getReachesIntoOuterContext} is `false` for all + * configurations), then the result of SLL prediction for that input is known to + * be equivalent to the result of LL prediction for that input. + * + * In some cases, the minimum represented alternative in the conflicting LL + * configuration set is not equal to the minimum represented alternative in the + * conflicting SLL configuration set. Grammars and inputs which result in this + * scenario are unable to use {@link PredictionMode#SLL}, which in turn means + * they cannot use the two-stage parsing strategy to improve parsing performance + * for that input. + * + * @see ParserATNSimulator#reportAmbiguity + * @see ParserErrorListener#reportAmbiguity + * + * @since 4.3 + */ + let AmbiguityInfo$1 = class AmbiguityInfo extends DecisionEventInfo_1.DecisionEventInfo { + /** + * Constructs a new instance of the {@link AmbiguityInfo} class with the + * specified detailed ambiguity information. + * + * @param decision The decision number + * @param state The final simulator state identifying the ambiguous + * alternatives for the current input + * @param ambigAlts The set of alternatives in the decision that lead to a valid parse. + * The predicted alt is the min(ambigAlts) + * @param input The input token stream + * @param startIndex The start index for the current prediction + * @param stopIndex The index at which the ambiguity was identified during + * prediction + */ + constructor(decision, state, ambigAlts, input, startIndex, stopIndex) { + super(decision, state, input, startIndex, stopIndex, state.useContext); + this.ambigAlts = ambigAlts; + } + /** + * Gets the set of alternatives in the decision that lead to a valid parse. + * + * @since 4.5 + */ + get ambiguousAlternatives() { + return this.ambigAlts; + } + }; + __decorate([ + Decorators_1.NotNull + ], AmbiguityInfo$1.prototype, "ambigAlts", void 0); + __decorate([ + Decorators_1.NotNull + ], AmbiguityInfo$1.prototype, "ambiguousAlternatives", null); + AmbiguityInfo$1 = __decorate([ + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull), + __param(3, Decorators_1.NotNull) + ], AmbiguityInfo$1); + AmbiguityInfo.AmbiguityInfo = AmbiguityInfo$1; + + return AmbiguityInfo; +} + +var ContextSensitivityInfo = {}; + +var hasRequiredContextSensitivityInfo; + +function requireContextSensitivityInfo () { + if (hasRequiredContextSensitivityInfo) return ContextSensitivityInfo; + hasRequiredContextSensitivityInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ContextSensitivityInfo && ContextSensitivityInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ContextSensitivityInfo && ContextSensitivityInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ContextSensitivityInfo, "__esModule", { value: true }); + ContextSensitivityInfo.ContextSensitivityInfo = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:28.1575933-07:00 + const DecisionEventInfo_1 = requireDecisionEventInfo(); + const Decorators_1 = requireDecorators(); + /** + * This class represents profiling event information for a context sensitivity. + * Context sensitivities are decisions where a particular input resulted in an + * SLL conflict, but LL prediction produced a single unique alternative. + * + * In some cases, the unique alternative identified by LL prediction is not + * equal to the minimum represented alternative in the conflicting SLL + * configuration set. Grammars and inputs which result in this scenario are + * unable to use {@link PredictionMode#SLL}, which in turn means they cannot use + * the two-stage parsing strategy to improve parsing performance for that + * input. + * + * @see ParserATNSimulator#reportContextSensitivity + * @see ParserErrorListener#reportContextSensitivity + * + * @since 4.3 + */ + let ContextSensitivityInfo$1 = class ContextSensitivityInfo extends DecisionEventInfo_1.DecisionEventInfo { + /** + * Constructs a new instance of the {@link ContextSensitivityInfo} class + * with the specified detailed context sensitivity information. + * + * @param decision The decision number + * @param state The final simulator state containing the unique + * alternative identified by full-context prediction + * @param input The input token stream + * @param startIndex The start index for the current prediction + * @param stopIndex The index at which the context sensitivity was + * identified during full-context prediction + */ + constructor(decision, state, input, startIndex, stopIndex) { + super(decision, state, input, startIndex, stopIndex, true); + } + }; + ContextSensitivityInfo$1 = __decorate([ + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ContextSensitivityInfo$1); + ContextSensitivityInfo.ContextSensitivityInfo = ContextSensitivityInfo$1; + + return ContextSensitivityInfo; +} + +var DecisionInfo = {}; + +var hasRequiredDecisionInfo; + +function requireDecisionInfo () { + if (hasRequiredDecisionInfo) return DecisionInfo; + hasRequiredDecisionInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DecisionInfo && DecisionInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(DecisionInfo, "__esModule", { value: true }); + DecisionInfo.DecisionInfo = void 0; + const Decorators_1 = requireDecorators(); + /** + * This class contains profiling gathered for a particular decision. + * + * Parsing performance in ANTLR 4 is heavily influenced by both static factors + * (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the + * choice of input and the state of the DFA cache at the time profiling + * operations are started). For best results, gather and use aggregate + * statistics from a large sample of inputs representing the inputs expected in + * production before using the results to make changes in the grammar. + * + * @since 4.3 + */ + let DecisionInfo$1 = class DecisionInfo { + /** + * Constructs a new instance of the {@link DecisionInfo} class to contain + * statistics for a particular decision. + * + * @param decision The decision number + */ + constructor(decision) { + /** + * The total number of times {@link ParserATNSimulator#adaptivePredict} was + * invoked for this decision. + */ + this.invocations = 0; + /** + * The total time spent in {@link ParserATNSimulator#adaptivePredict} for + * this decision, in nanoseconds. + * + * The value of this field contains the sum of differential results obtained + * by {@link System#nanoTime()}, and is not adjusted to compensate for JIT + * and/or garbage collection overhead. For best accuracy, use a modern JVM + * implementation that provides precise results from + * {@link System#nanoTime()}, and perform profiling in a separate process + * which is warmed up by parsing the input prior to profiling. If desired, + * call {@link ATNSimulator#clearDFA} to reset the DFA cache to its initial + * state before starting the profiling measurement pass. + */ + this.timeInPrediction = 0; + /** + * The sum of the lookahead required for SLL prediction for this decision. + * Note that SLL prediction is used before LL prediction for performance + * reasons even when {@link PredictionMode#LL} or + * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. + */ + this.SLL_TotalLook = 0; + /** + * Gets the minimum lookahead required for any single SLL prediction to + * complete for this decision, by reaching a unique prediction, reaching an + * SLL conflict state, or encountering a syntax error. + */ + this.SLL_MinLook = 0; + /** + * Gets the maximum lookahead required for any single SLL prediction to + * complete for this decision, by reaching a unique prediction, reaching an + * SLL conflict state, or encountering a syntax error. + */ + this.SLL_MaxLook = 0; + /** + * The sum of the lookahead required for LL prediction for this decision. + * Note that LL prediction is only used when SLL prediction reaches a + * conflict state. + */ + this.LL_TotalLook = 0; + /** + * Gets the minimum lookahead required for any single LL prediction to + * complete for this decision. An LL prediction completes when the algorithm + * reaches a unique prediction, a conflict state (for + * {@link PredictionMode#LL}, an ambiguity state (for + * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error. + */ + this.LL_MinLook = 0; + /** + * Gets the maximum lookahead required for any single LL prediction to + * complete for this decision. An LL prediction completes when the algorithm + * reaches a unique prediction, a conflict state (for + * {@link PredictionMode#LL}, an ambiguity state (for + * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error. + */ + this.LL_MaxLook = 0; + /** + * A collection of {@link ContextSensitivityInfo} instances describing the + * context sensitivities encountered during LL prediction for this decision. + * + * @see ContextSensitivityInfo + */ + this.contextSensitivities = []; + /** + * A collection of {@link ErrorInfo} instances describing the parse errors + * identified during calls to {@link ParserATNSimulator#adaptivePredict} for + * this decision. + * + * @see ErrorInfo + */ + this.errors = []; + /** + * A collection of {@link AmbiguityInfo} instances describing the + * ambiguities encountered during LL prediction for this decision. + * + * @see AmbiguityInfo + */ + this.ambiguities = []; + /** + * A collection of {@link PredicateEvalInfo} instances describing the + * results of evaluating individual predicates during prediction for this + * decision. + * + * @see PredicateEvalInfo + */ + this.predicateEvals = []; + /** + * The total number of ATN transitions required during SLL prediction for + * this decision. An ATN transition is determined by the number of times the + * DFA does not contain an edge that is required for prediction, resulting + * in on-the-fly computation of that edge. + * + * If DFA caching of SLL transitions is employed by the implementation, ATN + * computation may cache the computed edge for efficient lookup during + * future parsing of this decision. Otherwise, the SLL parsing algorithm + * will use ATN transitions exclusively. + * + * @see #SLL_ATNTransitions + * @see ParserATNSimulator#computeTargetState + * @see LexerATNSimulator#computeTargetState + */ + this.SLL_ATNTransitions = 0; + /** + * The total number of DFA transitions required during SLL prediction for + * this decision. + * + * If the ATN simulator implementation does not use DFA caching for SLL + * transitions, this value will be 0. + * + * @see ParserATNSimulator#getExistingTargetState + * @see LexerATNSimulator#getExistingTargetState + */ + this.SLL_DFATransitions = 0; + /** + * Gets the total number of times SLL prediction completed in a conflict + * state, resulting in fallback to LL prediction. + * + * Note that this value is not related to whether or not + * {@link PredictionMode#SLL} may be used successfully with a particular + * grammar. If the ambiguity resolution algorithm applied to the SLL + * conflicts for this decision produce the same result as LL prediction for + * this decision, {@link PredictionMode#SLL} would produce the same overall + * parsing result as {@link PredictionMode#LL}. + */ + this.LL_Fallback = 0; + /** + * The total number of ATN transitions required during LL prediction for + * this decision. An ATN transition is determined by the number of times the + * DFA does not contain an edge that is required for prediction, resulting + * in on-the-fly computation of that edge. + * + * If DFA caching of LL transitions is employed by the implementation, ATN + * computation may cache the computed edge for efficient lookup during + * future parsing of this decision. Otherwise, the LL parsing algorithm will + * use ATN transitions exclusively. + * + * @see #LL_DFATransitions + * @see ParserATNSimulator#computeTargetState + * @see LexerATNSimulator#computeTargetState + */ + this.LL_ATNTransitions = 0; + /** + * The total number of DFA transitions required during LL prediction for + * this decision. + * + * If the ATN simulator implementation does not use DFA caching for LL + * transitions, this value will be 0. + * + * @see ParserATNSimulator#getExistingTargetState + * @see LexerATNSimulator#getExistingTargetState + */ + this.LL_DFATransitions = 0; + this.decision = decision; + } + toString() { + return "{" + + "decision=" + this.decision + + ", contextSensitivities=" + this.contextSensitivities.length + + ", errors=" + this.errors.length + + ", ambiguities=" + this.ambiguities.length + + ", SLL_lookahead=" + this.SLL_TotalLook + + ", SLL_ATNTransitions=" + this.SLL_ATNTransitions + + ", SLL_DFATransitions=" + this.SLL_DFATransitions + + ", LL_Fallback=" + this.LL_Fallback + + ", LL_lookahead=" + this.LL_TotalLook + + ", LL_ATNTransitions=" + this.LL_ATNTransitions + + "}"; + } + }; + __decorate([ + Decorators_1.Override + ], DecisionInfo$1.prototype, "toString", null); + DecisionInfo.DecisionInfo = DecisionInfo$1; + + return DecisionInfo; +} + +var ErrorInfo = {}; + +var hasRequiredErrorInfo; + +function requireErrorInfo () { + if (hasRequiredErrorInfo) return ErrorInfo; + hasRequiredErrorInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ErrorInfo && ErrorInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ErrorInfo && ErrorInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ErrorInfo, "__esModule", { value: true }); + ErrorInfo.ErrorInfo = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:28.7213647-07:00 + const DecisionEventInfo_1 = requireDecisionEventInfo(); + const Decorators_1 = requireDecorators(); + /** + * This class represents profiling event information for a syntax error + * identified during prediction. Syntax errors occur when the prediction + * algorithm is unable to identify an alternative which would lead to a + * successful parse. + * + * @see Parser#notifyErrorListeners(Token, String, RecognitionException) + * @see ANTLRErrorListener#syntaxError + * + * @since 4.3 + */ + let ErrorInfo$1 = class ErrorInfo extends DecisionEventInfo_1.DecisionEventInfo { + /** + * Constructs a new instance of the {@link ErrorInfo} class with the + * specified detailed syntax error information. + * + * @param decision The decision number + * @param state The final simulator state reached during prediction + * prior to reaching the {@link ATNSimulator#ERROR} state + * @param input The input token stream + * @param startIndex The start index for the current prediction + * @param stopIndex The index at which the syntax error was identified + */ + constructor(decision, state, input, startIndex, stopIndex) { + super(decision, state, input, startIndex, stopIndex, state.useContext); + } + }; + ErrorInfo$1 = __decorate([ + __param(1, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull) + ], ErrorInfo$1); + ErrorInfo.ErrorInfo = ErrorInfo$1; + + return ErrorInfo; +} + +var LookaheadEventInfo = {}; + +var hasRequiredLookaheadEventInfo; + +function requireLookaheadEventInfo () { + if (hasRequiredLookaheadEventInfo) return LookaheadEventInfo; + hasRequiredLookaheadEventInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LookaheadEventInfo && LookaheadEventInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LookaheadEventInfo && LookaheadEventInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LookaheadEventInfo, "__esModule", { value: true }); + LookaheadEventInfo.LookaheadEventInfo = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:30.6852565-07:00 + const DecisionEventInfo_1 = requireDecisionEventInfo(); + const Decorators_1 = requireDecorators(); + /** + * This class represents profiling event information for tracking the lookahead + * depth required in order to make a prediction. + * + * @since 4.3 + */ + let LookaheadEventInfo$1 = class LookaheadEventInfo extends DecisionEventInfo_1.DecisionEventInfo { + /** + * Constructs a new instance of the {@link LookaheadEventInfo} class with + * the specified detailed lookahead information. + * + * @param decision The decision number + * @param state The final simulator state containing the necessary + * information to determine the result of a prediction, or `undefined` if + * the final state is not available + * @param input The input token stream + * @param startIndex The start index for the current prediction + * @param stopIndex The index at which the prediction was finally made + * @param fullCtx `true` if the current lookahead is part of an LL + * prediction; otherwise, `false` if the current lookahead is part of + * an SLL prediction + */ + constructor(decision, state, predictedAlt, input, startIndex, stopIndex, fullCtx) { + super(decision, state, input, startIndex, stopIndex, fullCtx); + this.predictedAlt = predictedAlt; + } + }; + LookaheadEventInfo$1 = __decorate([ + __param(3, Decorators_1.NotNull) + ], LookaheadEventInfo$1); + LookaheadEventInfo.LookaheadEventInfo = LookaheadEventInfo$1; + + return LookaheadEventInfo; +} + +var PredicateEvalInfo = {}; + +var hasRequiredPredicateEvalInfo; + +function requirePredicateEvalInfo () { + if (hasRequiredPredicateEvalInfo) return PredicateEvalInfo; + hasRequiredPredicateEvalInfo = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (PredicateEvalInfo && PredicateEvalInfo.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (PredicateEvalInfo && PredicateEvalInfo.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(PredicateEvalInfo, "__esModule", { value: true }); + PredicateEvalInfo.PredicateEvalInfo = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:35.1914305-07:00 + const DecisionEventInfo_1 = requireDecisionEventInfo(); + const Decorators_1 = requireDecorators(); + /** + * This class represents profiling event information for semantic predicate + * evaluations which occur during prediction. + * + * @see ParserATNSimulator#evalSemanticContext + * + * @since 4.3 + */ + let PredicateEvalInfo$1 = class PredicateEvalInfo extends DecisionEventInfo_1.DecisionEventInfo { + /** + * Constructs a new instance of the {@link PredicateEvalInfo} class with the + * specified detailed predicate evaluation information. + * + * @param state The simulator state + * @param decision The decision number + * @param input The input token stream + * @param startIndex The start index for the current prediction + * @param stopIndex The index at which the predicate evaluation was + * triggered. Note that the input stream may be reset to other positions for + * the actual evaluation of individual predicates. + * @param semctx The semantic context which was evaluated + * @param evalResult The results of evaluating the semantic context + * @param predictedAlt The alternative number for the decision which is + * guarded by the semantic context `semctx`. See {@link #predictedAlt} + * for more information. + * + * @see ParserATNSimulator#evalSemanticContext(SemanticContext, ParserRuleContext, int) + * @see SemanticContext#eval(Recognizer, RuleContext) + */ + constructor(state, decision, input, startIndex, stopIndex, semctx, evalResult, predictedAlt) { + super(decision, state, input, startIndex, stopIndex, state.useContext); + this.semctx = semctx; + this.evalResult = evalResult; + this.predictedAlt = predictedAlt; + } + }; + PredicateEvalInfo$1 = __decorate([ + __param(0, Decorators_1.NotNull), + __param(2, Decorators_1.NotNull), + __param(5, Decorators_1.NotNull) + ], PredicateEvalInfo$1); + PredicateEvalInfo.PredicateEvalInfo = PredicateEvalInfo$1; + + return PredicateEvalInfo; +} + +var hasRequiredProfilingATNSimulator; + +function requireProfilingATNSimulator () { + if (hasRequiredProfilingATNSimulator) return ProfilingATNSimulator; + hasRequiredProfilingATNSimulator = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (ProfilingATNSimulator && ProfilingATNSimulator.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (ProfilingATNSimulator && ProfilingATNSimulator.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(ProfilingATNSimulator, "__esModule", { value: true }); + ProfilingATNSimulator.ProfilingATNSimulator = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:36.4188352-07:00 + const AmbiguityInfo_1 = requireAmbiguityInfo(); + const ATN_1 = requireATN(); + const ATNSimulator_1 = requireATNSimulator(); + const ContextSensitivityInfo_1 = requireContextSensitivityInfo(); + const DecisionInfo_1 = requireDecisionInfo(); + const ErrorInfo_1 = requireErrorInfo(); + const Decorators_1 = requireDecorators(); + const LookaheadEventInfo_1 = requireLookaheadEventInfo(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const PredicateEvalInfo_1 = requirePredicateEvalInfo(); + const SemanticContext_1 = requireSemanticContext(); + const SimulatorState_1 = requireSimulatorState(); + /** + * @since 4.3 + */ + let ProfilingATNSimulator$1 = class ProfilingATNSimulator extends ParserATNSimulator_1.ParserATNSimulator { + constructor(parser) { + super(parser.interpreter.atn, parser); + this._startIndex = 0; + this._sllStopIndex = 0; + this._llStopIndex = 0; + this.currentDecision = 0; + /** At the point of LL failover, we record how SLL would resolve the conflict so that + * we can determine whether or not a decision / input pair is context-sensitive. + * If LL gives a different result than SLL's predicted alternative, we have a + * context sensitivity for sure. The converse is not necessarily true, however. + * It's possible that after conflict resolution chooses minimum alternatives, + * SLL could get the same answer as LL. Regardless of whether or not the result indicates + * an ambiguity, it is not treated as a context sensitivity because LL prediction + * was not required in order to produce a correct prediction for this decision and input sequence. + * It may in fact still be a context sensitivity but we don't know by looking at the + * minimum alternatives for the current input. + */ + this.conflictingAltResolvedBySLL = 0; + this.optimize_ll1 = false; + this.reportAmbiguities = true; + this.numDecisions = this.atn.decisionToState.length; + this.decisions = []; + for (let i = 0; i < this.numDecisions; i++) { + this.decisions.push(new DecisionInfo_1.DecisionInfo(i)); + } + } + adaptivePredict(input, decision, outerContext, useContext) { + if (useContext !== undefined) { + return super.adaptivePredict(input, decision, outerContext, useContext); + } + try { + this._input = input; + this._startIndex = input.index; + // it's possible for SLL to reach a conflict state without consuming any input + this._sllStopIndex = this._startIndex - 1; + this._llStopIndex = -1; + this.currentDecision = decision; + this.currentState = undefined; + this.conflictingAltResolvedBySLL = ATN_1.ATN.INVALID_ALT_NUMBER; + let start = process.hrtime(); + let alt = super.adaptivePredict(input, decision, outerContext); + let stop = process.hrtime(); + let nanoseconds = (stop[0] - start[0]) * 1000000000; + if (nanoseconds === 0) { + nanoseconds = stop[1] - start[1]; + } + else { + // Add nanoseconds from start to end of that second, plus start of the end second to end + nanoseconds += (1000000000 - start[1]) + stop[1]; + } + this.decisions[decision].timeInPrediction += nanoseconds; + this.decisions[decision].invocations++; + let SLL_k = this._sllStopIndex - this._startIndex + 1; + this.decisions[decision].SLL_TotalLook += SLL_k; + this.decisions[decision].SLL_MinLook = this.decisions[decision].SLL_MinLook === 0 ? SLL_k : Math.min(this.decisions[decision].SLL_MinLook, SLL_k); + if (SLL_k > this.decisions[decision].SLL_MaxLook) { + this.decisions[decision].SLL_MaxLook = SLL_k; + this.decisions[decision].SLL_MaxLookEvent = + new LookaheadEventInfo_1.LookaheadEventInfo(decision, undefined, alt, input, this._startIndex, this._sllStopIndex, false); + } + if (this._llStopIndex >= 0) { + let LL_k = this._llStopIndex - this._startIndex + 1; + this.decisions[decision].LL_TotalLook += LL_k; + this.decisions[decision].LL_MinLook = this.decisions[decision].LL_MinLook === 0 ? LL_k : Math.min(this.decisions[decision].LL_MinLook, LL_k); + if (LL_k > this.decisions[decision].LL_MaxLook) { + this.decisions[decision].LL_MaxLook = LL_k; + this.decisions[decision].LL_MaxLookEvent = + new LookaheadEventInfo_1.LookaheadEventInfo(decision, undefined, alt, input, this._startIndex, this._llStopIndex, true); + } + } + return alt; + } + finally { + this._input = undefined; + this.currentDecision = -1; + } + } + getStartState(dfa, input, outerContext, useContext) { + let state = super.getStartState(dfa, input, outerContext, useContext); + this.currentState = state; + return state; + } + computeStartState(dfa, globalContext, useContext) { + let state = super.computeStartState(dfa, globalContext, useContext); + this.currentState = state; + return state; + } + computeReachSet(dfa, previous, t, contextCache) { + if (this._input === undefined) { + throw new Error("Invalid state"); + } + let reachState = super.computeReachSet(dfa, previous, t, contextCache); + if (reachState == null) { + // no reach on current lookahead symbol. ERROR. + this.decisions[this.currentDecision].errors.push(new ErrorInfo_1.ErrorInfo(this.currentDecision, previous, this._input, this._startIndex, this._input.index)); + } + this.currentState = reachState; + return reachState; + } + getExistingTargetState(previousD, t) { + if (this.currentState === undefined || this._input === undefined) { + throw new Error("Invalid state"); + } + // this method is called after each time the input position advances + if (this.currentState.useContext) { + this._llStopIndex = this._input.index; + } + else { + this._sllStopIndex = this._input.index; + } + let existingTargetState = super.getExistingTargetState(previousD, t); + if (existingTargetState != null) { + // this method is directly called by execDFA; must construct a SimulatorState + // to represent the current state for this case + this.currentState = new SimulatorState_1.SimulatorState(this.currentState.outerContext, existingTargetState, this.currentState.useContext, this.currentState.remainingOuterContext); + if (this.currentState.useContext) { + this.decisions[this.currentDecision].LL_DFATransitions++; + } + else { + this.decisions[this.currentDecision].SLL_DFATransitions++; // count only if we transition over a DFA state + } + if (existingTargetState === ATNSimulator_1.ATNSimulator.ERROR) { + let state = new SimulatorState_1.SimulatorState(this.currentState.outerContext, previousD, this.currentState.useContext, this.currentState.remainingOuterContext); + this.decisions[this.currentDecision].errors.push(new ErrorInfo_1.ErrorInfo(this.currentDecision, state, this._input, this._startIndex, this._input.index)); + } + } + return existingTargetState; + } + computeTargetState(dfa, s, remainingGlobalContext, t, useContext, contextCache) { + let targetState = super.computeTargetState(dfa, s, remainingGlobalContext, t, useContext, contextCache); + if (useContext) { + this.decisions[this.currentDecision].LL_ATNTransitions++; + } + else { + this.decisions[this.currentDecision].SLL_ATNTransitions++; + } + return targetState; + } + evalSemanticContextImpl(pred, parserCallStack, alt) { + if (this.currentState === undefined || this._input === undefined) { + throw new Error("Invalid state"); + } + let result = super.evalSemanticContextImpl(pred, parserCallStack, alt); + if (!(pred instanceof SemanticContext_1.SemanticContext.PrecedencePredicate)) { + let fullContext = this._llStopIndex >= 0; + let stopIndex = fullContext ? this._llStopIndex : this._sllStopIndex; + this.decisions[this.currentDecision].predicateEvals.push(new PredicateEvalInfo_1.PredicateEvalInfo(this.currentState, this.currentDecision, this._input, this._startIndex, stopIndex, pred, result, alt)); + } + return result; + } + reportContextSensitivity(dfa, prediction, acceptState, startIndex, stopIndex) { + if (this._input === undefined) { + throw new Error("Invalid state"); + } + if (prediction !== this.conflictingAltResolvedBySLL) { + this.decisions[this.currentDecision].contextSensitivities.push(new ContextSensitivityInfo_1.ContextSensitivityInfo(this.currentDecision, acceptState, this._input, startIndex, stopIndex)); + } + super.reportContextSensitivity(dfa, prediction, acceptState, startIndex, stopIndex); + } + reportAttemptingFullContext(dfa, conflictingAlts, conflictState, startIndex, stopIndex) { + if (conflictingAlts != null) { + this.conflictingAltResolvedBySLL = conflictingAlts.nextSetBit(0); + } + else { + this.conflictingAltResolvedBySLL = conflictState.s0.configs.getRepresentedAlternatives().nextSetBit(0); + } + this.decisions[this.currentDecision].LL_Fallback++; + super.reportAttemptingFullContext(dfa, conflictingAlts, conflictState, startIndex, stopIndex); + } + reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs) { + if (this.currentState === undefined || this._input === undefined) { + throw new Error("Invalid state"); + } + let prediction; + if (ambigAlts != null) { + prediction = ambigAlts.nextSetBit(0); + } + else { + prediction = configs.getRepresentedAlternatives().nextSetBit(0); + } + if (this.conflictingAltResolvedBySLL !== ATN_1.ATN.INVALID_ALT_NUMBER && prediction !== this.conflictingAltResolvedBySLL) { + // Even though this is an ambiguity we are reporting, we can + // still detect some context sensitivities. Both SLL and LL + // are showing a conflict, hence an ambiguity, but if they resolve + // to different minimum alternatives we have also identified a + // context sensitivity. + this.decisions[this.currentDecision].contextSensitivities.push(new ContextSensitivityInfo_1.ContextSensitivityInfo(this.currentDecision, this.currentState, this._input, startIndex, stopIndex)); + } + this.decisions[this.currentDecision].ambiguities.push(new AmbiguityInfo_1.AmbiguityInfo(this.currentDecision, this.currentState, ambigAlts, this._input, startIndex, stopIndex)); + super.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts, configs); + } + // --------------------------------------------------------------------- + getDecisionInfo() { + return this.decisions; + } + getCurrentState() { + return this.currentState; + } + }; + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], ProfilingATNSimulator$1.prototype, "adaptivePredict", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "getStartState", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "computeStartState", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "computeReachSet", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "getExistingTargetState", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "computeTargetState", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "evalSemanticContextImpl", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "reportContextSensitivity", null); + __decorate([ + Decorators_1.Override + ], ProfilingATNSimulator$1.prototype, "reportAttemptingFullContext", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull), __param(5, Decorators_1.NotNull), __param(6, Decorators_1.NotNull) + ], ProfilingATNSimulator$1.prototype, "reportAmbiguity", null); + ProfilingATNSimulator.ProfilingATNSimulator = ProfilingATNSimulator$1; + + return ProfilingATNSimulator; +} + +var hasRequiredParser$1; + +function requireParser$1 () { + if (hasRequiredParser$1) return Parser; + hasRequiredParser$1 = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (Parser && Parser.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (Parser && Parser.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + var __awaiter = (Parser && Parser.__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(Parser, "__esModule", { value: true }); + Parser.Parser = void 0; + const Utils = requireUtils(); + const ATNDeserializationOptions_1 = requireATNDeserializationOptions(); + const ATNDeserializer_1 = requireATNDeserializer(); + const DefaultErrorStrategy_1 = requireDefaultErrorStrategy(); + const ErrorNode_1 = requireErrorNode(); + const IntegerStack_1 = requireIntegerStack(); + const Lexer_1 = requireLexer(); + const Decorators_1 = requireDecorators(); + const ParseInfo_1 = requireParseInfo(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const ProxyParserErrorListener_1 = requireProxyParserErrorListener(); + const Recognizer_1 = requireRecognizer(); + const TerminalNode_1 = requireTerminalNode(); + const Token_1 = requireToken(); + class TraceListener { + constructor(ruleNames, tokenStream) { + this.ruleNames = ruleNames; + this.tokenStream = tokenStream; + } + enterEveryRule(ctx) { + console.log("enter " + this.ruleNames[ctx.ruleIndex] + + ", LT(1)=" + this.tokenStream.LT(1).text); + } + exitEveryRule(ctx) { + console.log("exit " + this.ruleNames[ctx.ruleIndex] + + ", LT(1)=" + this.tokenStream.LT(1).text); + } + visitErrorNode(node) { + // intentionally empty + } + visitTerminal(node) { + let parent = node.parent.ruleContext; + let token = node.symbol; + console.log("consume " + token + " rule " + this.ruleNames[parent.ruleIndex]); + } + } + __decorate([ + Decorators_1.Override + ], TraceListener.prototype, "enterEveryRule", null); + __decorate([ + Decorators_1.Override + ], TraceListener.prototype, "exitEveryRule", null); + __decorate([ + Decorators_1.Override + ], TraceListener.prototype, "visitErrorNode", null); + __decorate([ + Decorators_1.Override + ], TraceListener.prototype, "visitTerminal", null); + /** This is all the parsing support code essentially; most of it is error recovery stuff. */ + let Parser$1 = class Parser extends Recognizer_1.Recognizer { + constructor(input) { + super(); + /** + * The error handling strategy for the parser. The default value is a new + * instance of {@link DefaultErrorStrategy}. + * + * @see #getErrorHandler + * @see #setErrorHandler + */ + this._errHandler = new DefaultErrorStrategy_1.DefaultErrorStrategy(); + this._precedenceStack = new IntegerStack_1.IntegerStack(); + /** + * Specifies whether or not the parser should construct a parse tree during + * the parsing process. The default value is `true`. + * + * @see `buildParseTree` + */ + this._buildParseTrees = true; + /** + * The list of {@link ParseTreeListener} listeners registered to receive + * events during the parse. + * + * @see #addParseListener + */ + this._parseListeners = []; + /** + * The number of syntax errors reported during parsing. This value is + * incremented each time {@link #notifyErrorListeners} is called. + */ + this._syntaxErrors = 0; + /** Indicates parser has match()ed EOF token. See {@link #exitRule()}. */ + this.matchedEOF = false; + this._precedenceStack.push(0); + this.inputStream = input; + } + reset(resetInput) { + // Note: this method executes when not parsing, so _ctx can be undefined + if (resetInput === undefined || resetInput) { + this.inputStream.seek(0); + } + this._errHandler.reset(this); + this._ctx = undefined; + this._syntaxErrors = 0; + this.matchedEOF = false; + this.isTrace = false; + this._precedenceStack.clear(); + this._precedenceStack.push(0); + let interpreter = this.interpreter; + if (interpreter != null) { + interpreter.reset(); + } + } + /** + * Match current input symbol against `ttype`. If the symbol type + * matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are + * called to complete the match process. + * + * If the symbol type does not match, + * {@link ANTLRErrorStrategy#recoverInline} is called on the current error + * strategy to attempt recovery. If {@link #getBuildParseTree} is + * `true` and the token index of the symbol returned by + * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to + * the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then + * {@link ParserRuleContext#addErrorNode(ErrorNode)}. + * + * @param ttype the token type to match + * @returns the matched symbol + * @ if the current input symbol did not match + * `ttype` and the error strategy could not recover from the + * mismatched symbol + */ + match(ttype) { + let t = this.currentToken; + if (t.type === ttype) { + if (ttype === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + else { + t = this._errHandler.recoverInline(this); + if (this._buildParseTrees && t.tokenIndex === -1) { + // we must have conjured up a new token during single token insertion + // if it's not the current symbol + this._ctx.addErrorNode(this.createErrorNode(this._ctx, t)); + } + } + return t; + } + /** + * Match current input symbol as a wildcard. If the symbol type matches + * (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch} + * and {@link #consume} are called to complete the match process. + * + * If the symbol type does not match, + * {@link ANTLRErrorStrategy#recoverInline} is called on the current error + * strategy to attempt recovery. If {@link #getBuildParseTree} is + * `true` and the token index of the symbol returned by + * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to + * the parse tree by calling {@link Parser#createErrorNode(ParserRuleContext, Token)} then + * {@link ParserRuleContext#addErrorNode(ErrorNode)}. + * + * @returns the matched symbol + * @ if the current input symbol did not match + * a wildcard and the error strategy could not recover from the mismatched + * symbol + */ + matchWildcard() { + let t = this.currentToken; + if (t.type > 0) { + this._errHandler.reportMatch(this); + this.consume(); + } + else { + t = this._errHandler.recoverInline(this); + if (this._buildParseTrees && t.tokenIndex === -1) { + // we must have conjured up a new token during single token insertion + // if it's not the current symbol + this._ctx.addErrorNode(this.createErrorNode(this._ctx, t)); + } + } + return t; + } + /** + * Track the {@link ParserRuleContext} objects during the parse and hook + * them up using the {@link ParserRuleContext#children} list so that it + * forms a parse tree. The {@link ParserRuleContext} returned from the start + * rule represents the root of the parse tree. + * + * Note that if we are not building parse trees, rule contexts only point + * upwards. When a rule exits, it returns the context but that gets garbage + * collected if nobody holds a reference. It points upwards but nobody + * points at it. + * + * When we build parse trees, we are adding all of these contexts to + * {@link ParserRuleContext#children} list. Contexts are then not candidates + * for garbage collection. + */ + set buildParseTree(buildParseTrees) { + this._buildParseTrees = buildParseTrees; + } + /** + * Gets whether or not a complete parse tree will be constructed while + * parsing. This property is `true` for a newly constructed parser. + * + * @returns `true` if a complete parse tree will be constructed while + * parsing, otherwise `false` + */ + get buildParseTree() { + return this._buildParseTrees; + } + getParseListeners() { + return this._parseListeners; + } + /** + * Registers `listener` to receive events during the parsing process. + * + * To support output-preserving grammar transformations (including but not + * limited to left-recursion removal, automated left-factoring, and + * optimized code generation), calls to listener methods during the parse + * may differ substantially from calls made by + * {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In + * particular, rule entry and exit events may occur in a different order + * during the parse than after the parser. In addition, calls to certain + * rule entry methods may be omitted. + * + * With the following specific exceptions, calls to listener events are + * *deterministic*, i.e. for identical input the calls to listener + * methods will be the same. + * + * * Alterations to the grammar used to generate code may change the + * behavior of the listener calls. + * * Alterations to the command line options passed to ANTLR 4 when + * generating the parser may change the behavior of the listener calls. + * * Changing the version of the ANTLR Tool used to generate the parser + * may change the behavior of the listener calls. + * + * @param listener the listener to add + * + * @throws {@link TypeError} if `listener` is `undefined` + */ + addParseListener(listener) { + if (listener == null) { + throw new TypeError("listener cannot be null"); + } + this._parseListeners.push(listener); + } + /** + * Remove `listener` from the list of parse listeners. + * + * If `listener` is `undefined` or has not been added as a parse + * listener, this method does nothing. + * + * @see #addParseListener + * + * @param listener the listener to remove + */ + removeParseListener(listener) { + let index = this._parseListeners.findIndex((l) => l === listener); + if (index !== -1) { + this._parseListeners.splice(index, 1); + } + } + /** + * Remove all parse listeners. + * + * @see #addParseListener + */ + removeParseListeners() { + this._parseListeners.length = 0; + } + /** + * Notify any parse listeners of an enter rule event. + * + * @see #addParseListener + */ + triggerEnterRuleEvent() { + for (let listener of this._parseListeners) { + if (listener.enterEveryRule) { + listener.enterEveryRule(this._ctx); + } + this._ctx.enterRule(listener); + } + } + /** + * Notify any parse listeners of an exit rule event. + * + * @see #addParseListener + */ + triggerExitRuleEvent() { + // reverse order walk of listeners + for (let i = this._parseListeners.length - 1; i >= 0; i--) { + let listener = this._parseListeners[i]; + this._ctx.exitRule(listener); + if (listener.exitEveryRule) { + listener.exitEveryRule(this._ctx); + } + } + } + /** + * Gets the number of syntax errors reported during parsing. This value is + * incremented each time {@link #notifyErrorListeners} is called. + * + * @see #notifyErrorListeners + */ + get numberOfSyntaxErrors() { + return this._syntaxErrors; + } + get tokenFactory() { + return this._input.tokenSource.tokenFactory; + } + /** + * The ATN with bypass alternatives is expensive to create so we create it + * lazily. + * + * @ if the current parser does not + * implement the `serializedATN` property. + */ + getATNWithBypassAlts() { + let serializedAtn = this.serializedATN; + if (serializedAtn == null) { + throw new Error("The current parser does not support an ATN with bypass alternatives."); + } + let result = Parser.bypassAltsAtnCache.get(serializedAtn); + if (result == null) { + let deserializationOptions = new ATNDeserializationOptions_1.ATNDeserializationOptions(); + deserializationOptions.isGenerateRuleBypassTransitions = true; + result = new ATNDeserializer_1.ATNDeserializer(deserializationOptions).deserialize(Utils.toCharArray(serializedAtn)); + Parser.bypassAltsAtnCache.set(serializedAtn, result); + } + return result; + } + compileParseTreePattern(pattern, patternRuleIndex, lexer) { + return __awaiter(this, void 0, void 0, function* () { + if (!lexer) { + if (this.inputStream) { + let tokenSource = this.inputStream.tokenSource; + if (tokenSource instanceof Lexer_1.Lexer) { + lexer = tokenSource; + } + } + if (!lexer) { + throw new Error("Parser can't discover a lexer to use"); + } + } + let currentLexer = lexer; + let m = yield Promise.resolve().then(() => requireParseTreePatternMatcher()); + let matcher = new m.ParseTreePatternMatcher(currentLexer, this); + return matcher.compile(pattern, patternRuleIndex); + }); + } + get errorHandler() { + return this._errHandler; + } + set errorHandler(handler) { + this._errHandler = handler; + } + get inputStream() { + return this._input; + } + /** Set the token stream and reset the parser. */ + set inputStream(input) { + this.reset(false); + this._input = input; + } + /** Match needs to return the current input symbol, which gets put + * into the label for the associated token ref; e.g., x=ID. + */ + get currentToken() { + return this._input.LT(1); + } + notifyErrorListeners(msg, offendingToken, e) { + if (offendingToken === undefined) { + offendingToken = this.currentToken; + } + else if (offendingToken === null) { + offendingToken = undefined; + } + this._syntaxErrors++; + let line = -1; + let charPositionInLine = -1; + if (offendingToken != null) { + line = offendingToken.line; + charPositionInLine = offendingToken.charPositionInLine; + } + let listener = this.getErrorListenerDispatch(); + if (listener.syntaxError) { + listener.syntaxError(this, offendingToken, line, charPositionInLine, msg, e); + } + } + /** + * Consume and return the [current symbol](`currentToken`). + * + * E.g., given the following input with `A` being the current + * lookahead symbol, this function moves the cursor to `B` and returns + * `A`. + * + * ``` + * A B + * ^ + * ``` + * + * If the parser is not in error recovery mode, the consumed symbol is added + * to the parse tree using {@link ParserRuleContext#addChild(TerminalNode)}, and + * {@link ParseTreeListener#visitTerminal} is called on any parse listeners. + * If the parser *is* in error recovery mode, the consumed symbol is + * added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then + * {@link ParserRuleContext#addErrorNode(ErrorNode)} and + * {@link ParseTreeListener#visitErrorNode} is called on any parse + * listeners. + */ + consume() { + let o = this.currentToken; + if (o.type !== Parser.EOF) { + this.inputStream.consume(); + } + let hasListener = this._parseListeners.length !== 0; + if (this._buildParseTrees || hasListener) { + if (this._errHandler.inErrorRecoveryMode(this)) { + let node = this._ctx.addErrorNode(this.createErrorNode(this._ctx, o)); + if (hasListener) { + for (let listener of this._parseListeners) { + if (listener.visitErrorNode) { + listener.visitErrorNode(node); + } + } + } + } + else { + let node = this.createTerminalNode(this._ctx, o); + this._ctx.addChild(node); + if (hasListener) { + for (let listener of this._parseListeners) { + if (listener.visitTerminal) { + listener.visitTerminal(node); + } + } + } + } + } + return o; + } + /** + * How to create a token leaf node associated with a parent. + * Typically, the terminal node to create is not a function of the parent. + * + * @since 4.7 + */ + createTerminalNode(parent, t) { + return new TerminalNode_1.TerminalNode(t); + } + /** + * How to create an error node, given a token, associated with a parent. + * Typically, the error node to create is not a function of the parent. + * + * @since 4.7 + */ + createErrorNode(parent, t) { + return new ErrorNode_1.ErrorNode(t); + } + addContextToParseTree() { + let parent = this._ctx._parent; + // add current context to parent if we have a parent + if (parent != null) { + parent.addChild(this._ctx); + } + } + /** + * Always called by generated parsers upon entry to a rule. Access field + * {@link #_ctx} get the current context. + */ + enterRule(localctx, state, ruleIndex) { + this.state = state; + this._ctx = localctx; + this._ctx._start = this._input.LT(1); + if (this._buildParseTrees) { + this.addContextToParseTree(); + } + this.triggerEnterRuleEvent(); + } + enterLeftFactoredRule(localctx, state, ruleIndex) { + this.state = state; + if (this._buildParseTrees) { + let factoredContext = this._ctx.getChild(this._ctx.childCount - 1); + this._ctx.removeLastChild(); + factoredContext._parent = localctx; + localctx.addChild(factoredContext); + } + this._ctx = localctx; + this._ctx._start = this._input.LT(1); + if (this._buildParseTrees) { + this.addContextToParseTree(); + } + this.triggerEnterRuleEvent(); + } + exitRule() { + if (this.matchedEOF) { + // if we have matched EOF, it cannot consume past EOF so we use LT(1) here + this._ctx._stop = this._input.LT(1); // LT(1) will be end of file + } + else { + this._ctx._stop = this._input.tryLT(-1); // stop node is what we just matched + } + // trigger event on _ctx, before it reverts to parent + this.triggerExitRuleEvent(); + this.state = this._ctx.invokingState; + this._ctx = this._ctx._parent; + } + enterOuterAlt(localctx, altNum) { + localctx.altNumber = altNum; + // if we have new localctx, make sure we replace existing ctx + // that is previous child of parse tree + if (this._buildParseTrees && this._ctx !== localctx) { + let parent = this._ctx._parent; + if (parent != null) { + parent.removeLastChild(); + parent.addChild(localctx); + } + } + this._ctx = localctx; + } + /** + * Get the precedence level for the top-most precedence rule. + * + * @returns The precedence level for the top-most precedence rule, or -1 if + * the parser context is not nested within a precedence rule. + */ + get precedence() { + if (this._precedenceStack.isEmpty) { + return -1; + } + return this._precedenceStack.peek(); + } + enterRecursionRule(localctx, state, ruleIndex, precedence) { + this.state = state; + this._precedenceStack.push(precedence); + this._ctx = localctx; + this._ctx._start = this._input.LT(1); + this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules + } + /** Like {@link #enterRule} but for recursive rules. + * Make the current context the child of the incoming localctx. + */ + pushNewRecursionContext(localctx, state, ruleIndex) { + let previous = this._ctx; + previous._parent = localctx; + previous.invokingState = state; + previous._stop = this._input.tryLT(-1); + this._ctx = localctx; + this._ctx._start = previous._start; + if (this._buildParseTrees) { + this._ctx.addChild(previous); + } + this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules + } + unrollRecursionContexts(_parentctx) { + this._precedenceStack.pop(); + this._ctx._stop = this._input.tryLT(-1); + let retctx = this._ctx; // save current ctx (return value) + // unroll so _ctx is as it was before call to recursive method + if (this._parseListeners.length > 0) { + while (this._ctx !== _parentctx) { + this.triggerExitRuleEvent(); + this._ctx = this._ctx._parent; + } + } + else { + this._ctx = _parentctx; + } + // hook into tree + retctx._parent = _parentctx; + if (this._buildParseTrees && _parentctx != null) { + // add return ctx into invoking rule's tree + _parentctx.addChild(retctx); + } + } + getInvokingContext(ruleIndex) { + let p = this._ctx; + while (p && p.ruleIndex !== ruleIndex) { + p = p._parent; + } + return p; + } + get context() { + return this._ctx; + } + set context(ctx) { + this._ctx = ctx; + } + precpred(localctx, precedence) { + return precedence >= this._precedenceStack.peek(); + } + getErrorListenerDispatch() { + return new ProxyParserErrorListener_1.ProxyParserErrorListener(this.getErrorListeners()); + } + inContext(context) { + // TODO: useful in parser? + return false; + } + /** + * Checks whether or not `symbol` can follow the current state in the + * ATN. The behavior of this method is equivalent to the following, but is + * implemented such that the complete context-sensitive follow set does not + * need to be explicitly constructed. + * + * ``` + * return getExpectedTokens().contains(symbol); + * ``` + * + * @param symbol the symbol type to check + * @returns `true` if `symbol` can follow the current state in + * the ATN, otherwise `false`. + */ + isExpectedToken(symbol) { + // return interpreter.atn.nextTokens(_ctx); + let atn = this.interpreter.atn; + let ctx = this._ctx; + let s = atn.states[this.state]; + let following = atn.nextTokens(s); + if (following.contains(symbol)) { + return true; + } + // System.out.println("following "+s+"="+following); + if (!following.contains(Token_1.Token.EPSILON)) { + return false; + } + while (ctx != null && ctx.invokingState >= 0 && following.contains(Token_1.Token.EPSILON)) { + let invokingState = atn.states[ctx.invokingState]; + let rt = invokingState.transition(0); + following = atn.nextTokens(rt.followState); + if (following.contains(symbol)) { + return true; + } + ctx = ctx._parent; + } + if (following.contains(Token_1.Token.EPSILON) && symbol === Token_1.Token.EOF) { + return true; + } + return false; + } + get isMatchedEOF() { + return this.matchedEOF; + } + /** + * Computes the set of input symbols which could follow the current parser + * state and context, as given by {@link #getState} and {@link #getContext}, + * respectively. + * + * @see ATN#getExpectedTokens(int, RuleContext) + */ + getExpectedTokens() { + return this.atn.getExpectedTokens(this.state, this.context); + } + getExpectedTokensWithinCurrentRule() { + let atn = this.interpreter.atn; + let s = atn.states[this.state]; + return atn.nextTokens(s); + } + /** Get a rule's index (i.e., `RULE_ruleName` field) or -1 if not found. */ + getRuleIndex(ruleName) { + let ruleIndex = this.getRuleIndexMap().get(ruleName); + if (ruleIndex != null) { + return ruleIndex; + } + return -1; + } + get ruleContext() { return this._ctx; } + /** Return List<String> of the rule names in your parser instance + * leading up to a call to the current rule. You could override if + * you want more details such as the file/line info of where + * in the ATN a rule is invoked. + * + * This is very useful for error messages. + */ + getRuleInvocationStack(ctx = this._ctx) { + let p = ctx; // Workaround for Microsoft/TypeScript#14487 + let ruleNames = this.ruleNames; + let stack = []; + while (p != null) { + // compute what follows who invoked us + let ruleIndex = p.ruleIndex; + if (ruleIndex < 0) { + stack.push("n/a"); + } + else { + stack.push(ruleNames[ruleIndex]); + } + p = p._parent; + } + return stack; + } + /** For debugging and other purposes. */ + getDFAStrings() { + let s = []; + for (let dfa of this._interp.atn.decisionToDFA) { + s.push(dfa.toString(this.vocabulary, this.ruleNames)); + } + return s; + } + /** For debugging and other purposes. */ + dumpDFA() { + let seenOne = false; + for (let dfa of this._interp.atn.decisionToDFA) { + if (!dfa.isEmpty) { + if (seenOne) { + console.log(); + } + console.log("Decision " + dfa.decision + ":"); + process.stdout.write(dfa.toString(this.vocabulary, this.ruleNames)); + seenOne = true; + } + } + } + get sourceName() { + return this._input.sourceName; + } + get parseInfo() { + return Promise.resolve().then(() => requireProfilingATNSimulator()).then((m) => { + let interp = this.interpreter; + if (interp instanceof m.ProfilingATNSimulator) { + return new ParseInfo_1.ParseInfo(interp); + } + return undefined; + }); + } + /** + * @since 4.3 + */ + setProfile(profile) { + return __awaiter(this, void 0, void 0, function* () { + let m = yield Promise.resolve().then(() => requireProfilingATNSimulator()); + let interp = this.interpreter; + if (profile) { + if (!(interp instanceof m.ProfilingATNSimulator)) { + this.interpreter = new m.ProfilingATNSimulator(this); + } + } + else if (interp instanceof m.ProfilingATNSimulator) { + this.interpreter = new ParserATNSimulator_1.ParserATNSimulator(this.atn, this); + } + this.interpreter.setPredictionMode(interp.getPredictionMode()); + }); + } + /** During a parse is sometimes useful to listen in on the rule entry and exit + * events as well as token matches. This is for quick and dirty debugging. + */ + set isTrace(trace) { + if (!trace) { + if (this._tracer) { + this.removeParseListener(this._tracer); + this._tracer = undefined; + } + } + else { + if (this._tracer) { + this.removeParseListener(this._tracer); + } + else { + this._tracer = new TraceListener(this.ruleNames, this._input); + } + this.addParseListener(this._tracer); + } + } + /** + * Gets whether a {@link TraceListener} is registered as a parse listener + * for the parser. + */ + get isTrace() { + return this._tracer != null; + } + }; + /** + * This field maps from the serialized ATN string to the deserialized {@link ATN} with + * bypass alternatives. + * + * @see ATNDeserializationOptions.isGenerateRuleBypassTransitions + */ + Parser$1.bypassAltsAtnCache = new Map(); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "_errHandler", void 0); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "match", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "matchWildcard", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "getParseListeners", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], Parser$1.prototype, "addParseListener", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "getATNWithBypassAlts", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], Parser$1.prototype, "errorHandler", null); + __decorate([ + Decorators_1.Override + ], Parser$1.prototype, "inputStream", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "currentToken", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], Parser$1.prototype, "enterRule", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.Nullable) + ], Parser$1.prototype, "precpred", null); + __decorate([ + Decorators_1.Override + ], Parser$1.prototype, "getErrorListenerDispatch", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "getExpectedTokens", null); + __decorate([ + Decorators_1.NotNull + ], Parser$1.prototype, "getExpectedTokensWithinCurrentRule", null); + __decorate([ + Decorators_1.Override + ], Parser$1.prototype, "parseInfo", null); + Parser.Parser = Parser$1; + + return Parser; +} + +var hasRequiredNoViableAltException; + +function requireNoViableAltException () { + if (hasRequiredNoViableAltException) return NoViableAltException; + hasRequiredNoViableAltException = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (NoViableAltException && NoViableAltException.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(NoViableAltException, "__esModule", { value: true }); + NoViableAltException.NoViableAltException = void 0; + const Parser_1 = requireParser$1(); + const RecognitionException_1 = requireRecognitionException(); + const Decorators_1 = requireDecorators(); + /** Indicates that the parser could not decide which of two or more paths + * to take based upon the remaining input. It tracks the starting token + * of the offending input and also knows where the parser was + * in the various paths when the error. Reported by reportNoViableAlternative() + */ + let NoViableAltException$1 = class NoViableAltException extends RecognitionException_1.RecognitionException { + constructor(recognizer, input, startToken, offendingToken, deadEndConfigs, ctx) { + if (recognizer instanceof Parser_1.Parser) { + if (input === undefined) { + input = recognizer.inputStream; + } + if (startToken === undefined) { + startToken = recognizer.currentToken; + } + if (offendingToken === undefined) { + offendingToken = recognizer.currentToken; + } + if (ctx === undefined) { + ctx = recognizer.context; + } + } + super(recognizer, input, ctx); + this._deadEndConfigs = deadEndConfigs; + this._startToken = startToken; + this.setOffendingToken(recognizer, offendingToken); + } + get startToken() { + return this._startToken; + } + get deadEndConfigs() { + return this._deadEndConfigs; + } + }; + __decorate([ + Decorators_1.NotNull + ], NoViableAltException$1.prototype, "_startToken", void 0); + NoViableAltException.NoViableAltException = NoViableAltException$1; + + return NoViableAltException; +} + +var hasRequiredDefaultErrorStrategy; + +function requireDefaultErrorStrategy () { + if (hasRequiredDefaultErrorStrategy) return DefaultErrorStrategy; + hasRequiredDefaultErrorStrategy = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DefaultErrorStrategy && DefaultErrorStrategy.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (DefaultErrorStrategy && DefaultErrorStrategy.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(DefaultErrorStrategy, "__esModule", { value: true }); + DefaultErrorStrategy.DefaultErrorStrategy = void 0; + const ATNState_1 = requireATNState(); + const ATNStateType_1 = requireATNStateType(); + const FailedPredicateException_1 = requireFailedPredicateException(); + const InputMismatchException_1 = requireInputMismatchException(); + const IntervalSet_1 = requireIntervalSet(); + const NoViableAltException_1 = requireNoViableAltException(); + const PredictionContext_1 = requirePredictionContext(); + const Token_1 = requireToken(); + const Decorators_1 = requireDecorators(); + /** + * This is the default implementation of {@link ANTLRErrorStrategy} used for + * error reporting and recovery in ANTLR parsers. + */ + let DefaultErrorStrategy$1 = class DefaultErrorStrategy { + constructor() { + /** + * Indicates whether the error strategy is currently "recovering from an + * error". This is used to suppress reporting multiple error messages while + * attempting to recover from a detected syntax error. + * + * @see #inErrorRecoveryMode + */ + this.errorRecoveryMode = false; + /** The index into the input stream where the last error occurred. + * This is used to prevent infinite loops where an error is found + * but no token is consumed during recovery...another error is found, + * ad nauseum. This is a failsafe mechanism to guarantee that at least + * one token/tree node is consumed for two errors. + */ + this.lastErrorIndex = -1; + /** + * @see #nextTokensContext + */ + this.nextTokensState = ATNState_1.ATNState.INVALID_STATE_NUMBER; + } + /** + * {@inheritDoc} + * + * The default implementation simply calls {@link #endErrorCondition} to + * ensure that the handler is not in error recovery mode. + */ + reset(recognizer) { + this.endErrorCondition(recognizer); + } + /** + * This method is called to enter error recovery mode when a recognition + * exception is reported. + * + * @param recognizer the parser instance + */ + beginErrorCondition(recognizer) { + this.errorRecoveryMode = true; + } + /** + * {@inheritDoc} + */ + inErrorRecoveryMode(recognizer) { + return this.errorRecoveryMode; + } + /** + * This method is called to leave error recovery mode after recovering from + * a recognition exception. + * + * @param recognizer + */ + endErrorCondition(recognizer) { + this.errorRecoveryMode = false; + this.lastErrorStates = undefined; + this.lastErrorIndex = -1; + } + /** + * {@inheritDoc} + * + * The default implementation simply calls {@link #endErrorCondition}. + */ + reportMatch(recognizer) { + this.endErrorCondition(recognizer); + } + /** + * {@inheritDoc} + * + * The default implementation returns immediately if the handler is already + * in error recovery mode. Otherwise, it calls {@link #beginErrorCondition} + * and dispatches the reporting task based on the runtime type of `e` + * according to the following table. + * + * * {@link NoViableAltException}: Dispatches the call to + * {@link #reportNoViableAlternative} + * * {@link InputMismatchException}: Dispatches the call to + * {@link #reportInputMismatch} + * * {@link FailedPredicateException}: Dispatches the call to + * {@link #reportFailedPredicate} + * * All other types: calls {@link Parser#notifyErrorListeners} to report + * the exception + */ + reportError(recognizer, e) { + // if we've already reported an error and have not matched a token + // yet successfully, don't report any errors. + if (this.inErrorRecoveryMode(recognizer)) { + // System.err.print("[SPURIOUS] "); + return; // don't report spurious errors + } + this.beginErrorCondition(recognizer); + if (e instanceof NoViableAltException_1.NoViableAltException) { + this.reportNoViableAlternative(recognizer, e); + } + else if (e instanceof InputMismatchException_1.InputMismatchException) { + this.reportInputMismatch(recognizer, e); + } + else if (e instanceof FailedPredicateException_1.FailedPredicateException) { + this.reportFailedPredicate(recognizer, e); + } + else { + console.error(`unknown recognition error type: ${e}`); + this.notifyErrorListeners(recognizer, e.toString(), e); + } + } + notifyErrorListeners(recognizer, message, e) { + let offendingToken = e.getOffendingToken(recognizer); + if (offendingToken === undefined) { + // Pass null to notifyErrorListeners so it in turn calls the error listeners with undefined as the offending + // token. If we passed undefined, it would instead call the listeners with currentToken from the parser. + offendingToken = null; + } + recognizer.notifyErrorListeners(message, offendingToken, e); + } + /** + * {@inheritDoc} + * + * The default implementation resynchronizes the parser by consuming tokens + * until we find one in the resynchronization set--loosely the set of tokens + * that can follow the current rule. + */ + recover(recognizer, e) { + // System.out.println("recover in "+recognizer.getRuleInvocationStack()+ + // " index="+recognizer.inputStream.index+ + // ", lastErrorIndex="+ + // lastErrorIndex+ + // ", states="+lastErrorStates); + if (this.lastErrorIndex === recognizer.inputStream.index && + this.lastErrorStates && + this.lastErrorStates.contains(recognizer.state)) { + // uh oh, another error at same token index and previously-visited + // state in ATN; must be a case where LT(1) is in the recovery + // token set so nothing got consumed. Consume a single token + // at least to prevent an infinite loop; this is a failsafe. + // System.err.println("seen error condition before index="+ + // lastErrorIndex+", states="+lastErrorStates); + // System.err.println("FAILSAFE consumes "+recognizer.getTokenNames()[recognizer.inputStream.LA(1)]); + recognizer.consume(); + } + this.lastErrorIndex = recognizer.inputStream.index; + if (!this.lastErrorStates) { + this.lastErrorStates = new IntervalSet_1.IntervalSet(); + } + this.lastErrorStates.add(recognizer.state); + let followSet = this.getErrorRecoverySet(recognizer); + this.consumeUntil(recognizer, followSet); + } + /** + * The default implementation of {@link ANTLRErrorStrategy#sync} makes sure + * that the current lookahead symbol is consistent with what were expecting + * at this point in the ATN. You can call this anytime but ANTLR only + * generates code to check before subrules/loops and each iteration. + * + * Implements Jim Idle's magic sync mechanism in closures and optional + * subrules. E.g., + * + * ```antlr + * a : sync ( stuff sync )* ; + * sync : {consume to what can follow sync} ; + * ``` + * + * At the start of a sub rule upon error, {@link #sync} performs single + * token deletion, if possible. If it can't do that, it bails on the current + * rule and uses the default error recovery, which consumes until the + * resynchronization set of the current rule. + * + * If the sub rule is optional (`(...)?`, `(...)*`, or block + * with an empty alternative), then the expected set includes what follows + * the subrule. + * + * During loop iteration, it consumes until it sees a token that can start a + * sub rule or what follows loop. Yes, that is pretty aggressive. We opt to + * stay in the loop as long as possible. + * + * **ORIGINS** + * + * Previous versions of ANTLR did a poor job of their recovery within loops. + * A single mismatch token or missing token would force the parser to bail + * out of the entire rules surrounding the loop. So, for rule + * + * ```antlr + * classDef : 'class' ID '{' member* '}' + * ``` + * + * input with an extra token between members would force the parser to + * consume until it found the next class definition rather than the next + * member definition of the current class. + * + * This functionality cost a little bit of effort because the parser has to + * compare token set at the start of the loop and at each iteration. If for + * some reason speed is suffering for you, you can turn off this + * functionality by simply overriding this method as a blank { }. + */ + sync(recognizer) { + let s = recognizer.interpreter.atn.states[recognizer.state]; + // System.err.println("sync @ "+s.stateNumber+"="+s.getClass().getSimpleName()); + // If already recovering, don't try to sync + if (this.inErrorRecoveryMode(recognizer)) { + return; + } + let tokens = recognizer.inputStream; + let la = tokens.LA(1); + // try cheaper subset first; might get lucky. seems to shave a wee bit off + let nextTokens = recognizer.atn.nextTokens(s); + if (nextTokens.contains(la)) { + // We are sure the token matches + this.nextTokensContext = undefined; + this.nextTokensState = ATNState_1.ATNState.INVALID_STATE_NUMBER; + return; + } + if (nextTokens.contains(Token_1.Token.EPSILON)) { + if (this.nextTokensContext === undefined) { + // It's possible the next token won't match; information tracked + // by sync is restricted for performance. + this.nextTokensContext = recognizer.context; + this.nextTokensState = recognizer.state; + } + return; + } + switch (s.stateType) { + case ATNStateType_1.ATNStateType.BLOCK_START: + case ATNStateType_1.ATNStateType.STAR_BLOCK_START: + case ATNStateType_1.ATNStateType.PLUS_BLOCK_START: + case ATNStateType_1.ATNStateType.STAR_LOOP_ENTRY: + // report error and recover if possible + if (this.singleTokenDeletion(recognizer)) { + return; + } + throw new InputMismatchException_1.InputMismatchException(recognizer); + case ATNStateType_1.ATNStateType.PLUS_LOOP_BACK: + case ATNStateType_1.ATNStateType.STAR_LOOP_BACK: + // System.err.println("at loop back: "+s.getClass().getSimpleName()); + this.reportUnwantedToken(recognizer); + let expecting = recognizer.getExpectedTokens(); + let whatFollowsLoopIterationOrRule = expecting.or(this.getErrorRecoverySet(recognizer)); + this.consumeUntil(recognizer, whatFollowsLoopIterationOrRule); + break; + } + } + /** + * This is called by {@link #reportError} when the exception is a + * {@link NoViableAltException}. + * + * @see #reportError + * + * @param recognizer the parser instance + * @param e the recognition exception + */ + reportNoViableAlternative(recognizer, e) { + let tokens = recognizer.inputStream; + let input; + if (tokens) { + if (e.startToken.type === Token_1.Token.EOF) { + input = ""; + } + else { + input = tokens.getTextFromRange(e.startToken, e.getOffendingToken()); + } + } + else { + input = ""; + } + let msg = "no viable alternative at input " + this.escapeWSAndQuote(input); + this.notifyErrorListeners(recognizer, msg, e); + } + /** + * This is called by {@link #reportError} when the exception is an + * {@link InputMismatchException}. + * + * @see #reportError + * + * @param recognizer the parser instance + * @param e the recognition exception + */ + reportInputMismatch(recognizer, e) { + let expected = e.expectedTokens; + let expectedString = expected ? expected.toStringVocabulary(recognizer.vocabulary) : ""; + let msg = "mismatched input " + this.getTokenErrorDisplay(e.getOffendingToken(recognizer)) + + " expecting " + expectedString; + this.notifyErrorListeners(recognizer, msg, e); + } + /** + * This is called by {@link #reportError} when the exception is a + * {@link FailedPredicateException}. + * + * @see #reportError + * + * @param recognizer the parser instance + * @param e the recognition exception + */ + reportFailedPredicate(recognizer, e) { + let ruleName = recognizer.ruleNames[recognizer.context.ruleIndex]; + let msg = "rule " + ruleName + " " + e.message; + this.notifyErrorListeners(recognizer, msg, e); + } + /** + * This method is called to report a syntax error which requires the removal + * of a token from the input stream. At the time this method is called, the + * erroneous symbol is current `LT(1)` symbol and has not yet been + * removed from the input stream. When this method returns, + * `recognizer` is in error recovery mode. + * + * This method is called when {@link #singleTokenDeletion} identifies + * single-token deletion as a viable recovery strategy for a mismatched + * input error. + * + * The default implementation simply returns if the handler is already in + * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + * enter error recovery mode, followed by calling + * {@link Parser#notifyErrorListeners}. + * + * @param recognizer the parser instance + */ + reportUnwantedToken(recognizer) { + if (this.inErrorRecoveryMode(recognizer)) { + return; + } + this.beginErrorCondition(recognizer); + let t = recognizer.currentToken; + let tokenName = this.getTokenErrorDisplay(t); + let expecting = this.getExpectedTokens(recognizer); + let msg = "extraneous input " + tokenName + " expecting " + + expecting.toStringVocabulary(recognizer.vocabulary); + recognizer.notifyErrorListeners(msg, t, undefined); + } + /** + * This method is called to report a syntax error which requires the + * insertion of a missing token into the input stream. At the time this + * method is called, the missing token has not yet been inserted. When this + * method returns, `recognizer` is in error recovery mode. + * + * This method is called when {@link #singleTokenInsertion} identifies + * single-token insertion as a viable recovery strategy for a mismatched + * input error. + * + * The default implementation simply returns if the handler is already in + * error recovery mode. Otherwise, it calls {@link #beginErrorCondition} to + * enter error recovery mode, followed by calling + * {@link Parser#notifyErrorListeners}. + * + * @param recognizer the parser instance + */ + reportMissingToken(recognizer) { + if (this.inErrorRecoveryMode(recognizer)) { + return; + } + this.beginErrorCondition(recognizer); + let t = recognizer.currentToken; + let expecting = this.getExpectedTokens(recognizer); + let msg = "missing " + expecting.toStringVocabulary(recognizer.vocabulary) + + " at " + this.getTokenErrorDisplay(t); + recognizer.notifyErrorListeners(msg, t, undefined); + } + /** + * {@inheritDoc} + * + * The default implementation attempts to recover from the mismatched input + * by using single token insertion and deletion as described below. If the + * recovery attempt fails, this method + * {@link InputMismatchException}. + * + * **EXTRA TOKEN** (single token deletion) + * + * `LA(1)` is not what we are looking for. If `LA(2)` has the + * right token, however, then assume `LA(1)` is some extra spurious + * token and delete it. Then consume and return the next token (which was + * the `LA(2)` token) as the successful result of the match operation. + * + * This recovery strategy is implemented by {@link #singleTokenDeletion}. + * + * **MISSING TOKEN** (single token insertion) + * + * If current token (at `LA(1)`) is consistent with what could come + * after the expected `LA(1)` token, then assume the token is missing + * and use the parser's {@link TokenFactory} to create it on the fly. The + * "insertion" is performed by returning the created token as the successful + * result of the match operation. + * + * This recovery strategy is implemented by {@link #singleTokenInsertion}. + * + * **EXAMPLE** + * + * For example, Input `i=(3;` is clearly missing the `')'`. When + * the parser returns from the nested call to `expr`, it will have + * call chain: + * + * ``` + * stat → expr → atom + * ``` + * + * and it will be trying to match the `')'` at this point in the + * derivation: + * + * ``` + * => ID '=' '(' INT ')' ('+' atom)* ';' + * ^ + * ``` + * + * The attempt to match `')'` will fail when it sees `';'` and + * call {@link #recoverInline}. To recover, it sees that `LA(1)==';'` + * is in the set of tokens that can follow the `')'` token reference + * in rule `atom`. It can assume that you forgot the `')'`. + */ + recoverInline(recognizer) { + // SINGLE TOKEN DELETION + let matchedSymbol = this.singleTokenDeletion(recognizer); + if (matchedSymbol) { + // we have deleted the extra token. + // now, move past ttype token as if all were ok + recognizer.consume(); + return matchedSymbol; + } + // SINGLE TOKEN INSERTION + if (this.singleTokenInsertion(recognizer)) { + return this.getMissingSymbol(recognizer); + } + // even that didn't work; must throw the exception + if (this.nextTokensContext === undefined) { + throw new InputMismatchException_1.InputMismatchException(recognizer); + } + else { + throw new InputMismatchException_1.InputMismatchException(recognizer, this.nextTokensState, this.nextTokensContext); + } + } + /** + * This method implements the single-token insertion inline error recovery + * strategy. It is called by {@link #recoverInline} if the single-token + * deletion strategy fails to recover from the mismatched input. If this + * method returns `true`, `recognizer` will be in error recovery + * mode. + * + * This method determines whether or not single-token insertion is viable by + * checking if the `LA(1)` input symbol could be successfully matched + * if it were instead the `LA(2)` symbol. If this method returns + * `true`, the caller is responsible for creating and inserting a + * token with the correct type to produce this behavior. + * + * @param recognizer the parser instance + * @returns `true` if single-token insertion is a viable recovery + * strategy for the current mismatched input, otherwise `false` + */ + singleTokenInsertion(recognizer) { + let currentSymbolType = recognizer.inputStream.LA(1); + // if current token is consistent with what could come after current + // ATN state, then we know we're missing a token; error recovery + // is free to conjure up and insert the missing token + let currentState = recognizer.interpreter.atn.states[recognizer.state]; + let next = currentState.transition(0).target; + let atn = recognizer.interpreter.atn; + let expectingAtLL2 = atn.nextTokens(next, PredictionContext_1.PredictionContext.fromRuleContext(atn, recognizer.context)); + // console.warn("LT(2) set="+expectingAtLL2.toString(recognizer.getTokenNames())); + if (expectingAtLL2.contains(currentSymbolType)) { + this.reportMissingToken(recognizer); + return true; + } + return false; + } + /** + * This method implements the single-token deletion inline error recovery + * strategy. It is called by {@link #recoverInline} to attempt to recover + * from mismatched input. If this method returns `undefined`, the parser and error + * handler state will not have changed. If this method returns non-`undefined`, + * `recognizer` will *not* be in error recovery mode since the + * returned token was a successful match. + * + * If the single-token deletion is successful, this method calls + * {@link #reportUnwantedToken} to report the error, followed by + * {@link Parser#consume} to actually "delete" the extraneous token. Then, + * before returning {@link #reportMatch} is called to signal a successful + * match. + * + * @param recognizer the parser instance + * @returns the successfully matched {@link Token} instance if single-token + * deletion successfully recovers from the mismatched input, otherwise + * `undefined` + */ + singleTokenDeletion(recognizer) { + let nextTokenType = recognizer.inputStream.LA(2); + let expecting = this.getExpectedTokens(recognizer); + if (expecting.contains(nextTokenType)) { + this.reportUnwantedToken(recognizer); + /* + System.err.println("recoverFromMismatchedToken deleting "+ + ((TokenStream)recognizer.inputStream).LT(1)+ + " since "+((TokenStream)recognizer.inputStream).LT(2)+ + " is what we want"); + */ + recognizer.consume(); // simply delete extra token + // we want to return the token we're actually matching + let matchedSymbol = recognizer.currentToken; + this.reportMatch(recognizer); // we know current token is correct + return matchedSymbol; + } + return undefined; + } + /** Conjure up a missing token during error recovery. + * + * The recognizer attempts to recover from single missing + * symbols. But, actions might refer to that missing symbol. + * For example, x=ID {f($x);}. The action clearly assumes + * that there has been an identifier matched previously and that + * $x points at that token. If that token is missing, but + * the next token in the stream is what we want we assume that + * this token is missing and we keep going. Because we + * have to return some token to replace the missing token, + * we have to conjure one up. This method gives the user control + * over the tokens returned for missing tokens. Mostly, + * you will want to create something special for identifier + * tokens. For literals such as '{' and ',', the default + * action in the parser or tree parser works. It simply creates + * a CommonToken of the appropriate type. The text will be the token. + * If you change what tokens must be created by the lexer, + * override this method to create the appropriate tokens. + */ + getMissingSymbol(recognizer) { + let currentSymbol = recognizer.currentToken; + let expecting = this.getExpectedTokens(recognizer); + let expectedTokenType = Token_1.Token.INVALID_TYPE; + if (!expecting.isNil) { + // get any element + expectedTokenType = expecting.minElement; + } + let tokenText; + if (expectedTokenType === Token_1.Token.EOF) { + tokenText = ""; + } + else { + tokenText = ""; + } + let current = currentSymbol; + let lookback = recognizer.inputStream.tryLT(-1); + if (current.type === Token_1.Token.EOF && lookback != null) { + current = lookback; + } + return this.constructToken(recognizer.inputStream.tokenSource, expectedTokenType, tokenText, current); + } + constructToken(tokenSource, expectedTokenType, tokenText, current) { + let factory = tokenSource.tokenFactory; + let x = current.tokenSource; + let stream = x ? x.inputStream : undefined; + return factory.create({ source: tokenSource, stream }, expectedTokenType, tokenText, Token_1.Token.DEFAULT_CHANNEL, -1, -1, current.line, current.charPositionInLine); + } + getExpectedTokens(recognizer) { + return recognizer.getExpectedTokens(); + } + /** How should a token be displayed in an error message? The default + * is to display just the text, but during development you might + * want to have a lot of information spit out. Override in that case + * to use t.toString() (which, for CommonToken, dumps everything about + * the token). This is better than forcing you to override a method in + * your token objects because you don't have to go modify your lexer + * so that it creates a new Java type. + */ + getTokenErrorDisplay(t) { + if (!t) { + return ""; + } + let s = this.getSymbolText(t); + if (!s) { + if (this.getSymbolType(t) === Token_1.Token.EOF) { + s = ""; + } + else { + s = `<${this.getSymbolType(t)}>`; + } + } + return this.escapeWSAndQuote(s); + } + getSymbolText(symbol) { + return symbol.text; + } + getSymbolType(symbol) { + return symbol.type; + } + escapeWSAndQuote(s) { + // if ( s==null ) return s; + s = s.replace("\n", "\\n"); + s = s.replace("\r", "\\r"); + s = s.replace("\t", "\\t"); + return "'" + s + "'"; + } + /* Compute the error recovery set for the current rule. During + * rule invocation, the parser pushes the set of tokens that can + * follow that rule reference on the stack; this amounts to + * computing FIRST of what follows the rule reference in the + * enclosing rule. See LinearApproximator.FIRST(). + * This local follow set only includes tokens + * from within the rule; i.e., the FIRST computation done by + * ANTLR stops at the end of a rule. + * + * EXAMPLE + * + * When you find a "no viable alt exception", the input is not + * consistent with any of the alternatives for rule r. The best + * thing to do is to consume tokens until you see something that + * can legally follow a call to r *or* any rule that called r. + * You don't want the exact set of viable next tokens because the + * input might just be missing a token--you might consume the + * rest of the input looking for one of the missing tokens. + * + * Consider grammar: + * + * a : '[' b ']' + * | '(' b ')' + * ; + * b : c '^' INT ; + * c : ID + * | INT + * ; + * + * At each rule invocation, the set of tokens that could follow + * that rule is pushed on a stack. Here are the various + * context-sensitive follow sets: + * + * FOLLOW(b1_in_a) = FIRST(']') = ']' + * FOLLOW(b2_in_a) = FIRST(')') = ')' + * FOLLOW(c_in_b) = FIRST('^') = '^' + * + * Upon erroneous input "[]", the call chain is + * + * a -> b -> c + * + * and, hence, the follow context stack is: + * + * depth follow set start of rule execution + * 0 a (from main()) + * 1 ']' b + * 2 '^' c + * + * Notice that ')' is not included, because b would have to have + * been called from a different context in rule a for ')' to be + * included. + * + * For error recovery, we cannot consider FOLLOW(c) + * (context-sensitive or otherwise). We need the combined set of + * all context-sensitive FOLLOW sets--the set of all tokens that + * could follow any reference in the call chain. We need to + * resync to one of those tokens. Note that FOLLOW(c)='^' and if + * we resync'd to that token, we'd consume until EOF. We need to + * sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. + * In this case, for input "[]", LA(1) is ']' and in the set, so we would + * not consume anything. After printing an error, rule c would + * return normally. Rule b would not find the required '^' though. + * At this point, it gets a mismatched token error and + * exception (since LA(1) is not in the viable following token + * set). The rule exception handler tries to recover, but finds + * the same recovery set and doesn't consume anything. Rule b + * exits normally returning to rule a. Now it finds the ']' (and + * with the successful match exits errorRecovery mode). + * + * So, you can see that the parser walks up the call chain looking + * for the token that was a member of the recovery set. + * + * Errors are not generated in errorRecovery mode. + * + * ANTLR's error recovery mechanism is based upon original ideas: + * + * "Algorithms + Data Structures = Programs" by Niklaus Wirth + * + * and + * + * "A note on error recovery in recursive descent parsers": + * http://portal.acm.org/citation.cfm?id=947902.947905 + * + * Later, Josef Grosch had some good ideas: + * + * "Efficient and Comfortable Error Recovery in Recursive Descent + * Parsers": + * ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip + * + * Like Grosch I implement context-sensitive FOLLOW sets that are combined + * at run-time upon error to avoid overhead during parsing. + */ + getErrorRecoverySet(recognizer) { + let atn = recognizer.interpreter.atn; + let ctx = recognizer.context; + let recoverSet = new IntervalSet_1.IntervalSet(); + while (ctx && ctx.invokingState >= 0) { + // compute what follows who invoked us + let invokingState = atn.states[ctx.invokingState]; + let rt = invokingState.transition(0); + let follow = atn.nextTokens(rt.followState); + recoverSet.addAll(follow); + ctx = ctx._parent; + } + recoverSet.remove(Token_1.Token.EPSILON); + // System.out.println("recover set "+recoverSet.toString(recognizer.getTokenNames())); + return recoverSet; + } + /** Consume tokens until one matches the given token set. */ + consumeUntil(recognizer, set) { + // System.err.println("consumeUntil("+set.toString(recognizer.getTokenNames())+")"); + let ttype = recognizer.inputStream.LA(1); + while (ttype !== Token_1.Token.EOF && !set.contains(ttype)) { + //System.out.println("consume during recover LA(1)="+getTokenNames()[input.LA(1)]); + // recognizer.inputStream.consume(); + recognizer.consume(); + ttype = recognizer.inputStream.LA(1); + } + } + }; + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "reset", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "beginErrorCondition", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "inErrorRecoveryMode", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "endErrorCondition", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "reportMatch", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "reportError", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "notifyErrorListeners", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "recover", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "sync", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "reportNoViableAlternative", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "reportInputMismatch", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "reportFailedPredicate", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "reportUnwantedToken", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "reportMissingToken", null); + __decorate([ + Decorators_1.Override + ], DefaultErrorStrategy$1.prototype, "recoverInline", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "singleTokenInsertion", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "singleTokenDeletion", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "getMissingSymbol", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "getExpectedTokens", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "getSymbolText", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "getSymbolType", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "escapeWSAndQuote", null); + __decorate([ + Decorators_1.NotNull, + __param(0, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "getErrorRecoverySet", null); + __decorate([ + __param(0, Decorators_1.NotNull), __param(1, Decorators_1.NotNull) + ], DefaultErrorStrategy$1.prototype, "consumeUntil", null); + DefaultErrorStrategy.DefaultErrorStrategy = DefaultErrorStrategy$1; + + return DefaultErrorStrategy; +} + +var hasRequiredBailErrorStrategy; + +function requireBailErrorStrategy () { + if (hasRequiredBailErrorStrategy) return BailErrorStrategy; + hasRequiredBailErrorStrategy = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (BailErrorStrategy && BailErrorStrategy.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(BailErrorStrategy, "__esModule", { value: true }); + BailErrorStrategy.BailErrorStrategy = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:49.2855056-07:00 + const DefaultErrorStrategy_1 = requireDefaultErrorStrategy(); + const InputMismatchException_1 = requireInputMismatchException(); + const Decorators_1 = requireDecorators(); + const ParseCancellationException_1 = requireParseCancellationException(); + /** + * This implementation of {@link ANTLRErrorStrategy} responds to syntax errors + * by immediately canceling the parse operation with a + * {@link ParseCancellationException}. The implementation ensures that the + * {@link ParserRuleContext#exception} field is set for all parse tree nodes + * that were not completed prior to encountering the error. + * + * This error strategy is useful in the following scenarios. + * + * * **Two-stage parsing:** This error strategy allows the first + * stage of two-stage parsing to immediately terminate if an error is + * encountered, and immediately fall back to the second stage. In addition to + * avoiding wasted work by attempting to recover from errors here, the empty + * implementation of {@link BailErrorStrategy#sync} improves the performance of + * the first stage. + * * **Silent validation:** When syntax errors are not being + * reported or logged, and the parse result is simply ignored if errors occur, + * the {@link BailErrorStrategy} avoids wasting work on recovering from errors + * when the result will be ignored either way. + * + * ``` + * myparser.errorHandler = new BailErrorStrategy(); + * ``` + * + * @see Parser.errorHandler + */ + let BailErrorStrategy$1 = class BailErrorStrategy extends DefaultErrorStrategy_1.DefaultErrorStrategy { + /** Instead of recovering from exception `e`, re-throw it wrapped + * in a {@link ParseCancellationException} so it is not caught by the + * rule function catches. Use {@link Exception#getCause()} to get the + * original {@link RecognitionException}. + */ + recover(recognizer, e) { + for (let context = recognizer.context; context; context = context.parent) { + context.exception = e; + } + throw new ParseCancellationException_1.ParseCancellationException(e); + } + /** Make sure we don't attempt to recover inline; if the parser + * successfully recovers, it won't throw an exception. + */ + recoverInline(recognizer) { + let e = new InputMismatchException_1.InputMismatchException(recognizer); + for (let context = recognizer.context; context; context = context.parent) { + context.exception = e; + } + throw new ParseCancellationException_1.ParseCancellationException(e); + } + /** Make sure we don't attempt to recover from problems in subrules. */ + sync(recognizer) { + // intentionally empty + } + }; + __decorate([ + Decorators_1.Override + ], BailErrorStrategy$1.prototype, "recover", null); + __decorate([ + Decorators_1.Override + ], BailErrorStrategy$1.prototype, "recoverInline", null); + __decorate([ + Decorators_1.Override + ], BailErrorStrategy$1.prototype, "sync", null); + BailErrorStrategy.BailErrorStrategy = BailErrorStrategy$1; + + return BailErrorStrategy; +} + +var CharStream = {}; + +var hasRequiredCharStream; + +function requireCharStream () { + if (hasRequiredCharStream) return CharStream; + hasRequiredCharStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(CharStream, "__esModule", { value: true }); + + return CharStream; +} + +var Dependents = {}; + +var hasRequiredDependents; + +function requireDependents () { + if (hasRequiredDependents) return Dependents; + hasRequiredDependents = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Dependents = void 0; + (function (Dependents) { + /** + * The element is dependent upon the specified rule. + */ + Dependents[Dependents["SELF"] = 0] = "SELF"; + /** + * The element is dependent upon the set of the specified rule's parents + * (rules which directly reference it). + */ + Dependents[Dependents["PARENTS"] = 1] = "PARENTS"; + /** + * The element is dependent upon the set of the specified rule's children + * (rules which it directly references). + */ + Dependents[Dependents["CHILDREN"] = 2] = "CHILDREN"; + /** + * The element is dependent upon the set of the specified rule's ancestors + * (the transitive closure of `PARENTS` rules). + */ + Dependents[Dependents["ANCESTORS"] = 3] = "ANCESTORS"; + /** + * The element is dependent upon the set of the specified rule's descendants + * (the transitive closure of `CHILDREN` rules). + */ + Dependents[Dependents["DESCENDANTS"] = 4] = "DESCENDANTS"; + /** + * The element is dependent upon the set of the specified rule's siblings + * (the union of `CHILDREN` of its `PARENTS`). + */ + Dependents[Dependents["SIBLINGS"] = 5] = "SIBLINGS"; + /** + * The element is dependent upon the set of the specified rule's preceeding + * siblings (the union of `CHILDREN` of its `PARENTS` which + * appear before a reference to the rule). + */ + Dependents[Dependents["PRECEEDING_SIBLINGS"] = 6] = "PRECEEDING_SIBLINGS"; + /** + * The element is dependent upon the set of the specified rule's following + * siblings (the union of `CHILDREN` of its `PARENTS` which + * appear after a reference to the rule). + */ + Dependents[Dependents["FOLLOWING_SIBLINGS"] = 7] = "FOLLOWING_SIBLINGS"; + /** + * The element is dependent upon the set of the specified rule's preceeding + * elements (rules which might end before the start of the specified rule + * while parsing). This is calculated by taking the + * `PRECEEDING_SIBLINGS` of the rule and each of its + * `ANCESTORS`, along with the `DESCENDANTS` of those + * elements. + */ + Dependents[Dependents["PRECEEDING"] = 8] = "PRECEEDING"; + /** + * The element is dependent upon the set of the specified rule's following + * elements (rules which might start after the end of the specified rule + * while parsing). This is calculated by taking the + * `FOLLOWING_SIBLINGS` of the rule and each of its + * `ANCESTORS`, along with the `DESCENDANTS` of those + * elements. + */ + Dependents[Dependents["FOLLOWING"] = 9] = "FOLLOWING"; + })(exports.Dependents || (exports.Dependents = {})); + + } (Dependents)); + return Dependents; +} + +var DiagnosticErrorListener = {}; + +var hasRequiredDiagnosticErrorListener; + +function requireDiagnosticErrorListener () { + if (hasRequiredDiagnosticErrorListener) return DiagnosticErrorListener; + hasRequiredDiagnosticErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (DiagnosticErrorListener && DiagnosticErrorListener.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (DiagnosticErrorListener && DiagnosticErrorListener.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(DiagnosticErrorListener, "__esModule", { value: true }); + DiagnosticErrorListener.DiagnosticErrorListener = void 0; + const BitSet_1 = requireBitSet(); + const Decorators_1 = requireDecorators(); + const Interval_1 = requireInterval(); + /** + * This implementation of {@link ANTLRErrorListener} can be used to identify + * certain potential correctness and performance problems in grammars. "Reports" + * are made by calling {@link Parser#notifyErrorListeners} with the appropriate + * message. + * + * * **Ambiguities**: These are cases where more than one path through the + * grammar can match the input. + * * **Weak context sensitivity**: These are cases where full-context + * prediction resolved an SLL conflict to a unique alternative which equaled the + * minimum alternative of the SLL conflict. + * * **Strong (forced) context sensitivity**: These are cases where the + * full-context prediction resolved an SLL conflict to a unique alternative, + * *and* the minimum alternative of the SLL conflict was found to not be + * a truly viable alternative. Two-stage parsing cannot be used for inputs where + * this situation occurs. + * + * @author Sam Harwell + */ + let DiagnosticErrorListener$1 = class DiagnosticErrorListener { + /** + * Initializes a new instance of {@link DiagnosticErrorListener}, specifying + * whether all ambiguities or only exact ambiguities are reported. + * + * @param exactOnly `true` to report only exact ambiguities, otherwise + * `false` to report all ambiguities. Defaults to true. + */ + constructor(exactOnly = true) { + this.exactOnly = exactOnly; + this.exactOnly = exactOnly; + } + syntaxError( + /*@NotNull*/ + recognizer, offendingSymbol, line, charPositionInLine, + /*@NotNull*/ + msg, e) { + // intentionally empty + } + reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) { + if (this.exactOnly && !exact) { + return; + } + let decision = this.getDecisionDescription(recognizer, dfa); + let conflictingAlts = this.getConflictingAlts(ambigAlts, configs); + let text = recognizer.inputStream.getText(Interval_1.Interval.of(startIndex, stopIndex)); + let message = `reportAmbiguity d=${decision}: ambigAlts=${conflictingAlts}, input='${text}'`; + recognizer.notifyErrorListeners(message); + } + reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, conflictState) { + let decision = this.getDecisionDescription(recognizer, dfa); + let text = recognizer.inputStream.getText(Interval_1.Interval.of(startIndex, stopIndex)); + let message = `reportAttemptingFullContext d=${decision}, input='${text}'`; + recognizer.notifyErrorListeners(message); + } + reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, acceptState) { + let decision = this.getDecisionDescription(recognizer, dfa); + let text = recognizer.inputStream.getText(Interval_1.Interval.of(startIndex, stopIndex)); + let message = `reportContextSensitivity d=${decision}, input='${text}'`; + recognizer.notifyErrorListeners(message); + } + getDecisionDescription(recognizer, dfa) { + let decision = dfa.decision; + let ruleIndex = dfa.atnStartState.ruleIndex; + let ruleNames = recognizer.ruleNames; + if (ruleIndex < 0 || ruleIndex >= ruleNames.length) { + return decision.toString(); + } + let ruleName = ruleNames[ruleIndex]; + if (!ruleName) { + return decision.toString(); + } + return `${decision} (${ruleName})`; + } + /** + * Computes the set of conflicting or ambiguous alternatives from a + * configuration set, if that information was not already provided by the + * parser. + * + * @param reportedAlts The set of conflicting or ambiguous alternatives, as + * reported by the parser. + * @param configs The conflicting or ambiguous configuration set. + * @returns Returns `reportedAlts` if it is not `undefined`, otherwise + * returns the set of alternatives represented in `configs`. + */ + getConflictingAlts(reportedAlts, configs) { + if (reportedAlts != null) { + return reportedAlts; + } + let result = new BitSet_1.BitSet(); + for (let config of configs) { + result.set(config.alt); + } + return result; + } + }; + __decorate([ + Decorators_1.Override + ], DiagnosticErrorListener$1.prototype, "syntaxError", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(6, Decorators_1.NotNull) + ], DiagnosticErrorListener$1.prototype, "reportAmbiguity", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(5, Decorators_1.NotNull) + ], DiagnosticErrorListener$1.prototype, "reportAttemptingFullContext", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull), + __param(5, Decorators_1.NotNull) + ], DiagnosticErrorListener$1.prototype, "reportContextSensitivity", null); + __decorate([ + __param(0, Decorators_1.NotNull), + __param(1, Decorators_1.NotNull) + ], DiagnosticErrorListener$1.prototype, "getDecisionDescription", null); + __decorate([ + Decorators_1.NotNull, + __param(1, Decorators_1.NotNull) + ], DiagnosticErrorListener$1.prototype, "getConflictingAlts", null); + DiagnosticErrorListener.DiagnosticErrorListener = DiagnosticErrorListener$1; + + return DiagnosticErrorListener; +} + +var LexerInterpreter = {}; + +var hasRequiredLexerInterpreter; + +function requireLexerInterpreter () { + if (hasRequiredLexerInterpreter) return LexerInterpreter; + hasRequiredLexerInterpreter = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (LexerInterpreter && LexerInterpreter.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (LexerInterpreter && LexerInterpreter.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(LexerInterpreter, "__esModule", { value: true }); + LexerInterpreter.LexerInterpreter = void 0; + const Lexer_1 = requireLexer(); + const LexerATNSimulator_1 = requireLexerATNSimulator(); + const Decorators_1 = requireDecorators(); + const Decorators_2 = requireDecorators(); + let LexerInterpreter$1 = class LexerInterpreter extends Lexer_1.Lexer { + constructor(grammarFileName, vocabulary, ruleNames, channelNames, modeNames, atn, input) { + super(input); + if (atn.grammarType !== 0 /* LEXER */) { + throw new Error("IllegalArgumentException: The ATN must be a lexer ATN."); + } + this._grammarFileName = grammarFileName; + this._atn = atn; + this._ruleNames = ruleNames.slice(0); + this._channelNames = channelNames.slice(0); + this._modeNames = modeNames.slice(0); + this._vocabulary = vocabulary; + this._interp = new LexerATNSimulator_1.LexerATNSimulator(atn, this); + } + get atn() { + return this._atn; + } + get grammarFileName() { + return this._grammarFileName; + } + get ruleNames() { + return this._ruleNames; + } + get channelNames() { + return this._channelNames; + } + get modeNames() { + return this._modeNames; + } + get vocabulary() { + return this._vocabulary; + } + }; + __decorate([ + Decorators_1.NotNull + ], LexerInterpreter$1.prototype, "_vocabulary", void 0); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "atn", null); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "grammarFileName", null); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "ruleNames", null); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "channelNames", null); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "modeNames", null); + __decorate([ + Decorators_2.Override + ], LexerInterpreter$1.prototype, "vocabulary", null); + LexerInterpreter$1 = __decorate([ + __param(1, Decorators_1.NotNull) + ], LexerInterpreter$1); + LexerInterpreter.LexerInterpreter = LexerInterpreter$1; + + return LexerInterpreter; +} + +var ParserErrorListener = {}; + +var hasRequiredParserErrorListener; + +function requireParserErrorListener () { + if (hasRequiredParserErrorListener) return ParserErrorListener; + hasRequiredParserErrorListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParserErrorListener, "__esModule", { value: true }); + + return ParserErrorListener; +} + +var RuleContextWithAltNum = {}; + +var hasRequiredRuleContextWithAltNum; + +function requireRuleContextWithAltNum () { + if (hasRequiredRuleContextWithAltNum) return RuleContextWithAltNum; + hasRequiredRuleContextWithAltNum = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (RuleContextWithAltNum && RuleContextWithAltNum.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(RuleContextWithAltNum, "__esModule", { value: true }); + RuleContextWithAltNum.RuleContextWithAltNum = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:57.4741196-07:00 + const ATN_1 = requireATN(); + const Decorators_1 = requireDecorators(); + const ParserRuleContext_1 = requireParserRuleContext(); + /** A handy class for use with + * + * options {contextSuperClass=org.antlr.v4.runtime.RuleContextWithAltNum;} + * + * that provides a backing field / impl for the outer alternative number + * matched for an internal parse tree node. + * + * I'm only putting into Java runtime as I'm certain I'm the only one that + * will really every use this. + */ + let RuleContextWithAltNum$1 = class RuleContextWithAltNum extends ParserRuleContext_1.ParserRuleContext { + constructor(parent, invokingStateNumber) { + if (invokingStateNumber !== undefined) { + super(parent, invokingStateNumber); + } + else { + super(); + } + this._altNumber = ATN_1.ATN.INVALID_ALT_NUMBER; + } + get altNumber() { + return this._altNumber; + } + // @Override + set altNumber(altNum) { + this._altNumber = altNum; + } + }; + __decorate([ + Decorators_1.Override + ], RuleContextWithAltNum$1.prototype, "altNumber", null); + RuleContextWithAltNum.RuleContextWithAltNum = RuleContextWithAltNum$1; + + return RuleContextWithAltNum; +} + +var RuleDependency = {}; + +var hasRequiredRuleDependency; + +function requireRuleDependency () { + if (hasRequiredRuleDependency) return RuleDependency; + hasRequiredRuleDependency = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(RuleDependency, "__esModule", { value: true }); + RuleDependency.RuleDependency = void 0; + /** + * Declares a dependency upon a grammar rule, along with a set of zero or more dependent rules. + * + * Version numbers within a grammar should be assigned on a monotonically increasing basis to allow for accurate + * tracking of dependent rules. + * + * @author Sam Harwell + */ + function RuleDependency$1(dependency) { + return (target, propertyKey, propertyDescriptor) => { + // intentionally empty + }; + } + RuleDependency.RuleDependency = RuleDependency$1; + + return RuleDependency; +} + +var RuleVersion = {}; + +var hasRequiredRuleVersion; + +function requireRuleVersion () { + if (hasRequiredRuleVersion) return RuleVersion; + hasRequiredRuleVersion = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(RuleVersion, "__esModule", { value: true }); + RuleVersion.RuleVersion = void 0; + /** + * + * @author Sam Harwell + */ + function RuleVersion$1(version) { + return (target, propertyKey, propertyDescriptor) => { + // intentionally empty + }; + } + RuleVersion.RuleVersion = RuleVersion$1; + + return RuleVersion; +} + +var TokenFactory = {}; + +var hasRequiredTokenFactory; + +function requireTokenFactory () { + if (hasRequiredTokenFactory) return TokenFactory; + hasRequiredTokenFactory = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(TokenFactory, "__esModule", { value: true }); + + return TokenFactory; +} + +var TokenSource = {}; + +var hasRequiredTokenSource; + +function requireTokenSource () { + if (hasRequiredTokenSource) return TokenSource; + hasRequiredTokenSource = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(TokenSource, "__esModule", { value: true }); + + return TokenSource; +} + +var TokenStream = {}; + +var hasRequiredTokenStream; + +function requireTokenStream () { + if (hasRequiredTokenStream) return TokenStream; + hasRequiredTokenStream = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(TokenStream, "__esModule", { value: true }); + + return TokenStream; +} + +var TokenStreamRewriter = {}; + +var hasRequiredTokenStreamRewriter; + +function requireTokenStreamRewriter () { + if (hasRequiredTokenStreamRewriter) return TokenStreamRewriter; + hasRequiredTokenStreamRewriter = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (TokenStreamRewriter && TokenStreamRewriter.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + Object.defineProperty(TokenStreamRewriter, "__esModule", { value: true }); + TokenStreamRewriter.RewriteOperation = TokenStreamRewriter.TokenStreamRewriter = void 0; + // ConvertTo-TS run at 2016-10-04T11:26:58.1768850-07:00 + const Interval_1 = requireInterval(); + const Decorators_1 = requireDecorators(); + const Token_1 = requireToken(); + /** + * Useful for rewriting out a buffered input token stream after doing some + * augmentation or other manipulations on it. + * + * You can insert stuff, replace, and delete chunks. Note that the operations + * are done lazily--only if you convert the buffer to a {@link String} with + * {@link TokenStream#getText()}. This is very efficient because you are not + * moving data around all the time. As the buffer of tokens is converted to + * strings, the {@link #getText()} method(s) scan the input token stream and + * check to see if there is an operation at the current index. If so, the + * operation is done and then normal {@link String} rendering continues on the + * buffer. This is like having multiple Turing machine instruction streams + * (programs) operating on a single input tape. :) + * + * This rewriter makes no modifications to the token stream. It does not ask the + * stream to fill itself up nor does it advance the input cursor. The token + * stream `TokenStream.index` will return the same value before and + * after any {@link #getText()} call. + * + * The rewriter only works on tokens that you have in the buffer and ignores the + * current input cursor. If you are buffering tokens on-demand, calling + * {@link #getText()} halfway through the input will only do rewrites for those + * tokens in the first half of the file. + * + * Since the operations are done lazily at {@link #getText}-time, operations do + * not screw up the token index values. That is, an insert operation at token + * index `i` does not change the index values for tokens + * `i`+1..n-1. + * + * Because operations never actually alter the buffer, you may always get the + * original token stream back without undoing anything. Since the instructions + * are queued up, you can easily simulate transactions and roll back any changes + * if there is an error just by removing instructions. For example, + * + * ``` + * CharStream input = new ANTLRFileStream("input"); + * TLexer lex = new TLexer(input); + * CommonTokenStream tokens = new CommonTokenStream(lex); + * T parser = new T(tokens); + * TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens); + * parser.startRule(); + * ``` + * + * Then in the rules, you can execute (assuming rewriter is visible): + * + * ``` + * Token t,u; + * ... + * rewriter.insertAfter(t, "text to put after t");} + * rewriter.insertAfter(u, "text after u");} + * System.out.println(rewriter.getText()); + * ``` + * + * You can also have multiple "instruction streams" and get multiple rewrites + * from a single pass over the input. Just name the instruction streams and use + * that name again when printing the buffer. This could be useful for generating + * a C file and also its header file--all from the same buffer: + * + * ``` + * rewriter.insertAfter("pass1", t, "text to put after t");} + * rewriter.insertAfter("pass2", u, "text after u");} + * System.out.println(rewriter.getText("pass1")); + * System.out.println(rewriter.getText("pass2")); + * ``` + * + * If you don't use named rewrite streams, a "default" stream is used as the + * first example shows. + */ + let TokenStreamRewriter$1 = class TokenStreamRewriter { + constructor(tokens) { + this.tokens = tokens; + this.programs = new Map(); + this.programs.set(TokenStreamRewriter.DEFAULT_PROGRAM_NAME, []); + this.lastRewriteTokenIndexes = new Map(); + } + getTokenStream() { + return this.tokens; + } + rollback(instructionIndex, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + let is = this.programs.get(programName); + if (is != null) { + this.programs.set(programName, is.slice(TokenStreamRewriter.MIN_TOKEN_INDEX, instructionIndex)); + } + } + deleteProgram(programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + this.rollback(TokenStreamRewriter.MIN_TOKEN_INDEX, programName); + } + insertAfter(tokenOrIndex, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + let index; + if (typeof tokenOrIndex === "number") { + index = tokenOrIndex; + } + else { + index = tokenOrIndex.tokenIndex; + } + // to insert after, just insert before next index (even if past end) + let rewrites = this.getProgram(programName); + let op = new InsertAfterOp(this.tokens, index, rewrites.length, text); + rewrites.push(op); + } + insertBefore(tokenOrIndex, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + let index; + if (typeof tokenOrIndex === "number") { + index = tokenOrIndex; + } + else { + index = tokenOrIndex.tokenIndex; + } + let rewrites = this.getProgram(programName); + let op = new InsertBeforeOp(this.tokens, index, rewrites.length, text); + rewrites.push(op); + } + replaceSingle(index, text) { + if (typeof index === "number") { + this.replace(index, index, text); + } + else { + this.replace(index, index, text); + } + } + replace(from, to, text, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + if (typeof from !== "number") { + from = from.tokenIndex; + } + if (typeof to !== "number") { + to = to.tokenIndex; + } + if (from > to || from < 0 || to < 0 || to >= this.tokens.size) { + throw new RangeError(`replace: range invalid: ${from}..${to}(size=${this.tokens.size})`); + } + let rewrites = this.getProgram(programName); + let op = new ReplaceOp(this.tokens, from, to, rewrites.length, text); + rewrites.push(op); + } + delete(from, to, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + if (to === undefined) { + to = from; + } + if (typeof from === "number") { + this.replace(from, to, "", programName); + } + else { + this.replace(from, to, "", programName); + } + } + getLastRewriteTokenIndex(programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + let I = this.lastRewriteTokenIndexes.get(programName); + if (I == null) { + return -1; + } + return I; + } + setLastRewriteTokenIndex(programName, i) { + this.lastRewriteTokenIndexes.set(programName, i); + } + getProgram(name) { + let is = this.programs.get(name); + if (is == null) { + is = this.initializeProgram(name); + } + return is; + } + initializeProgram(name) { + let is = []; + this.programs.set(name, is); + return is; + } + getText(intervalOrProgram, programName = TokenStreamRewriter.DEFAULT_PROGRAM_NAME) { + let interval; + if (intervalOrProgram instanceof Interval_1.Interval) { + interval = intervalOrProgram; + } + else { + interval = Interval_1.Interval.of(0, this.tokens.size - 1); + } + if (typeof intervalOrProgram === "string") { + programName = intervalOrProgram; + } + let rewrites = this.programs.get(programName); + let start = interval.a; + let stop = interval.b; + // ensure start/end are in range + if (stop > this.tokens.size - 1) { + stop = this.tokens.size - 1; + } + if (start < 0) { + start = 0; + } + if (rewrites == null || rewrites.length === 0) { + return this.tokens.getText(interval); // no instructions to execute + } + let buf = []; + // First, optimize instruction stream + let indexToOp = this.reduceToSingleOperationPerIndex(rewrites); + // Walk buffer, executing instructions and emitting tokens + let i = start; + while (i <= stop && i < this.tokens.size) { + let op = indexToOp.get(i); + indexToOp.delete(i); // remove so any left have index size-1 + let t = this.tokens.get(i); + if (op == null) { + // no operation at that index, just dump token + if (t.type !== Token_1.Token.EOF) { + buf.push(String(t.text)); + } + i++; // move to next token + } + else { + i = op.execute(buf); // execute operation and skip + } + } + // include stuff after end if it's last index in buffer + // So, if they did an insertAfter(lastValidIndex, "foo"), include + // foo if end==lastValidIndex. + if (stop === this.tokens.size - 1) { + // Scan any remaining operations after last token + // should be included (they will be inserts). + for (let op of indexToOp.values()) { + if (op.index >= this.tokens.size - 1) { + buf.push(op.text.toString()); + } + } + } + return buf.join(""); + } + /** We need to combine operations and report invalid operations (like + * overlapping replaces that are not completed nested). Inserts to + * same index need to be combined etc... Here are the cases: + * + * I.i.u I.j.v leave alone, nonoverlapping + * I.i.u I.i.v combine: Iivu + * + * R.i-j.u R.x-y.v | i-j in x-y delete first R + * R.i-j.u R.i-j.v delete first R + * R.i-j.u R.x-y.v | x-y in i-j ERROR + * R.i-j.u R.x-y.v | boundaries overlap ERROR + * + * Delete special case of replace (text==undefined): + * D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) + * + * I.i.u R.x-y.v | i in (x+1)-y delete I (since insert before + * we're not deleting i) + * I.i.u R.x-y.v | i not in (x+1)-y leave alone, nonoverlapping + * R.x-y.v I.i.u | i in x-y ERROR + * R.x-y.v I.x.u R.x-y.uv (combine, delete I) + * R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping + * + * I.i.u = insert u before op @ index i + * R.x-y.u = replace x-y indexed tokens with u + * + * First we need to examine replaces. For any replace op: + * + * 1. wipe out any insertions before op within that range. + * 2. Drop any replace op before that is contained completely within + * that range. + * 3. Throw exception upon boundary overlap with any previous replace. + * + * Then we can deal with inserts: + * + * 1. for any inserts to same index, combine even if not adjacent. + * 2. for any prior replace with same left boundary, combine this + * insert with replace and delete this replace. + * 3. throw exception if index in same range as previous replace + * + * Don't actually delete; make op undefined in list. Easier to walk list. + * Later we can throw as we add to index → op map. + * + * Note that I.2 R.2-2 will wipe out I.2 even though, technically, the + * inserted stuff would be before the replace range. But, if you + * add tokens in front of a method body '{' and then delete the method + * body, I think the stuff before the '{' you added should disappear too. + * + * Return a map from token index to operation. + */ + reduceToSingleOperationPerIndex(rewrites) { + // console.log(`rewrites=[${Utils.join(rewrites, ", ")}]`); + // WALK REPLACES + for (let i = 0; i < rewrites.length; i++) { + let op = rewrites[i]; + if (op == null) { + continue; + } + if (!(op instanceof ReplaceOp)) { + continue; + } + let rop = op; + // Wipe prior inserts within range + let inserts = this.getKindOfOps(rewrites, InsertBeforeOp, i); + for (let iop of inserts) { + if (iop.index === rop.index) { + // E.g., insert before 2, delete 2..2; update replace + // text to include insert before, kill insert + rewrites[iop.instructionIndex] = undefined; + rop.text = iop.text.toString() + (rop.text != null ? rop.text.toString() : ""); + } + else if (iop.index > rop.index && iop.index <= rop.lastIndex) { + // delete insert as it's a no-op. + rewrites[iop.instructionIndex] = undefined; + } + } + // Drop any prior replaces contained within + let prevReplaces = this.getKindOfOps(rewrites, ReplaceOp, i); + for (let prevRop of prevReplaces) { + if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex) { + // delete replace as it's a no-op. + rewrites[prevRop.instructionIndex] = undefined; + continue; + } + // throw exception unless disjoint or identical + let disjoint = prevRop.lastIndex < rop.index || prevRop.index > rop.lastIndex; + // Delete special case of replace (text==null): + // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) + if (prevRop.text == null && rop.text == null && !disjoint) { + // console.log(`overlapping deletes: ${prevRop}, ${rop}`); + rewrites[prevRop.instructionIndex] = undefined; // kill first delete + rop.index = Math.min(prevRop.index, rop.index); + rop.lastIndex = Math.max(prevRop.lastIndex, rop.lastIndex); + // console.log(`new rop ${rop}`); + } + else if (!disjoint) { + throw new Error(`replace op boundaries of ${rop} overlap with previous ${prevRop}`); + } + } + } + // WALK INSERTS + for (let i = 0; i < rewrites.length; i++) { + let op = rewrites[i]; + if (op == null) { + continue; + } + if (!(op instanceof InsertBeforeOp)) { + continue; + } + let iop = op; + // combine current insert with prior if any at same index + let prevInserts = this.getKindOfOps(rewrites, InsertBeforeOp, i); + for (let prevIop of prevInserts) { + if (prevIop.index === iop.index) { + if (prevIop instanceof InsertAfterOp) { + iop.text = this.catOpText(prevIop.text, iop.text); + rewrites[prevIop.instructionIndex] = undefined; + } + else if (prevIop instanceof InsertBeforeOp) { // combine objects + // convert to strings...we're in process of toString'ing + // whole token buffer so no lazy eval issue with any templates + iop.text = this.catOpText(iop.text, prevIop.text); + // delete redundant prior insert + rewrites[prevIop.instructionIndex] = undefined; + } + } + } + // look for replaces where iop.index is in range; error + let prevReplaces = this.getKindOfOps(rewrites, ReplaceOp, i); + for (let rop of prevReplaces) { + if (iop.index === rop.index) { + rop.text = this.catOpText(iop.text, rop.text); + rewrites[i] = undefined; // delete current insert + continue; + } + if (iop.index >= rop.index && iop.index <= rop.lastIndex) { + throw new Error(`insert op ${iop} within boundaries of previous ${rop}`); + } + } + } + // console.log(`rewrites after=[${Utils.join(rewrites, ", ")}]`); + let m = new Map(); + for (let op of rewrites) { + if (op == null) { + // ignore deleted ops + continue; + } + if (m.get(op.index) != null) { + throw new Error("should only be one op per index"); + } + m.set(op.index, op); + } + // console.log(`index to op: ${m}`); + return m; + } + catOpText(a, b) { + let x = ""; + let y = ""; + if (a != null) { + x = a.toString(); + } + if (b != null) { + y = b.toString(); + } + return x + y; + } + /** Get all operations before an index of a particular kind */ + getKindOfOps(rewrites, kind, before) { + let ops = []; + for (let i = 0; i < before && i < rewrites.length; i++) { + let op = rewrites[i]; + if (op == null) { + // ignore deleted + continue; + } + if (op instanceof kind) { + ops.push(op); + } + } + return ops; + } + }; + TokenStreamRewriter.TokenStreamRewriter = TokenStreamRewriter$1; + TokenStreamRewriter$1.DEFAULT_PROGRAM_NAME = "default"; + TokenStreamRewriter$1.PROGRAM_INIT_SIZE = 100; + TokenStreamRewriter$1.MIN_TOKEN_INDEX = 0; + // Define the rewrite operation hierarchy + class RewriteOperation { + constructor(tokens, index, instructionIndex, text) { + this.tokens = tokens; + this.instructionIndex = instructionIndex; + this.index = index; + this.text = text === undefined ? "" : text; + } + /** Execute the rewrite operation by possibly adding to the buffer. + * Return the index of the next token to operate on. + */ + execute(buf) { + return this.index; + } + toString() { + let opName = this.constructor.name; + let $index = opName.indexOf("$"); + opName = opName.substring($index + 1, opName.length); + return "<" + opName + "@" + this.tokens.get(this.index) + + ":\"" + this.text + "\">"; + } + } + __decorate([ + Decorators_1.Override + ], RewriteOperation.prototype, "toString", null); + TokenStreamRewriter.RewriteOperation = RewriteOperation; + class InsertBeforeOp extends RewriteOperation { + constructor(tokens, index, instructionIndex, text) { + super(tokens, index, instructionIndex, text); + } + execute(buf) { + buf.push(this.text.toString()); + if (this.tokens.get(this.index).type !== Token_1.Token.EOF) { + buf.push(String(this.tokens.get(this.index).text)); + } + return this.index + 1; + } + } + __decorate([ + Decorators_1.Override + ], InsertBeforeOp.prototype, "execute", null); + /** Distinguish between insert after/before to do the "insert afters" + * first and then the "insert befores" at same index. Implementation + * of "insert after" is "insert before index+1". + */ + class InsertAfterOp extends InsertBeforeOp { + constructor(tokens, index, instructionIndex, text) { + super(tokens, index + 1, instructionIndex, text); // insert after is insert before index+1 + } + } + /** I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp + * instructions. + */ + class ReplaceOp extends RewriteOperation { + constructor(tokens, from, to, instructionIndex, text) { + super(tokens, from, instructionIndex, text); + this.lastIndex = to; + } + execute(buf) { + if (this.text != null) { + buf.push(this.text.toString()); + } + return this.lastIndex + 1; + } + toString() { + if (this.text == null) { + return ""; + } + return ""; + } + } + __decorate([ + Decorators_1.Override + ], ReplaceOp.prototype, "execute", null); + __decorate([ + Decorators_1.Override + ], ReplaceOp.prototype, "toString", null); + + return TokenStreamRewriter; +} + +var Vocabulary = {}; + +var hasRequiredVocabulary; + +function requireVocabulary () { + if (hasRequiredVocabulary) return Vocabulary; + hasRequiredVocabulary = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Vocabulary, "__esModule", { value: true }); + + return Vocabulary; +} + +var WritableToken = {}; + +var hasRequiredWritableToken; + +function requireWritableToken () { + if (hasRequiredWritableToken) return WritableToken; + hasRequiredWritableToken = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(WritableToken, "__esModule", { value: true }); + + return WritableToken; +} + +var hasRequiredAntlr4ts; + +function requireAntlr4ts () { + if (hasRequiredAntlr4ts) return antlr4ts; + hasRequiredAntlr4ts = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __createBinding = (antlr4ts && antlr4ts.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = (antlr4ts && antlr4ts.__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(requireANTLRErrorListener(), exports); + __exportStar(requireANTLRErrorStrategy(), exports); + // export * from "./ANTLRFileStream"; + __exportStar(requireANTLRInputStream(), exports); + __exportStar(requireBailErrorStrategy(), exports); + __exportStar(requireBufferedTokenStream(), exports); + __exportStar(requireCharStream(), exports); + __exportStar(requireCharStreams(), exports); + __exportStar(requireCodePointBuffer(), exports); + __exportStar(requireCodePointCharStream(), exports); + __exportStar(requireCommonToken(), exports); + __exportStar(requireCommonTokenFactory(), exports); + __exportStar(requireCommonTokenStream(), exports); + __exportStar(requireConsoleErrorListener(), exports); + __exportStar(requireDefaultErrorStrategy(), exports); + __exportStar(requireDependents(), exports); + __exportStar(requireDiagnosticErrorListener(), exports); + __exportStar(requireFailedPredicateException(), exports); + __exportStar(requireInputMismatchException(), exports); + __exportStar(requireInterpreterRuleContext(), exports); + __exportStar(requireIntStream(), exports); + __exportStar(requireLexer(), exports); + __exportStar(requireLexerInterpreter(), exports); + __exportStar(requireLexerNoViableAltException(), exports); + __exportStar(requireListTokenSource(), exports); + __exportStar(requireNoViableAltException(), exports); + __exportStar(requireParser$1(), exports); + __exportStar(requireParserErrorListener(), exports); + __exportStar(requireParserInterpreter(), exports); + __exportStar(requireParserRuleContext(), exports); + __exportStar(requireProxyErrorListener(), exports); + __exportStar(requireProxyParserErrorListener(), exports); + __exportStar(requireRecognitionException(), exports); + __exportStar(requireRecognizer(), exports); + __exportStar(requireRuleContext(), exports); + __exportStar(requireRuleContextWithAltNum(), exports); + __exportStar(requireRuleDependency(), exports); + __exportStar(requireRuleVersion(), exports); + __exportStar(requireToken(), exports); + __exportStar(requireTokenFactory(), exports); + __exportStar(requireTokenSource(), exports); + __exportStar(requireTokenStream(), exports); + __exportStar(requireTokenStreamRewriter(), exports); + // export * from "./UnbufferedCharStream"; + // export * from "./UnbufferedTokenStream"; + __exportStar(requireVocabulary(), exports); + __exportStar(requireVocabularyImpl(), exports); + __exportStar(requireWritableToken(), exports); + + } (antlr4ts)); + return antlr4ts; +} + +var tree = {}; + +var AbstractParseTreeVisitor = {}; + +var hasRequiredAbstractParseTreeVisitor; + +function requireAbstractParseTreeVisitor () { + if (hasRequiredAbstractParseTreeVisitor) return AbstractParseTreeVisitor; + hasRequiredAbstractParseTreeVisitor = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __decorate = (AbstractParseTreeVisitor && AbstractParseTreeVisitor.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + var __param = (AbstractParseTreeVisitor && AbstractParseTreeVisitor.__param) || function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + Object.defineProperty(AbstractParseTreeVisitor, "__esModule", { value: true }); + AbstractParseTreeVisitor.AbstractParseTreeVisitor = void 0; + const Decorators_1 = requireDecorators(); + let AbstractParseTreeVisitor$1 = class AbstractParseTreeVisitor { + /** + * {@inheritDoc} + * + * The default implementation calls {@link ParseTree#accept} on the + * specified tree. + */ + visit(tree) { + return tree.accept(this); + } + /** + * {@inheritDoc} + * + * The default implementation initializes the aggregate result to + * {@link #defaultResult defaultResult()}. Before visiting each child, it + * calls {@link #shouldVisitNextChild shouldVisitNextChild}; if the result + * is `false` no more children are visited and the current aggregate + * result is returned. After visiting a child, the aggregate result is + * updated by calling {@link #aggregateResult aggregateResult} with the + * previous aggregate result and the result of visiting the child. + * + * The default implementation is not safe for use in visitors that modify + * the tree structure. Visitors that modify the tree should override this + * method to behave properly in respect to the specific algorithm in use. + */ + visitChildren(node) { + let result = this.defaultResult(); + let n = node.childCount; + for (let i = 0; i < n; i++) { + if (!this.shouldVisitNextChild(node, result)) { + break; + } + let c = node.getChild(i); + let childResult = c.accept(this); + result = this.aggregateResult(result, childResult); + } + return result; + } + /** + * {@inheritDoc} + * + * The default implementation returns the result of + * {@link #defaultResult defaultResult}. + */ + visitTerminal(node) { + return this.defaultResult(); + } + /** + * {@inheritDoc} + * + * The default implementation returns the result of + * {@link #defaultResult defaultResult}. + */ + visitErrorNode(node) { + return this.defaultResult(); + } + /** + * Aggregates the results of visiting multiple children of a node. After + * either all children are visited or {@link #shouldVisitNextChild} returns + * `false`, the aggregate value is returned as the result of + * {@link #visitChildren}. + * + * The default implementation returns `nextResult`, meaning + * {@link #visitChildren} will return the result of the last child visited + * (or return the initial value if the node has no children). + * + * @param aggregate The previous aggregate value. In the default + * implementation, the aggregate value is initialized to + * {@link #defaultResult}, which is passed as the `aggregate` argument + * to this method after the first child node is visited. + * @param nextResult The result of the immediately preceeding call to visit + * a child node. + * + * @returns The updated aggregate result. + */ + aggregateResult(aggregate, nextResult) { + return nextResult; + } + /** + * This method is called after visiting each child in + * {@link #visitChildren}. This method is first called before the first + * child is visited; at that point `currentResult` will be the initial + * value (in the default implementation, the initial value is returned by a + * call to {@link #defaultResult}. This method is not called after the last + * child is visited. + * + * The default implementation always returns `true`, indicating that + * `visitChildren` should only return after all children are visited. + * One reason to override this method is to provide a "short circuit" + * evaluation option for situations where the result of visiting a single + * child has the potential to determine the result of the visit operation as + * a whole. + * + * @param node The {@link RuleNode} whose children are currently being + * visited. + * @param currentResult The current aggregate result of the children visited + * to the current point. + * + * @returns `true` to continue visiting children. Otherwise return + * `false` to stop visiting children and immediately return the + * current aggregate result from {@link #visitChildren}. + */ + shouldVisitNextChild(node, currentResult) { + return true; + } + }; + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], AbstractParseTreeVisitor$1.prototype, "visit", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], AbstractParseTreeVisitor$1.prototype, "visitChildren", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], AbstractParseTreeVisitor$1.prototype, "visitTerminal", null); + __decorate([ + Decorators_1.Override, + __param(0, Decorators_1.NotNull) + ], AbstractParseTreeVisitor$1.prototype, "visitErrorNode", null); + __decorate([ + __param(0, Decorators_1.NotNull) + ], AbstractParseTreeVisitor$1.prototype, "shouldVisitNextChild", null); + AbstractParseTreeVisitor.AbstractParseTreeVisitor = AbstractParseTreeVisitor$1; + + return AbstractParseTreeVisitor; +} + +var ParseTree = {}; + +var hasRequiredParseTree; + +function requireParseTree () { + if (hasRequiredParseTree) return ParseTree; + hasRequiredParseTree = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParseTree, "__esModule", { value: true }); + + return ParseTree; +} + +var ParseTreeListener = {}; + +var hasRequiredParseTreeListener; + +function requireParseTreeListener () { + if (hasRequiredParseTreeListener) return ParseTreeListener; + hasRequiredParseTreeListener = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParseTreeListener, "__esModule", { value: true }); + + return ParseTreeListener; +} + +var ParseTreeProperty = {}; + +var hasRequiredParseTreeProperty; + +function requireParseTreeProperty () { + if (hasRequiredParseTreeProperty) return ParseTreeProperty; + hasRequiredParseTreeProperty = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParseTreeProperty, "__esModule", { value: true }); + ParseTreeProperty.ParseTreeProperty = void 0; + /** + * Associate a property with a parse tree node. Useful with parse tree listeners + * that need to associate values with particular tree nodes, kind of like + * specifying a return value for the listener event method that visited a + * particular node. Example: + * + * ``` + * ParseTreeProperty values = new ParseTreeProperty(); + * values.put(tree, 36); + * int x = values.get(tree); + * values.removeFrom(tree); + * ``` + * + * You would make one decl (values here) in the listener and use lots of times + * in your event methods. + */ + let ParseTreeProperty$1 = class ParseTreeProperty { + constructor(name = "ParseTreeProperty") { + this._symbol = Symbol(name); + } + get(node) { + return node[this._symbol]; + } + set(node, value) { + node[this._symbol] = value; + } + removeFrom(node) { + let result = node[this._symbol]; + delete node[this._symbol]; + return result; + } + }; + ParseTreeProperty.ParseTreeProperty = ParseTreeProperty$1; + + return ParseTreeProperty; +} + +var ParseTreeVisitor = {}; + +var hasRequiredParseTreeVisitor; + +function requireParseTreeVisitor () { + if (hasRequiredParseTreeVisitor) return ParseTreeVisitor; + hasRequiredParseTreeVisitor = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(ParseTreeVisitor, "__esModule", { value: true }); + + return ParseTreeVisitor; +} + +var ParseTreeWalker = {}; + +var hasRequiredParseTreeWalker; + +function requireParseTreeWalker () { + if (hasRequiredParseTreeWalker) return ParseTreeWalker; + hasRequiredParseTreeWalker = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ParseTreeWalker = void 0; + const ErrorNode_1 = requireErrorNode(); + const TerminalNode_1 = requireTerminalNode(); + const RuleNode_1 = requireRuleNode(); + class ParseTreeWalker { + /** + * Performs a walk on the given parse tree starting at the root and going down recursively + * with depth-first search. On each node, {@link ParseTreeWalker#enterRule} is called before + * recursively walking down into child nodes, then + * {@link ParseTreeWalker#exitRule} is called after the recursive call to wind up. + * @param listener The listener used by the walker to process grammar rules + * @param t The parse tree to be walked on + */ + walk(listener, t) { + let nodeStack = []; + let indexStack = []; + let currentNode = t; + let currentIndex = 0; + while (currentNode) { + // pre-order visit + if (currentNode instanceof ErrorNode_1.ErrorNode) { + if (listener.visitErrorNode) { + listener.visitErrorNode(currentNode); + } + } + else if (currentNode instanceof TerminalNode_1.TerminalNode) { + if (listener.visitTerminal) { + listener.visitTerminal(currentNode); + } + } + else { + this.enterRule(listener, currentNode); + } + // Move down to first child, if exists + if (currentNode.childCount > 0) { + nodeStack.push(currentNode); + indexStack.push(currentIndex); + currentIndex = 0; + currentNode = currentNode.getChild(0); + continue; + } + // No child nodes, so walk tree + do { + // post-order visit + if (currentNode instanceof RuleNode_1.RuleNode) { + this.exitRule(listener, currentNode); + } + // No parent, so no siblings + if (nodeStack.length === 0) { + currentNode = undefined; + currentIndex = 0; + break; + } + // Move to next sibling if possible + let last = nodeStack[nodeStack.length - 1]; + currentIndex++; + currentNode = currentIndex < last.childCount ? last.getChild(currentIndex) : undefined; + if (currentNode) { + break; + } + // No next sibling, so move up + currentNode = nodeStack.pop(); + currentIndex = indexStack.pop(); + } while (currentNode); + } + } + /** + * Enters a grammar rule by first triggering the generic event {@link ParseTreeListener#enterEveryRule} + * then by triggering the event specific to the given parse tree node + * @param listener The listener responding to the trigger events + * @param r The grammar rule containing the rule context + */ + enterRule(listener, r) { + let ctx = r.ruleContext; + if (listener.enterEveryRule) { + listener.enterEveryRule(ctx); + } + ctx.enterRule(listener); + } + /** + * Exits a grammar rule by first triggering the event specific to the given parse tree node + * then by triggering the generic event {@link ParseTreeListener#exitEveryRule} + * @param listener The listener responding to the trigger events + * @param r The grammar rule containing the rule context + */ + exitRule(listener, r) { + let ctx = r.ruleContext; + ctx.exitRule(listener); + if (listener.exitEveryRule) { + listener.exitEveryRule(ctx); + } + } + } + exports.ParseTreeWalker = ParseTreeWalker; + (function (ParseTreeWalker) { + ParseTreeWalker.DEFAULT = new ParseTreeWalker(); + })(ParseTreeWalker = exports.ParseTreeWalker || (exports.ParseTreeWalker = {})); + + } (ParseTreeWalker)); + return ParseTreeWalker; +} + +var SyntaxTree = {}; + +var hasRequiredSyntaxTree; + +function requireSyntaxTree () { + if (hasRequiredSyntaxTree) return SyntaxTree; + hasRequiredSyntaxTree = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(SyntaxTree, "__esModule", { value: true }); + + return SyntaxTree; +} + +var Tree = {}; + +var hasRequiredTree$1; + +function requireTree$1 () { + if (hasRequiredTree$1) return Tree; + hasRequiredTree$1 = 1; + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + Object.defineProperty(Tree, "__esModule", { value: true }); + + return Tree; +} + +var hasRequiredTree; + +function requireTree () { + if (hasRequiredTree) return tree; + hasRequiredTree = 1; + (function (exports) { + /*! + * Copyright 2016 The ANTLR Project. All rights reserved. + * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. + */ + var __createBinding = (tree && tree.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = (tree && tree.__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(requireAbstractParseTreeVisitor(), exports); + __exportStar(requireErrorNode(), exports); + __exportStar(requireParseTree(), exports); + __exportStar(requireParseTreeListener(), exports); + __exportStar(requireParseTreeProperty(), exports); + __exportStar(requireParseTreeVisitor(), exports); + __exportStar(requireParseTreeWalker(), exports); + __exportStar(requireRuleNode(), exports); + __exportStar(requireSyntaxTree(), exports); + __exportStar(requireTerminalNode(), exports); + __exportStar(requireTree$1(), exports); + __exportStar(requireTrees(), exports); + + } (tree)); + return tree; +} + +var generated$1 = {}; + +var ExpressionAntlrLexer = {}; + +var hasRequiredExpressionAntlrLexer; + +function requireExpressionAntlrLexer () { + if (hasRequiredExpressionAntlrLexer) return ExpressionAntlrLexer; + hasRequiredExpressionAntlrLexer = 1; + // Generated from src/parser/ExpressionAntlrLexer.g4 by ANTLR 4.7.3-SNAPSHOT + var __createBinding = (ExpressionAntlrLexer && ExpressionAntlrLexer.__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 = (ExpressionAntlrLexer && ExpressionAntlrLexer.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (ExpressionAntlrLexer && ExpressionAntlrLexer.__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(ExpressionAntlrLexer, "__esModule", { value: true }); + ExpressionAntlrLexer.ExpressionAntlrLexer = void 0; + const ATNDeserializer_1 = requireATNDeserializer(); + const Lexer_1 = requireLexer(); + const LexerATNSimulator_1 = requireLexerATNSimulator(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const Utils = __importStar(requireUtils()); + let ExpressionAntlrLexer$1 = class ExpressionAntlrLexer extends Lexer_1.Lexer { + constructor(input) { + super(input); + // tslint:enable:no-trailing-whitespace + this.ignoreWS = true; // usually we ignore whitespace, but inside stringInterpolation, whitespace is significant + this._interp = new LexerATNSimulator_1.LexerATNSimulator(ExpressionAntlrLexer._ATN, this); + } + // @Override + // @NotNull + get vocabulary() { + return ExpressionAntlrLexer.VOCABULARY; + } + // @Override + get grammarFileName() { return "ExpressionAntlrLexer.g4"; } + // @Override + get ruleNames() { return ExpressionAntlrLexer.ruleNames; } + // @Override + get serializedATN() { return ExpressionAntlrLexer._serializedATN; } + // @Override + get channelNames() { return ExpressionAntlrLexer.channelNames; } + // @Override + get modeNames() { return ExpressionAntlrLexer.modeNames; } + // @Override + action(_localctx, ruleIndex, actionIndex) { + switch (ruleIndex) { + case 3: + this.STRING_INTERPOLATION_START_action(_localctx, actionIndex); + break; + case 38: + this.STRING_INTERPOLATION_END_action(_localctx, actionIndex); + break; + } + } + STRING_INTERPOLATION_START_action(_localctx, actionIndex) { + switch (actionIndex) { + case 0: + this.ignoreWS = false; + break; + } + } + STRING_INTERPOLATION_END_action(_localctx, actionIndex) { + switch (actionIndex) { + case 1: + this.ignoreWS = true; + break; + } + } + // @Override + sempred(_localctx, ruleIndex, predIndex) { + switch (ruleIndex) { + case 33: + return this.WHITESPACE_sempred(_localctx, predIndex); + } + return true; + } + WHITESPACE_sempred(_localctx, predIndex) { + switch (predIndex) { + case 0: + return this.ignoreWS; + } + return true; + } + static get _ATN() { + if (!ExpressionAntlrLexer.__ATN) { + ExpressionAntlrLexer.__ATN = new ATNDeserializer_1.ATNDeserializer().deserialize(Utils.toCharArray(ExpressionAntlrLexer._serializedATN)); + } + return ExpressionAntlrLexer.__ATN; + } + }; + ExpressionAntlrLexer.ExpressionAntlrLexer = ExpressionAntlrLexer$1; + ExpressionAntlrLexer$1.STRING_INTERPOLATION_START = 1; + ExpressionAntlrLexer$1.PLUS = 2; + ExpressionAntlrLexer$1.SUBSTRACT = 3; + ExpressionAntlrLexer$1.NON = 4; + ExpressionAntlrLexer$1.XOR = 5; + ExpressionAntlrLexer$1.ASTERISK = 6; + ExpressionAntlrLexer$1.SLASH = 7; + ExpressionAntlrLexer$1.PERCENT = 8; + ExpressionAntlrLexer$1.DOUBLE_EQUAL = 9; + ExpressionAntlrLexer$1.NOT_EQUAL = 10; + ExpressionAntlrLexer$1.SINGLE_AND = 11; + ExpressionAntlrLexer$1.DOUBLE_AND = 12; + ExpressionAntlrLexer$1.DOUBLE_VERTICAL_CYLINDER = 13; + ExpressionAntlrLexer$1.LESS_THAN = 14; + ExpressionAntlrLexer$1.MORE_THAN = 15; + ExpressionAntlrLexer$1.LESS_OR_EQUAl = 16; + ExpressionAntlrLexer$1.MORE_OR_EQUAL = 17; + ExpressionAntlrLexer$1.OPEN_BRACKET = 18; + ExpressionAntlrLexer$1.CLOSE_BRACKET = 19; + ExpressionAntlrLexer$1.DOT = 20; + ExpressionAntlrLexer$1.OPEN_SQUARE_BRACKET = 21; + ExpressionAntlrLexer$1.CLOSE_SQUARE_BRACKET = 22; + ExpressionAntlrLexer$1.OPEN_CURLY_BRACKET = 23; + ExpressionAntlrLexer$1.CLOSE_CURLY_BRACKET = 24; + ExpressionAntlrLexer$1.COMMA = 25; + ExpressionAntlrLexer$1.COLON = 26; + ExpressionAntlrLexer$1.ARROW = 27; + ExpressionAntlrLexer$1.NULL_COALESCE = 28; + ExpressionAntlrLexer$1.QUESTION_MARK = 29; + ExpressionAntlrLexer$1.NUMBER = 30; + ExpressionAntlrLexer$1.WHITESPACE = 31; + ExpressionAntlrLexer$1.IDENTIFIER = 32; + ExpressionAntlrLexer$1.NEWLINE = 33; + ExpressionAntlrLexer$1.STRING = 34; + ExpressionAntlrLexer$1.INVALID_TOKEN_DEFAULT_MODE = 35; + ExpressionAntlrLexer$1.TEMPLATE = 36; + ExpressionAntlrLexer$1.ESCAPE_CHARACTER = 37; + ExpressionAntlrLexer$1.TEXT_CONTENT = 38; + ExpressionAntlrLexer$1.STRING_INTERPOLATION_MODE = 1; + // tslint:disable:no-trailing-whitespace + ExpressionAntlrLexer$1.channelNames = [ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + ]; + // tslint:disable:no-trailing-whitespace + ExpressionAntlrLexer$1.modeNames = [ + "DEFAULT_MODE", "STRING_INTERPOLATION_MODE", + ]; + ExpressionAntlrLexer$1.ruleNames = [ + "LETTER", "DIGIT", "OBJECT_DEFINITION", "STRING_INTERPOLATION_START", + "PLUS", "SUBSTRACT", "NON", "XOR", "ASTERISK", "SLASH", "PERCENT", "DOUBLE_EQUAL", + "NOT_EQUAL", "SINGLE_AND", "DOUBLE_AND", "DOUBLE_VERTICAL_CYLINDER", "LESS_THAN", + "MORE_THAN", "LESS_OR_EQUAl", "MORE_OR_EQUAL", "OPEN_BRACKET", "CLOSE_BRACKET", + "DOT", "OPEN_SQUARE_BRACKET", "CLOSE_SQUARE_BRACKET", "OPEN_CURLY_BRACKET", + "CLOSE_CURLY_BRACKET", "COMMA", "COLON", "ARROW", "NULL_COALESCE", "QUESTION_MARK", + "NUMBER", "WHITESPACE", "IDENTIFIER", "NEWLINE", "STRING", "INVALID_TOKEN_DEFAULT_MODE", + "STRING_INTERPOLATION_END", "TEMPLATE", "ESCAPE_CHARACTER", "TEXT_CONTENT", + ]; + ExpressionAntlrLexer$1._LITERAL_NAMES = [ + undefined, undefined, "'+'", "'-'", "'!'", "'^'", "'*'", "'/'", "'%'", + "'=='", undefined, "'&'", "'&&'", "'||'", "'<'", "'>'", "'<='", "'>='", + "'('", "')'", "'.'", "'['", "']'", "'{'", "'}'", "','", "':'", "'=>'", + "'??'", "'?'", + ]; + ExpressionAntlrLexer$1._SYMBOLIC_NAMES = [ + undefined, "STRING_INTERPOLATION_START", "PLUS", "SUBSTRACT", "NON", "XOR", + "ASTERISK", "SLASH", "PERCENT", "DOUBLE_EQUAL", "NOT_EQUAL", "SINGLE_AND", + "DOUBLE_AND", "DOUBLE_VERTICAL_CYLINDER", "LESS_THAN", "MORE_THAN", "LESS_OR_EQUAl", + "MORE_OR_EQUAL", "OPEN_BRACKET", "CLOSE_BRACKET", "DOT", "OPEN_SQUARE_BRACKET", + "CLOSE_SQUARE_BRACKET", "OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "COMMA", + "COLON", "ARROW", "NULL_COALESCE", "QUESTION_MARK", "NUMBER", "WHITESPACE", + "IDENTIFIER", "NEWLINE", "STRING", "INVALID_TOKEN_DEFAULT_MODE", "TEMPLATE", + "ESCAPE_CHARACTER", "TEXT_CONTENT", + ]; + ExpressionAntlrLexer$1.VOCABULARY = new VocabularyImpl_1.VocabularyImpl(ExpressionAntlrLexer$1._LITERAL_NAMES, ExpressionAntlrLexer$1._SYMBOLIC_NAMES, []); + ExpressionAntlrLexer$1._serializedATN = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02(\u010F\b\x01" + + "\b\x01\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06" + + "\t\x06\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f" + + "\x04\r\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04" + + "\x12\t\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04" + + "\x17\t\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04" + + "\x1C\t\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04 \t \x04!\t!\x04" + + "\"\t\"\x04#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(\t(\x04)\t)\x04*" + + "\t*\x04+\t+\x03\x02\x03\x02\x03\x03\x03\x03\x03\x04\x03\x04\x03\x04\x03" + + "\x04\x05\x04a\n\x04\x03\x04\x03\x04\x03\x04\x03\x04\x06\x04g\n\x04\r\x04" + + "\x0E\x04h\x07\x04k\n\x04\f\x04\x0E\x04n\v\x04\x03\x04\x03\x04\x03\x05" + + "\x03\x05\x03\x05\x03\x05\x03\x05\x03\x06\x03\x06\x03\x07\x03\x07\x03\b" + + "\x03\b\x03\t\x03\t\x03\n\x03\n\x03\v\x03\v\x03\f\x03\f\x03\r\x03\r\x03" + + "\r\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x05\x0E\x8C\n\x0E\x03\x0F\x03\x0F\x03" + + "\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03\x12\x03\x12\x03\x13\x03" + + "\x13\x03\x14\x03\x14\x03\x14\x03\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03" + + "\x17\x03\x17\x03\x18\x03\x18\x03\x19\x03\x19\x03\x1A\x03\x1A\x03\x1B\x03" + + "\x1B\x03\x1C\x03\x1C\x03\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1F\x03\x1F\x03" + + "\x1F\x03 \x03 \x03 \x03!\x03!\x03\"\x06\"\xBB\n\"\r\"\x0E\"\xBC\x03\"" + + "\x03\"\x06\"\xC1\n\"\r\"\x0E\"\xC2\x05\"\xC5\n\"\x03#\x03#\x03#\x03#\x03" + + "#\x03$\x03$\x03$\x03$\x03$\x05$\xD1\n$\x03$\x03$\x03$\x07$\xD6\n$\f$\x0E" + + "$\xD9\v$\x03%\x05%\xDC\n%\x03%\x03%\x03%\x03%\x03&\x03&\x03&\x03&\x07" + + "&\xE6\n&\f&\x0E&\xE9\v&\x03&\x03&\x03&\x03&\x03&\x07&\xF0\n&\f&\x0E&\xF3" + + "\v&\x03&\x05&\xF6\n&\x03\'\x03\'\x03(\x03(\x03(\x03(\x03(\x03(\x03)\x03" + + ")\x03)\x03)\x03)\x06)\u0105\n)\r)\x0E)\u0106\x03)\x03)\x03*\x03*\x03*" + + "\x03+\x03+\x04\xE7\xF1\x02\x02,\x04\x02\x02\x06\x02\x02\b\x02\x02\n\x02" + + "\x03\f\x02\x04\x0E\x02\x05\x10\x02\x06\x12\x02\x07\x14\x02\b\x16\x02\t" + + "\x18\x02\n\x1A\x02\v\x1C\x02\f\x1E\x02\r \x02\x0E\"\x02\x0F$\x02\x10&" + + "\x02\x11(\x02\x12*\x02\x13,\x02\x14.\x02\x150\x02\x162\x02\x174\x02\x18" + + "6\x02\x198\x02\x1A:\x02\x1B<\x02\x1C>\x02\x1D@\x02\x1EB\x02\x1FD\x02 " + + "F\x02!H\x02\"J\x02#L\x02$N\x02%P\x02\x02R\x02&T\x02\'V\x02(\x04\x02\x03" + + "\f\x04\x02C\\c|\x03\x022;\t\x02\f\f\x0F\x0F$$))bb}}\x7F\x7F\x06\x02\v" + + "\v\"\"\xA2\xA2\uFF01\uFF01\x05\x02%%BBaa\x04\x02))^^\x03\x02))\x04\x02" + + "$$^^\x03\x02$$\x04\x02&&bb\x02\u0123\x02\n\x03\x02\x02\x02\x02\f\x03\x02" + + "\x02\x02\x02\x0E\x03\x02\x02\x02\x02\x10\x03\x02\x02\x02\x02\x12\x03\x02" + + "\x02\x02\x02\x14\x03\x02\x02\x02\x02\x16\x03\x02\x02\x02\x02\x18\x03\x02" + + "\x02\x02\x02\x1A\x03\x02\x02\x02\x02\x1C\x03\x02\x02\x02\x02\x1E\x03\x02" + + "\x02\x02\x02 \x03\x02\x02\x02\x02\"\x03\x02\x02\x02\x02$\x03\x02\x02\x02" + + "\x02&\x03\x02\x02\x02\x02(\x03\x02\x02\x02\x02*\x03\x02\x02\x02\x02,\x03" + + "\x02\x02\x02\x02.\x03\x02\x02\x02\x020\x03\x02\x02\x02\x022\x03\x02\x02" + + "\x02\x024\x03\x02\x02\x02\x026\x03\x02\x02\x02\x028\x03\x02\x02\x02\x02" + + ":\x03\x02\x02\x02\x02<\x03\x02\x02\x02\x02>\x03\x02\x02\x02\x02@\x03\x02" + + "\x02\x02\x02B\x03\x02\x02\x02\x02D\x03\x02\x02\x02\x02F\x03\x02\x02\x02" + + "\x02H\x03\x02\x02\x02\x02J\x03\x02\x02\x02\x02L\x03\x02\x02\x02\x02N\x03" + + "\x02\x02\x02\x03P\x03\x02\x02\x02\x03R\x03\x02\x02\x02\x03T\x03\x02\x02" + + "\x02\x03V\x03\x02\x02\x02\x04X\x03\x02\x02\x02\x06Z\x03\x02\x02\x02\b" + + "\\\x03\x02\x02\x02\nq\x03\x02\x02\x02\fv\x03\x02\x02\x02\x0Ex\x03\x02" + + "\x02\x02\x10z\x03\x02\x02\x02\x12|\x03\x02\x02\x02\x14~\x03\x02\x02\x02" + + "\x16\x80\x03\x02\x02\x02\x18\x82\x03\x02\x02\x02\x1A\x84\x03\x02\x02\x02" + + "\x1C\x8B\x03\x02\x02\x02\x1E\x8D\x03\x02\x02\x02 \x8F\x03\x02\x02\x02" + + "\"\x92\x03\x02\x02\x02$\x95\x03\x02\x02\x02&\x97\x03\x02\x02\x02(\x99" + + "\x03\x02\x02\x02*\x9C\x03\x02\x02\x02,\x9F\x03\x02\x02\x02.\xA1\x03\x02" + + "\x02\x020\xA3\x03\x02\x02\x022\xA5\x03\x02\x02\x024\xA7\x03\x02\x02\x02" + + "6\xA9\x03\x02\x02\x028\xAB\x03\x02\x02\x02:\xAD\x03\x02\x02\x02<\xAF\x03" + + "\x02\x02\x02>\xB1\x03\x02\x02\x02@\xB4\x03\x02\x02\x02B\xB7\x03\x02\x02" + + "\x02D\xBA\x03\x02\x02\x02F\xC6\x03\x02\x02\x02H\xD0\x03\x02\x02\x02J\xDB" + + "\x03\x02\x02\x02L\xF5\x03\x02\x02\x02N\xF7\x03\x02\x02\x02P\xF9\x03\x02" + + "\x02\x02R\xFF\x03\x02\x02\x02T\u010A\x03\x02\x02\x02V\u010D\x03\x02\x02" + + "\x02XY\t\x02\x02\x02Y\x05\x03\x02\x02\x02Z[\t\x03\x02\x02[\x07\x03\x02" + + "\x02\x02\\l\x07}\x02\x02]k\x05F#\x02^a\x05H$\x02_a\x05L&\x02`^\x03\x02" + + "\x02\x02`_\x03\x02\x02\x02ab\x03\x02\x02\x02bf\x07<\x02\x02cg\x05L&\x02" + + "dg\n\x04\x02\x02eg\x05\b\x04\x02fc\x03\x02\x02\x02fd\x03\x02\x02\x02f" + + "e\x03\x02\x02\x02gh\x03\x02\x02\x02hf\x03\x02\x02\x02hi\x03\x02\x02\x02" + + "ik\x03\x02\x02\x02j]\x03\x02\x02\x02j`\x03\x02\x02\x02kn\x03\x02\x02\x02" + + "lj\x03\x02\x02\x02lm\x03\x02\x02\x02mo\x03\x02\x02\x02nl\x03\x02\x02\x02" + + "op\x07\x7F\x02\x02p\t\x03\x02\x02\x02qr\x07b\x02\x02rs\b\x05\x02\x02s" + + "t\x03\x02\x02\x02tu\b\x05\x03\x02u\v\x03\x02\x02\x02vw\x07-\x02\x02w\r" + + "\x03\x02\x02\x02xy\x07/\x02\x02y\x0F\x03\x02\x02\x02z{\x07#\x02\x02{\x11" + + "\x03\x02\x02\x02|}\x07`\x02\x02}\x13\x03\x02\x02\x02~\x7F\x07,\x02\x02" + + "\x7F\x15\x03\x02\x02\x02\x80\x81\x071\x02\x02\x81\x17\x03\x02\x02\x02" + + "\x82\x83\x07\'\x02\x02\x83\x19\x03\x02\x02\x02\x84\x85\x07?\x02\x02\x85" + + "\x86\x07?\x02\x02\x86\x1B\x03\x02\x02\x02\x87\x88\x07#\x02\x02\x88\x8C" + + "\x07?\x02\x02\x89\x8A\x07>\x02\x02\x8A\x8C\x07@\x02\x02\x8B\x87\x03\x02" + + "\x02\x02\x8B\x89\x03\x02\x02\x02\x8C\x1D\x03\x02\x02\x02\x8D\x8E\x07(" + + "\x02\x02\x8E\x1F\x03\x02\x02\x02\x8F\x90\x07(\x02\x02\x90\x91\x07(\x02" + + "\x02\x91!\x03\x02\x02\x02\x92\x93\x07~\x02\x02\x93\x94\x07~\x02\x02\x94" + + "#\x03\x02\x02\x02\x95\x96\x07>\x02\x02\x96%\x03\x02\x02\x02\x97\x98\x07" + + "@\x02\x02\x98\'\x03\x02\x02\x02\x99\x9A\x07>\x02\x02\x9A\x9B\x07?\x02" + + "\x02\x9B)\x03\x02\x02\x02\x9C\x9D\x07@\x02\x02\x9D\x9E\x07?\x02\x02\x9E" + + "+\x03\x02\x02\x02\x9F\xA0\x07*\x02\x02\xA0-\x03\x02\x02\x02\xA1\xA2\x07" + + "+\x02\x02\xA2/\x03\x02\x02\x02\xA3\xA4\x070\x02\x02\xA41\x03\x02\x02\x02" + + "\xA5\xA6\x07]\x02\x02\xA63\x03\x02\x02\x02\xA7\xA8\x07_\x02\x02\xA85\x03" + + "\x02\x02\x02\xA9\xAA\x07}\x02\x02\xAA7\x03\x02\x02\x02\xAB\xAC\x07\x7F" + + "\x02\x02\xAC9\x03\x02\x02\x02\xAD\xAE\x07.\x02\x02\xAE;\x03\x02\x02\x02" + + "\xAF\xB0\x07<\x02\x02\xB0=\x03\x02\x02\x02\xB1\xB2\x07?\x02\x02\xB2\xB3" + + "\x07@\x02\x02\xB3?\x03\x02\x02\x02\xB4\xB5\x07A\x02\x02\xB5\xB6\x07A\x02" + + "\x02\xB6A\x03\x02\x02\x02\xB7\xB8\x07A\x02\x02\xB8C\x03\x02\x02\x02\xB9" + + "\xBB\x05\x06\x03\x02\xBA\xB9\x03\x02\x02\x02\xBB\xBC\x03\x02\x02\x02\xBC" + + "\xBA\x03\x02\x02\x02\xBC\xBD\x03\x02\x02\x02\xBD\xC4\x03\x02\x02\x02\xBE" + + "\xC0\x070\x02\x02\xBF\xC1\x05\x06\x03\x02\xC0\xBF\x03\x02\x02\x02\xC1" + + "\xC2\x03\x02\x02\x02\xC2\xC0\x03\x02\x02\x02\xC2\xC3\x03\x02\x02\x02\xC3" + + "\xC5\x03\x02\x02\x02\xC4\xBE\x03\x02\x02\x02\xC4\xC5\x03\x02\x02\x02\xC5" + + "E\x03\x02\x02\x02\xC6\xC7\t\x05\x02\x02\xC7\xC8\x06#\x02\x02\xC8\xC9\x03" + + "\x02\x02\x02\xC9\xCA\b#\x04\x02\xCAG\x03\x02\x02\x02\xCB\xD1\x05\x04\x02" + + "\x02\xCC\xD1\t\x06\x02\x02\xCD\xCE\x07B\x02\x02\xCE\xD1\x07B\x02\x02\xCF" + + "\xD1\x04&\'\x02\xD0\xCB\x03\x02\x02\x02\xD0\xCC\x03\x02\x02\x02\xD0\xCD" + + "\x03\x02\x02\x02\xD0\xCF\x03\x02\x02\x02\xD1\xD7\x03\x02\x02\x02\xD2\xD6" + + "\x05\x04\x02\x02\xD3\xD6\x05\x06\x03\x02\xD4\xD6\x07a\x02\x02\xD5\xD2" + + "\x03\x02\x02\x02\xD5\xD3\x03\x02\x02\x02\xD5\xD4\x03\x02\x02\x02\xD6\xD9" + + "\x03\x02\x02\x02\xD7\xD5\x03\x02\x02\x02\xD7\xD8\x03\x02\x02\x02\xD8I" + + "\x03\x02\x02\x02\xD9\xD7\x03\x02\x02\x02\xDA\xDC\x07\x0F\x02\x02\xDB\xDA" + + "\x03\x02\x02\x02\xDB\xDC\x03\x02\x02\x02\xDC\xDD\x03\x02\x02\x02\xDD\xDE" + + "\x07\f\x02\x02\xDE\xDF\x03\x02\x02\x02\xDF\xE0\b%\x04\x02\xE0K\x03\x02" + + "\x02\x02\xE1\xE7\x07)\x02\x02\xE2\xE3\x07^\x02\x02\xE3\xE6\t\x07\x02\x02" + + "\xE4\xE6\n\b\x02\x02\xE5\xE2\x03\x02\x02\x02\xE5\xE4\x03\x02\x02\x02\xE6" + + "\xE9\x03\x02\x02\x02\xE7\xE8\x03\x02\x02\x02\xE7\xE5\x03\x02\x02\x02\xE8" + + "\xEA\x03\x02\x02\x02\xE9\xE7\x03\x02\x02\x02\xEA\xF6\x07)\x02\x02\xEB" + + "\xF1\x07$\x02\x02\xEC\xED\x07^\x02\x02\xED\xF0\t\t\x02\x02\xEE\xF0\n\n" + + "\x02\x02\xEF\xEC\x03\x02\x02\x02\xEF\xEE\x03\x02\x02\x02\xF0\xF3\x03\x02" + + "\x02\x02\xF1\xF2\x03\x02\x02\x02\xF1\xEF\x03\x02\x02\x02\xF2\xF4\x03\x02" + + "\x02\x02\xF3\xF1\x03\x02\x02\x02\xF4\xF6\x07$\x02\x02\xF5\xE1\x03\x02" + + "\x02\x02\xF5\xEB\x03\x02\x02\x02\xF6M\x03\x02\x02\x02\xF7\xF8\v\x02\x02" + + "\x02\xF8O\x03\x02\x02\x02\xF9\xFA\x07b\x02\x02\xFA\xFB\b(\x05\x02\xFB" + + "\xFC\x03\x02\x02\x02\xFC\xFD\b(\x06\x02\xFD\xFE\b(\x07\x02\xFEQ\x03\x02" + + "\x02\x02\xFF\u0100\x07&\x02\x02\u0100\u0104\x07}\x02\x02\u0101\u0105\x05" + + "L&\x02\u0102\u0105\x05\b\x04\x02\u0103\u0105\n\x04\x02\x02\u0104\u0101" + + "\x03\x02\x02\x02\u0104\u0102\x03\x02\x02\x02\u0104\u0103\x03\x02\x02\x02" + + "\u0105\u0106\x03\x02\x02\x02\u0106\u0104\x03\x02\x02\x02\u0106\u0107\x03" + + "\x02\x02\x02\u0107\u0108\x03\x02\x02\x02\u0108\u0109\x07\x7F\x02\x02\u0109" + + "S\x03\x02\x02\x02\u010A\u010B\x07^\x02\x02\u010B\u010C\t\v\x02\x02\u010C" + + "U\x03\x02\x02\x02\u010D\u010E\v\x02\x02\x02\u010EW\x03\x02\x02\x02\x18" + + "\x02\x03`fhjl\x8B\xBC\xC2\xC4\xD0\xD5\xD7\xDB\xE5\xE7\xEF\xF1\xF5\u0104" + + "\u0106\b\x03\x05\x02\x07\x03\x02\b\x02\x02\x03(\x03\t\x03\x02\x06\x02" + + "\x02"; + + return ExpressionAntlrLexer; +} + +var ExpressionAntlrParserListener = {}; + +var hasRequiredExpressionAntlrParserListener; + +function requireExpressionAntlrParserListener () { + if (hasRequiredExpressionAntlrParserListener) return ExpressionAntlrParserListener; + hasRequiredExpressionAntlrParserListener = 1; + // Generated from src/parser/ExpressionAntlrParser.g4 by ANTLR 4.7.3-SNAPSHOT + Object.defineProperty(ExpressionAntlrParserListener, "__esModule", { value: true }); + + return ExpressionAntlrParserListener; +} + +var ExpressionAntlrParser = {}; + +var hasRequiredExpressionAntlrParser; + +function requireExpressionAntlrParser () { + if (hasRequiredExpressionAntlrParser) return ExpressionAntlrParser; + hasRequiredExpressionAntlrParser = 1; + // Generated from src/parser/ExpressionAntlrParser.g4 by ANTLR 4.7.3-SNAPSHOT + var __createBinding = (ExpressionAntlrParser && ExpressionAntlrParser.__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 = (ExpressionAntlrParser && ExpressionAntlrParser.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (ExpressionAntlrParser && ExpressionAntlrParser.__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(ExpressionAntlrParser, "__esModule", { value: true }); + ExpressionAntlrParser.KeyContext = ExpressionAntlrParser.KeyValuePairContext = ExpressionAntlrParser.KeyValuePairListContext = ExpressionAntlrParser.LambdaContext = ExpressionAntlrParser.ArgsListContext = ExpressionAntlrParser.TextContentContext = ExpressionAntlrParser.StringInterpolationContext = ExpressionAntlrParser.IndexAccessExpContext = ExpressionAntlrParser.FuncInvokeExpContext = ExpressionAntlrParser.MemberAccessExpContext = ExpressionAntlrParser.StringInterpolationAtomContext = ExpressionAntlrParser.IdAtomContext = ExpressionAntlrParser.StringAtomContext = ExpressionAntlrParser.NumericAtomContext = ExpressionAntlrParser.JsonCreationExpContext = ExpressionAntlrParser.ArrayCreationExpContext = ExpressionAntlrParser.ParenthesisExpContext = ExpressionAntlrParser.PrimaryExpressionContext = ExpressionAntlrParser.PrimaryExpContext = ExpressionAntlrParser.TripleOpExpContext = ExpressionAntlrParser.BinaryOpExpContext = ExpressionAntlrParser.UnaryOpExpContext = ExpressionAntlrParser.ExpressionContext = ExpressionAntlrParser.FileContext = ExpressionAntlrParser.ExpressionAntlrParser = void 0; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + const ATN_1 = requireATN(); + const ATNDeserializer_1 = requireATNDeserializer(); + const FailedPredicateException_1 = requireFailedPredicateException(); + const NoViableAltException_1 = requireNoViableAltException(); + const Parser_1 = requireParser$1(); + const ParserRuleContext_1 = requireParserRuleContext(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const RecognitionException_1 = requireRecognitionException(); + const Token_1 = requireToken(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const Utils = __importStar(requireUtils()); + let ExpressionAntlrParser$1 = class ExpressionAntlrParser extends Parser_1.Parser { + constructor(input) { + super(input); + this._interp = new ParserATNSimulator_1.ParserATNSimulator(ExpressionAntlrParser._ATN, this); + } + // @Override + // @NotNull + get vocabulary() { + return ExpressionAntlrParser.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + // @Override + get grammarFileName() { return "ExpressionAntlrParser.g4"; } + // @Override + get ruleNames() { return ExpressionAntlrParser.ruleNames; } + // @Override + get serializedATN() { return ExpressionAntlrParser._serializedATN; } + // @RuleVersion(0) + file() { + let _localctx = new FileContext(this._ctx, this.state); + this.enterRule(_localctx, 0, ExpressionAntlrParser.RULE_file); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 20; + this.expression(0); + this.state = 21; + this.match(ExpressionAntlrParser.EOF); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + expression(_p) { + if (_p === undefined) { + _p = 0; + } + let _parentctx = this._ctx; + let _parentState = this.state; + let _localctx = new ExpressionContext(this._ctx, _parentState); + let _prevctx = _localctx; + let _startState = 2; + this.enterRecursionRule(_localctx, 2, ExpressionAntlrParser.RULE_expression, _p); + let _la; + try { + let _alt; + this.enterOuterAlt(_localctx, 1); + { + this.state = 27; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case ExpressionAntlrParser.PLUS: + case ExpressionAntlrParser.SUBSTRACT: + case ExpressionAntlrParser.NON: + { + _localctx = new UnaryOpExpContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 24; + _la = this._input.LA(1); + if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << ExpressionAntlrParser.PLUS) | (1 << ExpressionAntlrParser.SUBSTRACT) | (1 << ExpressionAntlrParser.NON))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 25; + this.expression(12); + } + break; + case ExpressionAntlrParser.STRING_INTERPOLATION_START: + case ExpressionAntlrParser.OPEN_BRACKET: + case ExpressionAntlrParser.OPEN_SQUARE_BRACKET: + case ExpressionAntlrParser.OPEN_CURLY_BRACKET: + case ExpressionAntlrParser.NUMBER: + case ExpressionAntlrParser.IDENTIFIER: + case ExpressionAntlrParser.STRING: + { + _localctx = new PrimaryExpContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 26; + this.primaryExpression(0); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + this._ctx._stop = this._input.tryLT(-1); + this.state = 64; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + while (_alt !== 2 && _alt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + if (this._parseListeners != null) { + this.triggerExitRuleEvent(); + } + _prevctx = _localctx; + { + this.state = 62; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 1, this._ctx)) { + case 1: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 29; + if (!(this.precpred(this._ctx, 11))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 11)"); + } + this.state = 30; + this.match(ExpressionAntlrParser.XOR); + this.state = 31; + this.expression(11); + } + break; + case 2: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 32; + if (!(this.precpred(this._ctx, 10))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 10)"); + } + this.state = 33; + _la = this._input.LA(1); + if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << ExpressionAntlrParser.ASTERISK) | (1 << ExpressionAntlrParser.SLASH) | (1 << ExpressionAntlrParser.PERCENT))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 34; + this.expression(11); + } + break; + case 3: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 35; + if (!(this.precpred(this._ctx, 9))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 9)"); + } + this.state = 36; + _la = this._input.LA(1); + if (!(_la === ExpressionAntlrParser.PLUS || _la === ExpressionAntlrParser.SUBSTRACT)) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 37; + this.expression(10); + } + break; + case 4: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 38; + if (!(this.precpred(this._ctx, 8))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 8)"); + } + this.state = 39; + _la = this._input.LA(1); + if (!(_la === ExpressionAntlrParser.DOUBLE_EQUAL || _la === ExpressionAntlrParser.NOT_EQUAL)) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 40; + this.expression(9); + } + break; + case 5: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 41; + if (!(this.precpred(this._ctx, 7))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 7)"); + } + { + this.state = 42; + this.match(ExpressionAntlrParser.SINGLE_AND); + } + this.state = 43; + this.expression(8); + } + break; + case 6: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 44; + if (!(this.precpred(this._ctx, 6))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 6)"); + } + this.state = 45; + _la = this._input.LA(1); + if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << ExpressionAntlrParser.LESS_THAN) | (1 << ExpressionAntlrParser.MORE_THAN) | (1 << ExpressionAntlrParser.LESS_OR_EQUAl) | (1 << ExpressionAntlrParser.MORE_OR_EQUAL))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 46; + this.expression(7); + } + break; + case 7: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 47; + if (!(this.precpred(this._ctx, 5))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 5)"); + } + this.state = 48; + this.match(ExpressionAntlrParser.DOUBLE_AND); + this.state = 49; + this.expression(6); + } + break; + case 8: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 50; + if (!(this.precpred(this._ctx, 4))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 4)"); + } + this.state = 51; + this.match(ExpressionAntlrParser.DOUBLE_VERTICAL_CYLINDER); + this.state = 52; + this.expression(5); + } + break; + case 9: + { + _localctx = new BinaryOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 53; + if (!(this.precpred(this._ctx, 3))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 3)"); + } + this.state = 54; + this.match(ExpressionAntlrParser.NULL_COALESCE); + this.state = 55; + this.expression(4); + } + break; + case 10: + { + _localctx = new TripleOpExpContext(new ExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_expression); + this.state = 56; + if (!(this.precpred(this._ctx, 2))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 2)"); + } + this.state = 57; + this.match(ExpressionAntlrParser.QUESTION_MARK); + this.state = 58; + this.expression(0); + this.state = 59; + this.match(ExpressionAntlrParser.COLON); + this.state = 60; + this.expression(3); + } + break; + } + } + } + this.state = 66; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 2, this._ctx); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.unrollRecursionContexts(_parentctx); + } + return _localctx; + } + // @RuleVersion(0) + primaryExpression(_p) { + if (_p === undefined) { + _p = 0; + } + let _parentctx = this._ctx; + let _parentState = this.state; + let _localctx = new PrimaryExpressionContext(this._ctx, _parentState); + let _prevctx = _localctx; + let _startState = 4; + this.enterRecursionRule(_localctx, 4, ExpressionAntlrParser.RULE_primaryExpression, _p); + let _la; + try { + let _alt; + this.enterOuterAlt(_localctx, 1); + { + this.state = 86; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case ExpressionAntlrParser.OPEN_BRACKET: + { + _localctx = new ParenthesisExpContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 68; + this.match(ExpressionAntlrParser.OPEN_BRACKET); + this.state = 69; + this.expression(0); + this.state = 70; + this.match(ExpressionAntlrParser.CLOSE_BRACKET); + } + break; + case ExpressionAntlrParser.OPEN_SQUARE_BRACKET: + { + _localctx = new ArrayCreationExpContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 72; + this.match(ExpressionAntlrParser.OPEN_SQUARE_BRACKET); + this.state = 74; + this._errHandler.sync(this); + _la = this._input.LA(1); + if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << ExpressionAntlrParser.STRING_INTERPOLATION_START) | (1 << ExpressionAntlrParser.PLUS) | (1 << ExpressionAntlrParser.SUBSTRACT) | (1 << ExpressionAntlrParser.NON) | (1 << ExpressionAntlrParser.OPEN_BRACKET) | (1 << ExpressionAntlrParser.OPEN_SQUARE_BRACKET) | (1 << ExpressionAntlrParser.OPEN_CURLY_BRACKET) | (1 << ExpressionAntlrParser.NUMBER))) !== 0) || _la === ExpressionAntlrParser.IDENTIFIER || _la === ExpressionAntlrParser.STRING) { + { + this.state = 73; + this.argsList(); + } + } + this.state = 76; + this.match(ExpressionAntlrParser.CLOSE_SQUARE_BRACKET); + } + break; + case ExpressionAntlrParser.OPEN_CURLY_BRACKET: + { + _localctx = new JsonCreationExpContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 77; + this.match(ExpressionAntlrParser.OPEN_CURLY_BRACKET); + this.state = 79; + this._errHandler.sync(this); + _la = this._input.LA(1); + if (_la === ExpressionAntlrParser.IDENTIFIER || _la === ExpressionAntlrParser.STRING) { + { + this.state = 78; + this.keyValuePairList(); + } + } + this.state = 81; + this.match(ExpressionAntlrParser.CLOSE_CURLY_BRACKET); + } + break; + case ExpressionAntlrParser.NUMBER: + { + _localctx = new NumericAtomContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 82; + this.match(ExpressionAntlrParser.NUMBER); + } + break; + case ExpressionAntlrParser.STRING: + { + _localctx = new StringAtomContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 83; + this.match(ExpressionAntlrParser.STRING); + } + break; + case ExpressionAntlrParser.IDENTIFIER: + { + _localctx = new IdAtomContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 84; + this.match(ExpressionAntlrParser.IDENTIFIER); + } + break; + case ExpressionAntlrParser.STRING_INTERPOLATION_START: + { + _localctx = new StringInterpolationAtomContext(_localctx); + this._ctx = _localctx; + _prevctx = _localctx; + this.state = 85; + this.stringInterpolation(); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + this._ctx._stop = this._input.tryLT(-1); + this.state = 107; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); + while (_alt !== 2 && _alt !== ATN_1.ATN.INVALID_ALT_NUMBER) { + if (_alt === 1) { + if (this._parseListeners != null) { + this.triggerExitRuleEvent(); + } + _prevctx = _localctx; + { + this.state = 105; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 8, this._ctx)) { + case 1: + { + _localctx = new MemberAccessExpContext(new PrimaryExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_primaryExpression); + this.state = 88; + if (!(this.precpred(this._ctx, 3))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 3)"); + } + this.state = 89; + this.match(ExpressionAntlrParser.DOT); + this.state = 90; + this.match(ExpressionAntlrParser.IDENTIFIER); + } + break; + case 2: + { + _localctx = new FuncInvokeExpContext(new PrimaryExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_primaryExpression); + this.state = 91; + if (!(this.precpred(this._ctx, 2))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 2)"); + } + this.state = 93; + this._errHandler.sync(this); + _la = this._input.LA(1); + if (_la === ExpressionAntlrParser.NON) { + { + this.state = 92; + this.match(ExpressionAntlrParser.NON); + } + } + this.state = 95; + this.match(ExpressionAntlrParser.OPEN_BRACKET); + this.state = 97; + this._errHandler.sync(this); + _la = this._input.LA(1); + if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << ExpressionAntlrParser.STRING_INTERPOLATION_START) | (1 << ExpressionAntlrParser.PLUS) | (1 << ExpressionAntlrParser.SUBSTRACT) | (1 << ExpressionAntlrParser.NON) | (1 << ExpressionAntlrParser.OPEN_BRACKET) | (1 << ExpressionAntlrParser.OPEN_SQUARE_BRACKET) | (1 << ExpressionAntlrParser.OPEN_CURLY_BRACKET) | (1 << ExpressionAntlrParser.NUMBER))) !== 0) || _la === ExpressionAntlrParser.IDENTIFIER || _la === ExpressionAntlrParser.STRING) { + { + this.state = 96; + this.argsList(); + } + } + this.state = 99; + this.match(ExpressionAntlrParser.CLOSE_BRACKET); + } + break; + case 3: + { + _localctx = new IndexAccessExpContext(new PrimaryExpressionContext(_parentctx, _parentState)); + this.pushNewRecursionContext(_localctx, _startState, ExpressionAntlrParser.RULE_primaryExpression); + this.state = 100; + if (!(this.precpred(this._ctx, 1))) { + throw new FailedPredicateException_1.FailedPredicateException(this, "this.precpred(this._ctx, 1)"); + } + this.state = 101; + this.match(ExpressionAntlrParser.OPEN_SQUARE_BRACKET); + this.state = 102; + this.expression(0); + this.state = 103; + this.match(ExpressionAntlrParser.CLOSE_SQUARE_BRACKET); + } + break; + } + } + } + this.state = 109; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 9, this._ctx); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.unrollRecursionContexts(_parentctx); + } + return _localctx; + } + // @RuleVersion(0) + stringInterpolation() { + let _localctx = new StringInterpolationContext(this._ctx, this.state); + this.enterRule(_localctx, 6, ExpressionAntlrParser.RULE_stringInterpolation); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 110; + this.match(ExpressionAntlrParser.STRING_INTERPOLATION_START); + this.state = 116; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (((((_la - 36)) & ~0x1F) === 0 && ((1 << (_la - 36)) & ((1 << (ExpressionAntlrParser.TEMPLATE - 36)) | (1 << (ExpressionAntlrParser.ESCAPE_CHARACTER - 36)) | (1 << (ExpressionAntlrParser.TEXT_CONTENT - 36)))) !== 0)) { + { + this.state = 114; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case ExpressionAntlrParser.ESCAPE_CHARACTER: + { + this.state = 111; + this.match(ExpressionAntlrParser.ESCAPE_CHARACTER); + } + break; + case ExpressionAntlrParser.TEMPLATE: + { + this.state = 112; + this.match(ExpressionAntlrParser.TEMPLATE); + } + break; + case ExpressionAntlrParser.TEXT_CONTENT: + { + this.state = 113; + this.textContent(); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + this.state = 118; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + this.state = 119; + this.match(ExpressionAntlrParser.STRING_INTERPOLATION_START); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + textContent() { + let _localctx = new TextContentContext(this._ctx, this.state); + this.enterRule(_localctx, 8, ExpressionAntlrParser.RULE_textContent); + try { + let _alt; + this.enterOuterAlt(_localctx, 1); + { + this.state = 122; + this._errHandler.sync(this); + _alt = 1; + do { + switch (_alt) { + case 1: + { + { + this.state = 121; + this.match(ExpressionAntlrParser.TEXT_CONTENT); + } + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + this.state = 124; + this._errHandler.sync(this); + _alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx); + } while (_alt !== 2 && _alt !== ATN_1.ATN.INVALID_ALT_NUMBER); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + argsList() { + let _localctx = new ArgsListContext(this._ctx, this.state); + this.enterRule(_localctx, 10, ExpressionAntlrParser.RULE_argsList); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 128; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 13, this._ctx)) { + case 1: + { + this.state = 126; + this.lambda(); + } + break; + case 2: + { + this.state = 127; + this.expression(0); + } + break; + } + this.state = 137; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (_la === ExpressionAntlrParser.COMMA) { + { + { + this.state = 130; + this.match(ExpressionAntlrParser.COMMA); + this.state = 133; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 14, this._ctx)) { + case 1: + { + this.state = 131; + this.lambda(); + } + break; + case 2: + { + this.state = 132; + this.expression(0); + } + break; + } + } + } + this.state = 139; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + lambda() { + let _localctx = new LambdaContext(this._ctx, this.state); + this.enterRule(_localctx, 12, ExpressionAntlrParser.RULE_lambda); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 140; + this.match(ExpressionAntlrParser.IDENTIFIER); + this.state = 141; + this.match(ExpressionAntlrParser.ARROW); + this.state = 142; + this.expression(0); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + keyValuePairList() { + let _localctx = new KeyValuePairListContext(this._ctx, this.state); + this.enterRule(_localctx, 14, ExpressionAntlrParser.RULE_keyValuePairList); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 144; + this.keyValuePair(); + this.state = 149; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (_la === ExpressionAntlrParser.COMMA) { + { + { + this.state = 145; + this.match(ExpressionAntlrParser.COMMA); + this.state = 146; + this.keyValuePair(); + } + } + this.state = 151; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + keyValuePair() { + let _localctx = new KeyValuePairContext(this._ctx, this.state); + this.enterRule(_localctx, 16, ExpressionAntlrParser.RULE_keyValuePair); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 152; + this.key(); + this.state = 153; + this.match(ExpressionAntlrParser.COLON); + this.state = 154; + this.expression(0); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + key() { + let _localctx = new KeyContext(this._ctx, this.state); + this.enterRule(_localctx, 18, ExpressionAntlrParser.RULE_key); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 156; + _la = this._input.LA(1); + if (!(_la === ExpressionAntlrParser.IDENTIFIER || _la === ExpressionAntlrParser.STRING)) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + sempred(_localctx, ruleIndex, predIndex) { + switch (ruleIndex) { + case 1: + return this.expression_sempred(_localctx, predIndex); + case 2: + return this.primaryExpression_sempred(_localctx, predIndex); + } + return true; + } + expression_sempred(_localctx, predIndex) { + switch (predIndex) { + case 0: + return this.precpred(this._ctx, 11); + case 1: + return this.precpred(this._ctx, 10); + case 2: + return this.precpred(this._ctx, 9); + case 3: + return this.precpred(this._ctx, 8); + case 4: + return this.precpred(this._ctx, 7); + case 5: + return this.precpred(this._ctx, 6); + case 6: + return this.precpred(this._ctx, 5); + case 7: + return this.precpred(this._ctx, 4); + case 8: + return this.precpred(this._ctx, 3); + case 9: + return this.precpred(this._ctx, 2); + } + return true; + } + primaryExpression_sempred(_localctx, predIndex) { + switch (predIndex) { + case 10: + return this.precpred(this._ctx, 3); + case 11: + return this.precpred(this._ctx, 2); + case 12: + return this.precpred(this._ctx, 1); + } + return true; + } + static get _ATN() { + if (!ExpressionAntlrParser.__ATN) { + ExpressionAntlrParser.__ATN = new ATNDeserializer_1.ATNDeserializer().deserialize(Utils.toCharArray(ExpressionAntlrParser._serializedATN)); + } + return ExpressionAntlrParser.__ATN; + } + }; + ExpressionAntlrParser.ExpressionAntlrParser = ExpressionAntlrParser$1; + ExpressionAntlrParser$1.STRING_INTERPOLATION_START = 1; + ExpressionAntlrParser$1.PLUS = 2; + ExpressionAntlrParser$1.SUBSTRACT = 3; + ExpressionAntlrParser$1.NON = 4; + ExpressionAntlrParser$1.XOR = 5; + ExpressionAntlrParser$1.ASTERISK = 6; + ExpressionAntlrParser$1.SLASH = 7; + ExpressionAntlrParser$1.PERCENT = 8; + ExpressionAntlrParser$1.DOUBLE_EQUAL = 9; + ExpressionAntlrParser$1.NOT_EQUAL = 10; + ExpressionAntlrParser$1.SINGLE_AND = 11; + ExpressionAntlrParser$1.DOUBLE_AND = 12; + ExpressionAntlrParser$1.DOUBLE_VERTICAL_CYLINDER = 13; + ExpressionAntlrParser$1.LESS_THAN = 14; + ExpressionAntlrParser$1.MORE_THAN = 15; + ExpressionAntlrParser$1.LESS_OR_EQUAl = 16; + ExpressionAntlrParser$1.MORE_OR_EQUAL = 17; + ExpressionAntlrParser$1.OPEN_BRACKET = 18; + ExpressionAntlrParser$1.CLOSE_BRACKET = 19; + ExpressionAntlrParser$1.DOT = 20; + ExpressionAntlrParser$1.OPEN_SQUARE_BRACKET = 21; + ExpressionAntlrParser$1.CLOSE_SQUARE_BRACKET = 22; + ExpressionAntlrParser$1.OPEN_CURLY_BRACKET = 23; + ExpressionAntlrParser$1.CLOSE_CURLY_BRACKET = 24; + ExpressionAntlrParser$1.COMMA = 25; + ExpressionAntlrParser$1.COLON = 26; + ExpressionAntlrParser$1.ARROW = 27; + ExpressionAntlrParser$1.NULL_COALESCE = 28; + ExpressionAntlrParser$1.QUESTION_MARK = 29; + ExpressionAntlrParser$1.NUMBER = 30; + ExpressionAntlrParser$1.WHITESPACE = 31; + ExpressionAntlrParser$1.IDENTIFIER = 32; + ExpressionAntlrParser$1.NEWLINE = 33; + ExpressionAntlrParser$1.STRING = 34; + ExpressionAntlrParser$1.INVALID_TOKEN_DEFAULT_MODE = 35; + ExpressionAntlrParser$1.TEMPLATE = 36; + ExpressionAntlrParser$1.ESCAPE_CHARACTER = 37; + ExpressionAntlrParser$1.TEXT_CONTENT = 38; + ExpressionAntlrParser$1.RULE_file = 0; + ExpressionAntlrParser$1.RULE_expression = 1; + ExpressionAntlrParser$1.RULE_primaryExpression = 2; + ExpressionAntlrParser$1.RULE_stringInterpolation = 3; + ExpressionAntlrParser$1.RULE_textContent = 4; + ExpressionAntlrParser$1.RULE_argsList = 5; + ExpressionAntlrParser$1.RULE_lambda = 6; + ExpressionAntlrParser$1.RULE_keyValuePairList = 7; + ExpressionAntlrParser$1.RULE_keyValuePair = 8; + ExpressionAntlrParser$1.RULE_key = 9; + // tslint:disable:no-trailing-whitespace + ExpressionAntlrParser$1.ruleNames = [ + "file", "expression", "primaryExpression", "stringInterpolation", "textContent", + "argsList", "lambda", "keyValuePairList", "keyValuePair", "key", + ]; + ExpressionAntlrParser$1._LITERAL_NAMES = [ + undefined, undefined, "'+'", "'-'", "'!'", "'^'", "'*'", "'/'", "'%'", + "'=='", undefined, "'&'", "'&&'", "'||'", "'<'", "'>'", "'<='", "'>='", + "'('", "')'", "'.'", "'['", "']'", "'{'", "'}'", "','", "':'", "'=>'", + "'??'", "'?'", + ]; + ExpressionAntlrParser$1._SYMBOLIC_NAMES = [ + undefined, "STRING_INTERPOLATION_START", "PLUS", "SUBSTRACT", "NON", "XOR", + "ASTERISK", "SLASH", "PERCENT", "DOUBLE_EQUAL", "NOT_EQUAL", "SINGLE_AND", + "DOUBLE_AND", "DOUBLE_VERTICAL_CYLINDER", "LESS_THAN", "MORE_THAN", "LESS_OR_EQUAl", + "MORE_OR_EQUAL", "OPEN_BRACKET", "CLOSE_BRACKET", "DOT", "OPEN_SQUARE_BRACKET", + "CLOSE_SQUARE_BRACKET", "OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "COMMA", + "COLON", "ARROW", "NULL_COALESCE", "QUESTION_MARK", "NUMBER", "WHITESPACE", + "IDENTIFIER", "NEWLINE", "STRING", "INVALID_TOKEN_DEFAULT_MODE", "TEMPLATE", + "ESCAPE_CHARACTER", "TEXT_CONTENT", + ]; + ExpressionAntlrParser$1.VOCABULARY = new VocabularyImpl_1.VocabularyImpl(ExpressionAntlrParser$1._LITERAL_NAMES, ExpressionAntlrParser$1._SYMBOLIC_NAMES, []); + ExpressionAntlrParser$1._serializedATN = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03(\xA1\x04\x02" + + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + + "\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x03\x02\x03\x02\x03\x02" + + "\x03\x03\x03\x03\x03\x03\x03\x03\x05\x03\x1E\n\x03\x03\x03\x03\x03\x03" + + "\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03" + + "\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03" + + "\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03" + + "\x03\x03\x03\x03\x03\x03\x03\x07\x03A\n\x03\f\x03\x0E\x03D\v\x03\x03\x04" + + "\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x05\x04M\n\x04\x03\x04" + + "\x03\x04\x03\x04\x05\x04R\n\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04" + + "\x05\x04Y\n\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x05\x04`\n\x04" + + "\x03\x04\x03\x04\x05\x04d\n\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04" + + "\x03\x04\x07\x04l\n\x04\f\x04\x0E\x04o\v\x04\x03\x05\x03\x05\x03\x05\x03" + + "\x05\x07\x05u\n\x05\f\x05\x0E\x05x\v\x05\x03\x05\x03\x05\x03\x06\x06\x06" + + "}\n\x06\r\x06\x0E\x06~\x03\x07\x03\x07\x05\x07\x83\n\x07\x03\x07\x03\x07" + + "\x03\x07\x05\x07\x88\n\x07\x07\x07\x8A\n\x07\f\x07\x0E\x07\x8D\v\x07\x03" + + "\b\x03\b\x03\b\x03\b\x03\t\x03\t\x03\t\x07\t\x96\n\t\f\t\x0E\t\x99\v\t" + + "\x03\n\x03\n\x03\n\x03\n\x03\v\x03\v\x03\v\x02\x02\x04\x04\x06\f\x02\x02" + + "\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12\x02\x14\x02\x02" + + "\b\x03\x02\x04\x06\x03\x02\b\n\x03\x02\x04\x05\x03\x02\v\f\x03\x02\x10" + + "\x13\x04\x02\"\"$$\x02\xB6\x02\x16\x03\x02\x02\x02\x04\x1D\x03\x02\x02" + + "\x02\x06X\x03\x02\x02\x02\bp\x03\x02\x02\x02\n|\x03\x02\x02\x02\f\x82" + + "\x03\x02\x02\x02\x0E\x8E\x03\x02\x02\x02\x10\x92\x03\x02\x02\x02\x12\x9A" + + "\x03\x02\x02\x02\x14\x9E\x03\x02\x02\x02\x16\x17\x05\x04\x03\x02\x17\x18" + + "\x07\x02\x02\x03\x18\x03\x03\x02\x02\x02\x19\x1A\b\x03\x01\x02\x1A\x1B" + + "\t\x02\x02\x02\x1B\x1E\x05\x04\x03\x0E\x1C\x1E\x05\x06\x04\x02\x1D\x19" + + "\x03\x02\x02\x02\x1D\x1C\x03\x02\x02\x02\x1EB\x03\x02\x02\x02\x1F \f\r" + + "\x02\x02 !\x07\x07\x02\x02!A\x05\x04\x03\r\"#\f\f\x02\x02#$\t\x03\x02" + + "\x02$A\x05\x04\x03\r%&\f\v\x02\x02&\'\t\x04\x02\x02\'A\x05\x04\x03\f(" + + ")\f\n\x02\x02)*\t\x05\x02\x02*A\x05\x04\x03\v+,\f\t\x02\x02,-\x07\r\x02" + + "\x02-A\x05\x04\x03\n./\f\b\x02\x02/0\t\x06\x02\x020A\x05\x04\x03\t12\f" + + "\x07\x02\x0223\x07\x0E\x02\x023A\x05\x04\x03\b45\f\x06\x02\x0256\x07\x0F" + + "\x02\x026A\x05\x04\x03\x0778\f\x05\x02\x0289\x07\x1E\x02\x029A\x05\x04" + + "\x03\x06:;\f\x04\x02\x02;<\x07\x1F\x02\x02<=\x05\x04\x03\x02=>\x07\x1C" + + "\x02\x02>?\x05\x04\x03\x05?A\x03\x02\x02\x02@\x1F\x03\x02\x02\x02@\"\x03" + + "\x02\x02\x02@%\x03\x02\x02\x02@(\x03\x02\x02\x02@+\x03\x02\x02\x02@.\x03" + + "\x02\x02\x02@1\x03\x02\x02\x02@4\x03\x02\x02\x02@7\x03\x02\x02\x02@:\x03" + + "\x02\x02\x02AD\x03\x02\x02\x02B@\x03\x02\x02\x02BC\x03\x02\x02\x02C\x05" + + "\x03\x02\x02\x02DB\x03\x02\x02\x02EF\b\x04\x01\x02FG\x07\x14\x02\x02G" + + "H\x05\x04\x03\x02HI\x07\x15\x02\x02IY\x03\x02\x02\x02JL\x07\x17\x02\x02" + + "KM\x05\f\x07\x02LK\x03\x02\x02\x02LM\x03\x02\x02\x02MN\x03\x02\x02\x02" + + "NY\x07\x18\x02\x02OQ\x07\x19\x02\x02PR\x05\x10\t\x02QP\x03\x02\x02\x02" + + "QR\x03\x02\x02\x02RS\x03\x02\x02\x02SY\x07\x1A\x02\x02TY\x07 \x02\x02" + + "UY\x07$\x02\x02VY\x07\"\x02\x02WY\x05\b\x05\x02XE\x03\x02\x02\x02XJ\x03" + + "\x02\x02\x02XO\x03\x02\x02\x02XT\x03\x02\x02\x02XU\x03\x02\x02\x02XV\x03" + + "\x02\x02\x02XW\x03\x02\x02\x02Ym\x03\x02\x02\x02Z[\f\x05\x02\x02[\\\x07" + + "\x16\x02\x02\\l\x07\"\x02\x02]_\f\x04\x02\x02^`\x07\x06\x02\x02_^\x03" + + "\x02\x02\x02_`\x03\x02\x02\x02`a\x03\x02\x02\x02ac\x07\x14\x02\x02bd\x05" + + "\f\x07\x02cb\x03\x02\x02\x02cd\x03\x02\x02\x02de\x03\x02\x02\x02el\x07" + + "\x15\x02\x02fg\f\x03\x02\x02gh\x07\x17\x02\x02hi\x05\x04\x03\x02ij\x07" + + "\x18\x02\x02jl\x03\x02\x02\x02kZ\x03\x02\x02\x02k]\x03\x02\x02\x02kf\x03" + + "\x02\x02\x02lo\x03\x02\x02\x02mk\x03\x02\x02\x02mn\x03\x02\x02\x02n\x07" + + "\x03\x02\x02\x02om\x03\x02\x02\x02pv\x07\x03\x02\x02qu\x07\'\x02\x02r" + + "u\x07&\x02\x02su\x05\n\x06\x02tq\x03\x02\x02\x02tr\x03\x02\x02\x02ts\x03" + + "\x02\x02\x02ux\x03\x02\x02\x02vt\x03\x02\x02\x02vw\x03\x02\x02\x02wy\x03" + + "\x02\x02\x02xv\x03\x02\x02\x02yz\x07\x03\x02\x02z\t\x03\x02\x02\x02{}" + + "\x07(\x02\x02|{\x03\x02\x02\x02}~\x03\x02\x02\x02~|\x03\x02\x02\x02~\x7F" + + "\x03\x02\x02\x02\x7F\v\x03\x02\x02\x02\x80\x83\x05\x0E\b\x02\x81\x83\x05" + + "\x04\x03\x02\x82\x80\x03\x02\x02\x02\x82\x81\x03\x02\x02\x02\x83\x8B\x03" + + "\x02\x02\x02\x84\x87\x07\x1B\x02\x02\x85\x88\x05\x0E\b\x02\x86\x88\x05" + + "\x04\x03\x02\x87\x85\x03\x02\x02\x02\x87\x86\x03\x02\x02\x02\x88\x8A\x03" + + "\x02\x02\x02\x89\x84\x03\x02\x02\x02\x8A\x8D\x03\x02\x02\x02\x8B\x89\x03" + + "\x02\x02\x02\x8B\x8C\x03\x02\x02\x02\x8C\r\x03\x02\x02\x02\x8D\x8B\x03" + + "\x02\x02\x02\x8E\x8F\x07\"\x02\x02\x8F\x90\x07\x1D\x02\x02\x90\x91\x05" + + "\x04\x03\x02\x91\x0F\x03\x02\x02\x02\x92\x97\x05\x12\n\x02\x93\x94\x07" + + "\x1B\x02\x02\x94\x96\x05\x12\n\x02\x95\x93\x03\x02\x02\x02\x96\x99\x03" + + "\x02\x02\x02\x97\x95\x03\x02\x02\x02\x97\x98\x03\x02\x02\x02\x98\x11\x03" + + "\x02\x02\x02\x99\x97\x03\x02\x02\x02\x9A\x9B\x05\x14\v\x02\x9B\x9C\x07" + + "\x1C\x02\x02\x9C\x9D\x05\x04\x03\x02\x9D\x13\x03\x02\x02\x02\x9E\x9F\t" + + "\x07\x02\x02\x9F\x15\x03\x02\x02\x02\x13\x1D@BLQX_ckmtv~\x82\x87\x8B\x97"; + class FileContext extends ParserRuleContext_1.ParserRuleContext { + expression() { + return this.getRuleContext(0, ExpressionContext); + } + EOF() { return this.getToken(ExpressionAntlrParser$1.EOF, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_file; } + // @Override + enterRule(listener) { + if (listener.enterFile) { + listener.enterFile(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitFile) { + listener.exitFile(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitFile) { + return visitor.visitFile(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.FileContext = FileContext; + class ExpressionContext extends ParserRuleContext_1.ParserRuleContext { + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_expression; } + copyFrom(ctx) { + super.copyFrom(ctx); + } + } + ExpressionAntlrParser.ExpressionContext = ExpressionContext; + class UnaryOpExpContext extends ExpressionContext { + expression() { + return this.getRuleContext(0, ExpressionContext); + } + NON() { return this.tryGetToken(ExpressionAntlrParser$1.NON, 0); } + SUBSTRACT() { return this.tryGetToken(ExpressionAntlrParser$1.SUBSTRACT, 0); } + PLUS() { return this.tryGetToken(ExpressionAntlrParser$1.PLUS, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterUnaryOpExp) { + listener.enterUnaryOpExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitUnaryOpExp) { + listener.exitUnaryOpExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitUnaryOpExp) { + return visitor.visitUnaryOpExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.UnaryOpExpContext = UnaryOpExpContext; + class BinaryOpExpContext extends ExpressionContext { + expression(i) { + if (i === undefined) { + return this.getRuleContexts(ExpressionContext); + } + else { + return this.getRuleContext(i, ExpressionContext); + } + } + XOR() { return this.tryGetToken(ExpressionAntlrParser$1.XOR, 0); } + ASTERISK() { return this.tryGetToken(ExpressionAntlrParser$1.ASTERISK, 0); } + SLASH() { return this.tryGetToken(ExpressionAntlrParser$1.SLASH, 0); } + PERCENT() { return this.tryGetToken(ExpressionAntlrParser$1.PERCENT, 0); } + PLUS() { return this.tryGetToken(ExpressionAntlrParser$1.PLUS, 0); } + SUBSTRACT() { return this.tryGetToken(ExpressionAntlrParser$1.SUBSTRACT, 0); } + DOUBLE_EQUAL() { return this.tryGetToken(ExpressionAntlrParser$1.DOUBLE_EQUAL, 0); } + NOT_EQUAL() { return this.tryGetToken(ExpressionAntlrParser$1.NOT_EQUAL, 0); } + SINGLE_AND() { return this.tryGetToken(ExpressionAntlrParser$1.SINGLE_AND, 0); } + LESS_THAN() { return this.tryGetToken(ExpressionAntlrParser$1.LESS_THAN, 0); } + LESS_OR_EQUAl() { return this.tryGetToken(ExpressionAntlrParser$1.LESS_OR_EQUAl, 0); } + MORE_THAN() { return this.tryGetToken(ExpressionAntlrParser$1.MORE_THAN, 0); } + MORE_OR_EQUAL() { return this.tryGetToken(ExpressionAntlrParser$1.MORE_OR_EQUAL, 0); } + DOUBLE_AND() { return this.tryGetToken(ExpressionAntlrParser$1.DOUBLE_AND, 0); } + DOUBLE_VERTICAL_CYLINDER() { return this.tryGetToken(ExpressionAntlrParser$1.DOUBLE_VERTICAL_CYLINDER, 0); } + NULL_COALESCE() { return this.tryGetToken(ExpressionAntlrParser$1.NULL_COALESCE, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterBinaryOpExp) { + listener.enterBinaryOpExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitBinaryOpExp) { + listener.exitBinaryOpExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitBinaryOpExp) { + return visitor.visitBinaryOpExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.BinaryOpExpContext = BinaryOpExpContext; + class TripleOpExpContext extends ExpressionContext { + expression(i) { + if (i === undefined) { + return this.getRuleContexts(ExpressionContext); + } + else { + return this.getRuleContext(i, ExpressionContext); + } + } + QUESTION_MARK() { return this.getToken(ExpressionAntlrParser$1.QUESTION_MARK, 0); } + COLON() { return this.getToken(ExpressionAntlrParser$1.COLON, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterTripleOpExp) { + listener.enterTripleOpExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitTripleOpExp) { + listener.exitTripleOpExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitTripleOpExp) { + return visitor.visitTripleOpExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.TripleOpExpContext = TripleOpExpContext; + class PrimaryExpContext extends ExpressionContext { + primaryExpression() { + return this.getRuleContext(0, PrimaryExpressionContext); + } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterPrimaryExp) { + listener.enterPrimaryExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitPrimaryExp) { + listener.exitPrimaryExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitPrimaryExp) { + return visitor.visitPrimaryExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.PrimaryExpContext = PrimaryExpContext; + class PrimaryExpressionContext extends ParserRuleContext_1.ParserRuleContext { + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_primaryExpression; } + copyFrom(ctx) { + super.copyFrom(ctx); + } + } + ExpressionAntlrParser.PrimaryExpressionContext = PrimaryExpressionContext; + class ParenthesisExpContext extends PrimaryExpressionContext { + OPEN_BRACKET() { return this.getToken(ExpressionAntlrParser$1.OPEN_BRACKET, 0); } + expression() { + return this.getRuleContext(0, ExpressionContext); + } + CLOSE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.CLOSE_BRACKET, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterParenthesisExp) { + listener.enterParenthesisExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitParenthesisExp) { + listener.exitParenthesisExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitParenthesisExp) { + return visitor.visitParenthesisExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.ParenthesisExpContext = ParenthesisExpContext; + class ArrayCreationExpContext extends PrimaryExpressionContext { + OPEN_SQUARE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.OPEN_SQUARE_BRACKET, 0); } + CLOSE_SQUARE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.CLOSE_SQUARE_BRACKET, 0); } + argsList() { + return this.tryGetRuleContext(0, ArgsListContext); + } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterArrayCreationExp) { + listener.enterArrayCreationExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitArrayCreationExp) { + listener.exitArrayCreationExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitArrayCreationExp) { + return visitor.visitArrayCreationExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.ArrayCreationExpContext = ArrayCreationExpContext; + class JsonCreationExpContext extends PrimaryExpressionContext { + OPEN_CURLY_BRACKET() { return this.getToken(ExpressionAntlrParser$1.OPEN_CURLY_BRACKET, 0); } + CLOSE_CURLY_BRACKET() { return this.getToken(ExpressionAntlrParser$1.CLOSE_CURLY_BRACKET, 0); } + keyValuePairList() { + return this.tryGetRuleContext(0, KeyValuePairListContext); + } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterJsonCreationExp) { + listener.enterJsonCreationExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitJsonCreationExp) { + listener.exitJsonCreationExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitJsonCreationExp) { + return visitor.visitJsonCreationExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.JsonCreationExpContext = JsonCreationExpContext; + class NumericAtomContext extends PrimaryExpressionContext { + NUMBER() { return this.getToken(ExpressionAntlrParser$1.NUMBER, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterNumericAtom) { + listener.enterNumericAtom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitNumericAtom) { + listener.exitNumericAtom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitNumericAtom) { + return visitor.visitNumericAtom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.NumericAtomContext = NumericAtomContext; + class StringAtomContext extends PrimaryExpressionContext { + STRING() { return this.getToken(ExpressionAntlrParser$1.STRING, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterStringAtom) { + listener.enterStringAtom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitStringAtom) { + listener.exitStringAtom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitStringAtom) { + return visitor.visitStringAtom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.StringAtomContext = StringAtomContext; + class IdAtomContext extends PrimaryExpressionContext { + IDENTIFIER() { return this.getToken(ExpressionAntlrParser$1.IDENTIFIER, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterIdAtom) { + listener.enterIdAtom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitIdAtom) { + listener.exitIdAtom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitIdAtom) { + return visitor.visitIdAtom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.IdAtomContext = IdAtomContext; + class StringInterpolationAtomContext extends PrimaryExpressionContext { + stringInterpolation() { + return this.getRuleContext(0, StringInterpolationContext); + } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterStringInterpolationAtom) { + listener.enterStringInterpolationAtom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitStringInterpolationAtom) { + listener.exitStringInterpolationAtom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitStringInterpolationAtom) { + return visitor.visitStringInterpolationAtom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.StringInterpolationAtomContext = StringInterpolationAtomContext; + class MemberAccessExpContext extends PrimaryExpressionContext { + primaryExpression() { + return this.getRuleContext(0, PrimaryExpressionContext); + } + DOT() { return this.getToken(ExpressionAntlrParser$1.DOT, 0); } + IDENTIFIER() { return this.getToken(ExpressionAntlrParser$1.IDENTIFIER, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterMemberAccessExp) { + listener.enterMemberAccessExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitMemberAccessExp) { + listener.exitMemberAccessExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitMemberAccessExp) { + return visitor.visitMemberAccessExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.MemberAccessExpContext = MemberAccessExpContext; + class FuncInvokeExpContext extends PrimaryExpressionContext { + primaryExpression() { + return this.getRuleContext(0, PrimaryExpressionContext); + } + OPEN_BRACKET() { return this.getToken(ExpressionAntlrParser$1.OPEN_BRACKET, 0); } + CLOSE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.CLOSE_BRACKET, 0); } + NON() { return this.tryGetToken(ExpressionAntlrParser$1.NON, 0); } + argsList() { + return this.tryGetRuleContext(0, ArgsListContext); + } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterFuncInvokeExp) { + listener.enterFuncInvokeExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitFuncInvokeExp) { + listener.exitFuncInvokeExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitFuncInvokeExp) { + return visitor.visitFuncInvokeExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.FuncInvokeExpContext = FuncInvokeExpContext; + class IndexAccessExpContext extends PrimaryExpressionContext { + primaryExpression() { + return this.getRuleContext(0, PrimaryExpressionContext); + } + OPEN_SQUARE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.OPEN_SQUARE_BRACKET, 0); } + expression() { + return this.getRuleContext(0, ExpressionContext); + } + CLOSE_SQUARE_BRACKET() { return this.getToken(ExpressionAntlrParser$1.CLOSE_SQUARE_BRACKET, 0); } + constructor(ctx) { + super(ctx.parent, ctx.invokingState); + this.copyFrom(ctx); + } + // @Override + enterRule(listener) { + if (listener.enterIndexAccessExp) { + listener.enterIndexAccessExp(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitIndexAccessExp) { + listener.exitIndexAccessExp(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitIndexAccessExp) { + return visitor.visitIndexAccessExp(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.IndexAccessExpContext = IndexAccessExpContext; + class StringInterpolationContext extends ParserRuleContext_1.ParserRuleContext { + STRING_INTERPOLATION_START(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.STRING_INTERPOLATION_START); + } + else { + return this.getToken(ExpressionAntlrParser$1.STRING_INTERPOLATION_START, i); + } + } + ESCAPE_CHARACTER(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.ESCAPE_CHARACTER); + } + else { + return this.getToken(ExpressionAntlrParser$1.ESCAPE_CHARACTER, i); + } + } + TEMPLATE(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.TEMPLATE); + } + else { + return this.getToken(ExpressionAntlrParser$1.TEMPLATE, i); + } + } + textContent(i) { + if (i === undefined) { + return this.getRuleContexts(TextContentContext); + } + else { + return this.getRuleContext(i, TextContentContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_stringInterpolation; } + // @Override + enterRule(listener) { + if (listener.enterStringInterpolation) { + listener.enterStringInterpolation(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitStringInterpolation) { + listener.exitStringInterpolation(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitStringInterpolation) { + return visitor.visitStringInterpolation(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.StringInterpolationContext = StringInterpolationContext; + class TextContentContext extends ParserRuleContext_1.ParserRuleContext { + TEXT_CONTENT(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.TEXT_CONTENT); + } + else { + return this.getToken(ExpressionAntlrParser$1.TEXT_CONTENT, i); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_textContent; } + // @Override + enterRule(listener) { + if (listener.enterTextContent) { + listener.enterTextContent(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitTextContent) { + listener.exitTextContent(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitTextContent) { + return visitor.visitTextContent(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.TextContentContext = TextContentContext; + class ArgsListContext extends ParserRuleContext_1.ParserRuleContext { + lambda(i) { + if (i === undefined) { + return this.getRuleContexts(LambdaContext); + } + else { + return this.getRuleContext(i, LambdaContext); + } + } + expression(i) { + if (i === undefined) { + return this.getRuleContexts(ExpressionContext); + } + else { + return this.getRuleContext(i, ExpressionContext); + } + } + COMMA(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.COMMA); + } + else { + return this.getToken(ExpressionAntlrParser$1.COMMA, i); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_argsList; } + // @Override + enterRule(listener) { + if (listener.enterArgsList) { + listener.enterArgsList(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitArgsList) { + listener.exitArgsList(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitArgsList) { + return visitor.visitArgsList(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.ArgsListContext = ArgsListContext; + class LambdaContext extends ParserRuleContext_1.ParserRuleContext { + IDENTIFIER() { return this.getToken(ExpressionAntlrParser$1.IDENTIFIER, 0); } + ARROW() { return this.getToken(ExpressionAntlrParser$1.ARROW, 0); } + expression() { + return this.getRuleContext(0, ExpressionContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_lambda; } + // @Override + enterRule(listener) { + if (listener.enterLambda) { + listener.enterLambda(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitLambda) { + listener.exitLambda(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitLambda) { + return visitor.visitLambda(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.LambdaContext = LambdaContext; + class KeyValuePairListContext extends ParserRuleContext_1.ParserRuleContext { + keyValuePair(i) { + if (i === undefined) { + return this.getRuleContexts(KeyValuePairContext); + } + else { + return this.getRuleContext(i, KeyValuePairContext); + } + } + COMMA(i) { + if (i === undefined) { + return this.getTokens(ExpressionAntlrParser$1.COMMA); + } + else { + return this.getToken(ExpressionAntlrParser$1.COMMA, i); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_keyValuePairList; } + // @Override + enterRule(listener) { + if (listener.enterKeyValuePairList) { + listener.enterKeyValuePairList(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitKeyValuePairList) { + listener.exitKeyValuePairList(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitKeyValuePairList) { + return visitor.visitKeyValuePairList(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.KeyValuePairListContext = KeyValuePairListContext; + class KeyValuePairContext extends ParserRuleContext_1.ParserRuleContext { + key() { + return this.getRuleContext(0, KeyContext); + } + COLON() { return this.getToken(ExpressionAntlrParser$1.COLON, 0); } + expression() { + return this.getRuleContext(0, ExpressionContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_keyValuePair; } + // @Override + enterRule(listener) { + if (listener.enterKeyValuePair) { + listener.enterKeyValuePair(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitKeyValuePair) { + listener.exitKeyValuePair(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitKeyValuePair) { + return visitor.visitKeyValuePair(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.KeyValuePairContext = KeyValuePairContext; + class KeyContext extends ParserRuleContext_1.ParserRuleContext { + IDENTIFIER() { return this.tryGetToken(ExpressionAntlrParser$1.IDENTIFIER, 0); } + STRING() { return this.tryGetToken(ExpressionAntlrParser$1.STRING, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return ExpressionAntlrParser$1.RULE_key; } + // @Override + enterRule(listener) { + if (listener.enterKey) { + listener.enterKey(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitKey) { + listener.exitKey(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitKey) { + return visitor.visitKey(this); + } + else { + return visitor.visitChildren(this); + } + } + } + ExpressionAntlrParser.KeyContext = KeyContext; + + return ExpressionAntlrParser; +} + +var ExpressionAntlrParserVisitor = {}; + +var hasRequiredExpressionAntlrParserVisitor; + +function requireExpressionAntlrParserVisitor () { + if (hasRequiredExpressionAntlrParserVisitor) return ExpressionAntlrParserVisitor; + hasRequiredExpressionAntlrParserVisitor = 1; + // Generated from src/parser/ExpressionAntlrParser.g4 by ANTLR 4.7.3-SNAPSHOT + Object.defineProperty(ExpressionAntlrParserVisitor, "__esModule", { value: true }); + + return ExpressionAntlrParserVisitor; +} + +var hasRequiredGenerated$1; + +function requireGenerated$1 () { + if (hasRequiredGenerated$1) return generated$1; + hasRequiredGenerated$1 = 1; + (function (exports) { + var __createBinding = (generated$1 && generated$1.__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 = (generated$1 && generated$1.__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 }); + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + __exportStar(requireExpressionAntlrLexer(), exports); + __exportStar(requireExpressionAntlrParserListener(), exports); + __exportStar(requireExpressionAntlrParser(), exports); + __exportStar(requireExpressionAntlrParserVisitor(), exports); + + } (generated$1)); + return generated$1; +} + +var hasRequiredExpressionParser; + +function requireExpressionParser () { + if (hasRequiredExpressionParser) return expressionParser; + hasRequiredExpressionParser = 1; + var __createBinding = (expressionParser && expressionParser.__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 = (expressionParser && expressionParser.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (expressionParser && expressionParser.__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(expressionParser, "__esModule", { value: true }); + expressionParser.ExpressionParser = void 0; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + const antlr4ts_1 = requireAntlr4ts(); + const tree_1 = requireTree(); + const constant_1 = requireConstant(); + const expression_1 = requireExpression(); + const expressionType_1 = requireExpressionType(); + const generated_1 = requireGenerated$1(); + const ep = __importStar(requireExpressionAntlrParser()); + const parseErrorListener_1 = requireParseErrorListener(); + const functionUtils_1 = requireFunctionUtils(); + /** + * Parser to turn strings into Expression + */ + class ExpressionParser { + /** + * Initializes a new instance of the [ExpressionParser](xref:adaptive-expressions.ExpressionParser) class. + * + * @param lookup [EvaluatorLookup](xref:adaptive-expressions.EvaluatorLookup) for information from type string. + */ + constructor(lookup) { + this.ExpressionTransformer = class extends tree_1.AbstractParseTreeVisitor { + constructor(lookup) { + super(); + this.escapeRegex = new RegExp(/\\[^\r\n]?/g); + this._lookupFunction = undefined; + this.transform = (context) => this.visit(context); + this.visitParenthesisExp = (context) => this.visit(context.expression()); + this.defaultResult = () => new constant_1.Constant(''); + this.makeExpression = (functionType, ...children) => { + if (!this._lookupFunction(functionType)) { + throw new Error(`${functionType} does not have an evaluator, it's not a built-in function or a custom function.`); + } + return expression_1.Expression.makeExpression(functionType, this._lookupFunction(functionType), ...children); + }; + this._lookupFunction = lookup; + } + visitUnaryOpExp(context) { + const unaryOperationName = context.getChild(0).text; + const operand = this.visit(context.expression()); + if (unaryOperationName === expressionType_1.ExpressionType.Subtract || unaryOperationName === expressionType_1.ExpressionType.Add) { + return this.makeExpression(unaryOperationName, new constant_1.Constant(0), operand); + } + return this.makeExpression(unaryOperationName, operand); + } + visitBinaryOpExp(context) { + const binaryOperationName = context.getChild(1).text; + const left = this.visit(context.expression(0)); + const right = this.visit(context.expression(1)); + return this.makeExpression(binaryOperationName, left, right); + } + visitTripleOpExp(context) { + const conditionalExpression = this.visit(context.expression(0)); + const left = this.visit(context.expression(1)); + const right = this.visit(context.expression(2)); + return this.makeExpression(expressionType_1.ExpressionType.If, conditionalExpression, left, right); + } + visitFuncInvokeExp(context) { + const parameters = this.processArgsList(context.argsList()); + // Remove the check to check primaryExpression is just an IDENTIFIER to support "." in template name + let functionName = context.primaryExpression().text; + if (context.NON() !== undefined) { + functionName += context.NON().text; + } + return this.makeExpression(functionName, ...parameters); + } + visitIdAtom(context) { + let result; + const symbol = context.text; + if (symbol === 'false') { + result = new constant_1.Constant(false); + } + else if (symbol === 'true') { + result = new constant_1.Constant(true); + } + else if (symbol === 'null') { + result = new constant_1.Constant(null); + } + else if (symbol === 'undefined') { + result = new constant_1.Constant(undefined); + } + else { + result = this.makeExpression(expressionType_1.ExpressionType.Accessor, new constant_1.Constant(symbol)); + } + return result; + } + visitIndexAccessExp(context) { + const property = this.visit(context.expression()); + const instance = this.visit(context.primaryExpression()); + return this.makeExpression(expressionType_1.ExpressionType.Element, instance, property); + } + visitMemberAccessExp(context) { + const property = context.IDENTIFIER().text; + const instance = this.visit(context.primaryExpression()); + return this.makeExpression(expressionType_1.ExpressionType.Accessor, new constant_1.Constant(property), instance); + } + visitNumericAtom(context) { + const numberValue = parseFloat(context.text); + if (functionUtils_1.FunctionUtils.isNumber(numberValue)) { + return new constant_1.Constant(numberValue); + } + throw new Error(`${context.text} is not a number.`); + } + visitArrayCreationExp(context) { + const parameters = this.processArgsList(context.argsList()); + return this.makeExpression(expressionType_1.ExpressionType.CreateArray, ...parameters); + } + visitStringAtom(context) { + let text = context.text; + if (text.startsWith("'") && text.endsWith("'")) { + text = text.substr(1, text.length - 2).replace(/\\'/g, "'"); + } + else if (text.startsWith('"') && text.endsWith('"')) { + // start with "" + text = text.substr(1, text.length - 2).replace(/\\"/g, '"'); + } + else { + throw new Error(`Invalid string ${text}`); + } + return new constant_1.Constant(this.evalEscape(text)); + } + visitJsonCreationExp(context) { + let expr = this.makeExpression(expressionType_1.ExpressionType.Json, new constant_1.Constant('{}')); + if (context.keyValuePairList()) { + for (const kvPair of context.keyValuePairList().keyValuePair()) { + let key = ''; + const keyNode = kvPair.key().children[0]; + if (keyNode instanceof tree_1.TerminalNode) { + if (keyNode.symbol.type === ep.ExpressionAntlrParser.IDENTIFIER) { + key = keyNode.text; + } + else { + key = keyNode.text.substring(1, keyNode.text.length - 1); + } + } + expr = this.makeExpression(expressionType_1.ExpressionType.SetProperty, expr, new constant_1.Constant(key), this.visit(kvPair.expression())); + } + } + return expr; + } + visitStringInterpolationAtom(context) { + const children = [new constant_1.Constant('')]; + for (const node of context.stringInterpolation().children) { + if (node instanceof tree_1.TerminalNode) { + switch (node.symbol.type) { + case ep.ExpressionAntlrParser.TEMPLATE: { + const expressionString = this.trimExpression(node.text); + children.push(expression_1.Expression.parse(expressionString, this._lookupFunction)); + break; + } + case ep.ExpressionAntlrParser.ESCAPE_CHARACTER: { + children.push(new constant_1.Constant(node.text.replace(/\\`/g, '`').replace(/\\\$/g, '$'))); + break; + } + } + } + else { + children.push(new constant_1.Constant(node.text)); + } + } + return this.makeExpression(expressionType_1.ExpressionType.Concat, ...children); + } + processArgsList(context) { + const result = []; + if (!context) { + return result; + } + for (const child of context.children) { + if (child instanceof ep.LambdaContext) { + const evalParam = this.makeExpression(expressionType_1.ExpressionType.Accessor, new constant_1.Constant(child.IDENTIFIER().text)); + const evalFun = this.visit(child.expression()); + result.push(evalParam); + result.push(evalFun); + } + else if (child instanceof ep.ExpressionContext) { + result.push(this.visit(child)); + } + } + return result; + } + trimExpression(expression) { + let result = expression.trim(); + if (result.startsWith('$')) { + result = result.substr(1); + } + result = result.trim(); + if (result.startsWith('{') && result.endsWith('}')) { + result = result.substr(1, result.length - 2); + } + return result.trim(); + } + evalEscape(text) { + const validCharactersDict = { + '\\r': '\r', + '\\n': '\n', + '\\t': '\t', + '\\\\': '\\', + }; + return text.replace(this.escapeRegex, (sub) => { + if (sub in validCharactersDict) { + return validCharactersDict[sub]; + } + else { + return sub; + } + }); + } + }; + this.EvaluatorLookup = lookup || expression_1.Expression.lookup; + } + /** + * @protected + * Parse the expression to ANTLR lexer and parser. + * @param expression The input string expression. + * @returns A ParseTree. + */ + static antlrParse(expression) { + if (ExpressionParser.expressionDict.has({ key: expression })) { + return ExpressionParser.expressionDict.get({ key: expression }); + } + const inputStream = new antlr4ts_1.ANTLRInputStream(expression); + const lexer = new generated_1.ExpressionAntlrLexer(inputStream); + lexer.removeErrorListeners(); + const tokenStream = new antlr4ts_1.CommonTokenStream(lexer); + const parser = new generated_1.ExpressionAntlrParser(tokenStream); + parser.removeErrorListeners(); + parser.addErrorListener(parseErrorListener_1.ParseErrorListener.Instance); + parser.buildParseTree = true; + let expressionContext; + const file = parser.file(); + if (file !== undefined) { + expressionContext = file.expression(); + } + ExpressionParser.expressionDict.set({ key: expression }, expressionContext); + return expressionContext; + } + /** + * Parse the input into an expression. + * + * @param expression Expression to parse. + * @returns Expression tree. + */ + parse(expression) { + if (expression == null || expression === '') { + return new constant_1.Constant(''); + } + else { + return new this.ExpressionTransformer(this.EvaluatorLookup).transform(ExpressionParser.antlrParse(expression)); + } + } + } + expressionParser.ExpressionParser = ExpressionParser; + ExpressionParser.expressionDict = new WeakMap(); + + return expressionParser; +} + +var util$1 = {}; + +var hasRequiredUtil$1; + +function requireUtil$1 () { + if (hasRequiredUtil$1) return util$1; + hasRequiredUtil$1 = 1; + Object.defineProperty(util$1, "__esModule", { value: true }); + util$1.Util = void 0; + /* eslint-disable security/detect-non-literal-regexp */ + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + /** + * util class + */ + class Util { + /** + * trim char. + * + * @param str input string. + * @param char trim character. + * @returns The trimmed char. + */ + static trim(str, char) { + if (char !== undefined) { + return str.replace(new RegExp(''.concat('^\\', char, '+|\\', char, '+$'), 'g'), ''); + } + return str.trim(); + } + } + util$1.Util = Util; + + return util$1; +} + +var hasRequiredParser; + +function requireParser () { + if (hasRequiredParser) return parser; + hasRequiredParser = 1; + (function (exports) { + var __createBinding = (parser && parser.__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 = (parser && parser.__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 }); + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + __exportStar(requireParseErrorListener(), exports); + __exportStar(requireExpressionParser(), exports); + __exportStar(requireUtil$1(), exports); + __exportStar(requireGenerated$1(), exports); + + } (parser)); + return parser; +} + +var hasRequiredExpression; + +function requireExpression () { + if (hasRequiredExpression) return expression; + hasRequiredExpression = 1; + Object.defineProperty(expression, "__esModule", { value: true }); + expression.Expression = void 0; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + const constant_1 = requireConstant(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const extensions_1 = requireExtensions(); + const functionTable_1 = requireFunctionTable(); + const memory_1 = requireMemory(); + const options_1 = requireOptions(); + const parser_1 = requireParser(); + const returnType_1 = requireReturnType(); + /** + * An expression which can be analyzed or evaluated to produce a value. + * This provides an open-ended wrapper that supports a number of built-in functions and can also be extended at runtime. + * It also supports validation of the correctness of an expression and evaluation that should be exception free. + */ + class Expression { + /** + * expression constructor. + * + * @param type Type of expression from ExpressionType + * @param evaluator Information about how to validate and evaluate expression. + * @param children Child expressions. + */ + constructor(type, evaluator, ...children) { + /** + * Validate immediate expression. + * + * @returns The validated expression. + */ + this.validate = () => this.evaluator.validateExpression(this); + if (evaluator) { + this.evaluator = evaluator; + this.children = children; + } + else if (type !== undefined) { + if (!Expression.functions.get(type)) { + throw Error(`${type} does not have an evaluator, it's not a built-in function or a custom function.`); + } + this.evaluator = Expression.functions.get(type); + this.children = children; + } + } + /** + * Expected result of evaluating the expression. + * + * @returns The expected result of evaluating the expression. + */ + get returnType() { + return this.evaluator.returnType; + } + /** + * Type of expression. + * + * @returns The type of the expression. + */ + get type() { + return this.evaluator.type; + } + /** + * Do a deep equality between expressions. + * + * @param other Other expression. + * @returns True if expressions are the same. + */ + deepEquals(other) { + let eq = false; + if (other) { + eq = this.type === other.type; + if (eq) { + eq = this.children.length === other.children.length; + if (this.type === expressionType_1.ExpressionType.And || this.type === expressionType_1.ExpressionType.Or) { + // And/Or do not depand on order + for (let i = 0; eq && i < this.children.length; i++) { + const primary = this.children[0]; + let found = false; + for (let j = 0; j < this.children.length; j++) { + if (primary.deepEquals(other.children[j])) { + found = true; + break; + } + } + eq = found; + } + } + else { + for (let i = 0; eq && i < this.children.length; i++) { + eq = this.children[i].deepEquals(other.children[i]); + } + } + } + } + return eq; + } + /** + * Return the static reference paths to memory. + * Return all static paths to memory. If there is a computed element index, then the path is terminated there, + * but you might get other paths from the computed part as well. + * + * @returns List of the static reference paths. + */ + references() { + const { path, refs } = this.referenceWalk(this); + if (path !== undefined) { + refs.add(path); + } + return Array.from(refs); + } + /** + * Walking function for identifying static memory references in an expression. + * + * @param expression Expression to analyze. + * @param extension If present, called to override lookup for things like template expansion. + * @returns Accessor path of expression. + */ + referenceWalk(expression, extension) { + let path; + let refs = new Set(); + if (extension === undefined || !extension(expression)) { + const children = expression.children; + if (expression.type === expressionType_1.ExpressionType.Accessor) { + const prop = children[0].value; + if (children.length === 1) { + path = prop; + } + if (children.length === 2) { + ({ path, refs } = this.referenceWalk(children[1], extension)); + if (path !== undefined) { + path = path.concat('.', prop); + } + // if path is null we still keep it null, won't append prop + // because for example, first(items).x should not return x as refs + } + } + else if (expression.type === expressionType_1.ExpressionType.Element) { + ({ path, refs } = this.referenceWalk(children[0], extension)); + if (path !== undefined) { + if (children[1] instanceof constant_1.Constant) { + const cnst = children[1]; + if (cnst.returnType === returnType_1.ReturnType.String) { + path += `.${cnst.value}`; + } + else { + path += `[${cnst.value}]`; + } + } + else { + refs.add(path); + } + } + const result = this.referenceWalk(children[1], extension); + const idxPath = result.path; + const refs1 = result.refs; + refs = new Set([...refs, ...refs1]); + if (idxPath !== undefined) { + refs.add(idxPath); + } + } + else if (expression.type === expressionType_1.ExpressionType.Foreach || + expression.type === expressionType_1.ExpressionType.Where || + expression.type === expressionType_1.ExpressionType.Select) { + let result = this.referenceWalk(children[0], extension); + const child0Path = result.path; + const refs0 = result.refs; + if (child0Path !== undefined) { + refs0.add(child0Path); + } + result = this.referenceWalk(children[2], extension); + const child2Path = result.path; + const refs2 = result.refs; + if (child2Path !== undefined) { + refs2.add(child2Path); + } + const iteratorName = children[1].children[0].value; + const nonLocalRefs2 = Array.from(refs2).filter((x) => !(x === iteratorName || x.startsWith(iteratorName + '.') || x.startsWith(iteratorName + '['))); + refs = new Set([...refs, ...refs0, ...nonLocalRefs2]); + } + else { + for (const child of expression.children) { + const result = this.referenceWalk(child, extension); + const childPath = result.path; + const refs0 = result.refs; + refs = new Set([...refs, ...refs0]); + if (childPath !== undefined) { + refs.add(childPath); + } + } + } + } + return { path, refs }; + } + /** + * Parse an expression string into an [Expression](xref:adaptive-expressions.Expression) object. + * + * @param expression Expression string. + * @param lookup Optional. [EvaluatorLookup](xref:adaptive-expressions.EvaluatorLookup) function lookup when parsing the expression. Default is [Expression.lookup](xref:adaptive-expressions.Expression.lookup) which uses [Expression.functions](xref:adaptive-expressions.Expression.functions) table. + * @returns The expression object. + */ + static parse(expression, lookup) { + return new parser_1.ExpressionParser(lookup || Expression.lookup).parse(expression.replace(/^=/, '')); + } + /** + * Lookup an [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) function by name. + * + * @param functionName Name of function to lookup. + * @returns An [ExpressionEvaluator](xref:adaptive-expressions.ExpressionEvaluator) corresponding to the function name. + */ + static lookup(functionName) { + const exprEvaluator = Expression.functions.get(functionName); + if (!exprEvaluator) { + return undefined; + } + return exprEvaluator; + } + /** + * Make an expression and validate it. + * + * @param type Type of expression from ExpressionType. + * @param evaluator Information about how to validate and evaluate expression. + * @param children Child expressions. + * @returns The new expression. + */ + static makeExpression(type, evaluator, ...children) { + const expr = new Expression(type, evaluator, ...children); + expr.validate(); + return expr; + } + /** + * Construct an expression from a EvaluateExpressionDelegate + * + * @param func Function to create an expression from. + * @returns The new expression. + */ + static lambaExpression(func) { + return new Expression(expressionType_1.ExpressionType.Lambda, new expressionEvaluator_1.ExpressionEvaluator(expressionType_1.ExpressionType.Lambda, func)); + } + /** + * Construct an expression from a lamba expression over the state. + * Exceptions will be caught and surfaced as an error string. + * + * @param func ambda expression to evaluate. + * @returns New expression. + */ + static lambda(func) { + return new Expression(expressionType_1.ExpressionType.Lambda, new expressionEvaluator_1.ExpressionEvaluator(expressionType_1.ExpressionType.Lambda, (_expression, state, _) => { + let value; + let error; + try { + value = func(state); + } + catch (funcError) { + error = funcError; + } + return { value, error }; + })); + } + /** + * Construct and validate an Set a property expression to a value expression. + * + * @param property property expression. + * @param value value expression. + * @returns New expression. + */ + static setPathToValue(property, value) { + if (value instanceof Expression) { + return Expression.makeExpression(expressionType_1.ExpressionType.SetPathToValue, undefined, property, value); + } + else { + return Expression.makeExpression(expressionType_1.ExpressionType.SetPathToValue, undefined, property, new constant_1.Constant(value)); + } + } + /** + * Construct and validate an Equals expression. + * + * @param children Child clauses. + * @returns New expression. + */ + static equalsExpression(...children) { + return Expression.makeExpression(expressionType_1.ExpressionType.Equal, undefined, ...children); + } + /** + * Construct and validate an And expression. + * + * @param children Child clauses. + * @returns New expression. + */ + static andExpression(...children) { + if (children.length > 1) { + return Expression.makeExpression(expressionType_1.ExpressionType.And, undefined, ...children); + } + else { + return children[0]; + } + } + /** + * Construct and validate an Or expression. + * + * @param children Child clauses. + * @returns New expression. + */ + static orExpression(...children) { + if (children.length > 1) { + return Expression.makeExpression(expressionType_1.ExpressionType.Or, undefined, ...children); + } + else { + return children[0]; + } + } + /** + * Construct and validate an Not expression. + * + * @param child Child clauses. + * @returns New expression. + */ + static notExpression(child) { + return Expression.makeExpression(expressionType_1.ExpressionType.Not, undefined, child); + } + /** + * Recursively validate the expression tree. + */ + validateTree() { + this.validate(); + for (const child of this.children) { + child.validateTree(); + } + } + /** + * Evaluate the expression. + * + * @param state Global state to evaluate accessor expressions against. Can be Dictionary, otherwise reflection is used to access property and then indexer. + * @param options Options used in the evaluation. + * @returns Computed value and an error string. If the string is non-null, then there was an evaluation error. + */ + tryEvaluate(state, options = undefined) { + if (!extensions_1.Extensions.isMemoryInterface(state)) { + state = memory_1.SimpleObjectMemory.wrap(state); + } + options = options ? options : new options_1.Options(); + return this.evaluator.tryEvaluate(this, state, options); + } + /** + * Returns a string that represents the current [Expression](xref:adaptive-expressions.Expression) object. + * + * @returns A string that represents the current [Expression](xref:adaptive-expressions.Expression) object. + */ + toString() { + let builder = ''; + let valid = false; + // Special support for memory paths + if (this.type === expressionType_1.ExpressionType.Accessor && this.children.length >= 1) { + if (this.children[0] instanceof constant_1.Constant) { + const prop = this.children[0].value; + if (typeof prop === 'string') { + if (this.children.length === 1) { + valid = true; + builder = builder.concat(prop); + } + else if (this.children.length === 2) { + valid = true; + builder = builder.concat(this.children[1].toString(), '.', prop); + } + } + } + } + else if (this.type === expressionType_1.ExpressionType.Element && this.children.length === 2) { + valid = true; + builder = builder.concat(this.children[0].toString(), '[', this.children[1].toString(), ']'); + } + if (!valid) { + const infix = this.type.length > 0 && !new RegExp(/[a-z]/i).test(this.type[0]) && this.children.length >= 2; + if (!infix) { + builder = builder.concat(this.type); + } + builder = builder.concat('('); + let first = true; + for (const child of this.children) { + if (first) { + first = false; + } + else { + if (infix) { + builder = builder.concat(' ', this.type, ' '); + } + else { + builder = builder.concat(', '); + } + } + builder = builder.concat(child.toString()); + } + builder = builder.concat(')'); + } + return builder; + } + } + expression.Expression = Expression; + /** + * Dictionary of function => ExpressionEvaluator. + * This is all available functions, you can add custom functions to it, but you cannot + * replace builtin functions. If you clear the dictionary, it will be reset to the built in functions. + */ + Expression.functions = new functionTable_1.FunctionTable(); + + return expression; +} + +var hasRequiredConstant; + +function requireConstant () { + if (hasRequiredConstant) return constant; + hasRequiredConstant = 1; + Object.defineProperty(constant, "__esModule", { value: true }); + constant.Constant = void 0; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + const expression_1 = requireExpression(); + const returnType_1 = requireReturnType(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + /** + * Construct an expression constant. + */ + class Constant extends expression_1.Expression { + /** + * Initializes a new instance of the [Constant](xref:adaptive-expressions.Constant) class. + * Constructs an expression constant. + * + * @param value Constant value. + */ + constructor(value) { + super(expressionType_1.ExpressionType.Constant, new expressionEvaluator_1.ExpressionEvaluator(expressionType_1.ExpressionType.Constant, (expression) => { + return { value: expression.value, error: undefined }; + })); + // original regex: (? "'\\")); + return `'${result}'`; + } + else if (functionUtils_1.FunctionUtils.isNumber(this.value)) { + return this.value.toString(); + } + else if (typeof this.value === 'object') { + return JSON.stringify(this.value); + } + return this.value.toString(); + } + /** + * @private + */ + reverseString(str) { + if (!str) { + return str; + } + return str.split('').reverse().join(''); + } + } + constant.Constant = Constant; + + return constant; +} + +var dayjs_min$1 = {exports: {}}; + +var dayjs_min = dayjs_min$1.exports; + +var hasRequiredDayjs_min; + +function requireDayjs_min () { + if (hasRequiredDayjs_min) return dayjs_min$1.exports; + hasRequiredDayjs_min = 1; + (function (module, exports) { + !function(t,e){module.exports=e();}(dayjs_min,(function(){var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",c="month",f="quarter",h="year",d="date",l="Invalid Date",$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return "["+t+(e[(n-20)%10]||e[n]||e[0])+"]"}},m=function(t,e,n){var r=String(t);return !r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return (e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()1)return t(u[0])}else {var a=e.name;D[a]=e,i=a;}return !r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,true),this.parse(t),this.$x=this.$x||t.x||{},this[p]=true;}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init();},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds();},m.$utils=function(){return b},m.isValid=function(){return !(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t) 23) { + const days = Math.floor(result.hour / 24); + const hour = result.hour % 24; + result.hour = hour; + if ('year' in result && 'month' in result && 'dayOfMonth' in result) { + const d = new Date(result.year, result.month - 1, result.dayOfMonth, 0, 0, 0); + for (let i=0; i 59) { + result.hour++; + result.minute = 0; + } + return result; + } + return start; +}; + +const timexDateTimeAdd = function (start, duration) { + return timexTimeAdd(timexDateAdd(start, duration), duration); +}; + +const expandDateTimeRange = function (timex) { + const types = ('types' in timex) ? timex.types : timexInference.infer(timex); + if (types.has('duration')) { + const start = cloneDateTime(timex); + const duration = cloneDuration(timex); + return { start: start, end: timexDateTimeAdd(start, duration), duration: duration }; + } + else { + if ('year' in timex) { + const range = { start: { year: timex.year }, end: {} }; + if ('month' in timex) { + range.start.month = timex.month; + range.start.dayOfMonth = 1; + range.end.year = timex.year; + range.end.month = timex.month + 1; + range.end.dayOfMonth = 1; + } + else { + range.start.month = 1; + range.start.dayOfMonth = 1; + range.end.year = timex.year + 1; + range.end.month = 1; + range.end.dayOfMonth = 1; + } + return range; + } + } + return { start: {}, end: {} }; +}; + +const timeAdd = function (start, duration) { + const hours = duration.hours || 0; + const minutes = duration.minutes || 0; + const seconds = duration.seconds || 0; + return { hour: start.hour + hours, minute: start.minute + minutes, second: start.second + seconds }; +}; + +const expandTimeRange = function (timex) { + + if (!timex.types.has('timerange')) + { + throw new exception('argument must be a timerange'); + } + + if (timex.partOfDay !== undefined) { + switch (timex.partOfDay) { + case 'DT': + timex = { hour: 8, minute: 0, second: 0, hours: 10, minutes: 0, seconds: 0 }; + break; + case 'MO': + timex = { hour: 8, minute: 0, second: 0, hours: 4, minutes: 0, seconds: 0 }; + break; + case 'AF': + timex = { hour: 12, minute: 0, second: 0, hours: 4, minutes: 0, seconds: 0 }; + break; + case 'EV': + timex = { hour: 16, minute: 0, second: 0, hours: 4, minutes: 0, seconds: 0 }; + break; + case 'NI': + timex = { hour: 20, minute: 0, second: 0, hours: 4, minutes: 0, seconds: 0 }; + break; + default: + throw new exception('unrecognized part of day timerange'); + } + } + + const start = { hour: timex.hour, minute: timex.minute, second: timex.second }; + const duration = cloneDuration(timex); + return { start: start, end: timeAdd(start, duration), duration: duration }; +}; + +const dateFromTimex = function (timex) { + const year = 'year' in timex ? timex.year : 2001; + const month = 'month' in timex ? timex.month - 1 : 0; + const date = 'dayOfMonth' in timex ? timex.dayOfMonth : 1; + const hour = 'hour' in timex ? timex.hour : 0; + const minute = 'minute' in timex ? timex.minute : 0; + const second = 'second' in timex ? timex.second : 0; + return new Date(year, month, date, hour, minute, second); +}; + +const timeFromTimex = function (timex) { + const hour = timex.hour || 0; + const minute = timex.minute || 0; + const second = timex.second || 0; + return new Time$1(hour, minute, second); +}; + +const dateRangeFromTimex = function (timex) { + const expanded = expandDateTimeRange(timex); + return { start: dateFromTimex(expanded.start), end: dateFromTimex(expanded.end) }; +}; + +const timeRangeFromTimex = function (timex) { + const expanded = expandTimeRange(timex); + return { start: timeFromTimex(expanded.start), end: timeFromTimex(expanded.end) }; +}; + +var timexHelpers$1 = { + expandDateTimeRange: expandDateTimeRange, + expandTimeRange: expandTimeRange, + dateFromTimex: dateFromTimex, + timeFromTimex: timeFromTimex, + dateRangeFromTimex: dateRangeFromTimex, + timeRangeFromTimex: timeRangeFromTimex, + timexTimeAdd: timexTimeAdd, + timexDateTimeAdd: timexDateTimeAdd +}; +var timexHelpers_1 = timexHelpers$1.expandDateTimeRange; +var timexHelpers_2 = timexHelpers$1.expandTimeRange; +var timexHelpers_3 = timexHelpers$1.dateFromTimex; +var timexHelpers_4 = timexHelpers$1.timeFromTimex; +var timexHelpers_5 = timexHelpers$1.dateRangeFromTimex; +var timexHelpers_6 = timexHelpers$1.timeRangeFromTimex; +var timexHelpers_7 = timexHelpers$1.timexTimeAdd; +var timexHelpers_8 = timexHelpers$1.timexDateTimeAdd; + +var timexHelpers$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexHelpers$1, + __moduleExports: timexHelpers$1, + expandDateTimeRange: timexHelpers_1, + expandTimeRange: timexHelpers_2, + dateFromTimex: timexHelpers_3, + timeFromTimex: timexHelpers_4, + dateRangeFromTimex: timexHelpers_5, + timeRangeFromTimex: timexHelpers_6, + timexTimeAdd: timexHelpers_7, + timexDateTimeAdd: timexHelpers_8 +}); + +var require$$1$1 = ( timexDateHelpers$1 && timexDateHelpers ) || timexDateHelpers$1; + +var timexHelpers = ( timexHelpers$2 && timexHelpers$1 ) || timexHelpers$2; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + +const fixedFormatNumber$1 = require$$1$1.fixedFormatNumber; + + +const formatDuration = function (timex) { + if ('years' in timex) { + return `P${timex.years}Y`; + } + if ('months' in timex) { + return `P${timex.months}M`; + } + if ('weeks' in timex) { + return `P${timex.weeks}W`; + } + if ('days' in timex) { + return `P${timex.days}D`; + } + if ('hours' in timex) { + return `PT${timex.hours}H`; + } + if ('minutes' in timex) { + return `PT${timex.minutes}M`; + } + if ('seconds' in timex) { + return `PT${timex.seconds}S`; + } + return ''; +}; + +const formatTime = function (timex) { + if (timex.minute === 0 && timex.second === 0) { + return `T${fixedFormatNumber$1(timex.hour, 2)}`; + } + if (timex.second === 0) { + return `T${fixedFormatNumber$1(timex.hour, 2)}:${fixedFormatNumber$1(timex.minute, 2)}`; + } + return `T${fixedFormatNumber$1(timex.hour, 2)}:${fixedFormatNumber$1(timex.minute, 2)}:${fixedFormatNumber$1(timex.second, 2)}`; +}; + +const formatDate = function (timex) { + if ('year' in timex && 'month' in timex && 'dayOfMonth' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}-${fixedFormatNumber$1(timex.month, 2)}-${fixedFormatNumber$1(timex.dayOfMonth, 2)}`; + } + if ('month' in timex && 'dayOfMonth' in timex) { + return `XXXX-${fixedFormatNumber$1(timex.month, 2)}-${fixedFormatNumber$1(timex.dayOfMonth, 2)}`; + } + if ('dayOfWeek' in timex) { + return `XXXX-WXX-${timex.dayOfWeek}`; + } + return ''; +}; + +const formatDateRange = function (timex) { + if ('year' in timex && 'weekOfYear' in timex && 'weekend' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}-W${fixedFormatNumber$1(timex.weekOfYear, 2)}-WE`; + } + if ('year' in timex && 'weekOfYear' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}-W${fixedFormatNumber$1(timex.weekOfYear, 2)}`; + } + if ('year' in timex && 'season' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}-${timex.season}`; + } + if ('season' in timex) { + return `${timex.season}`; + } + if ('year' in timex && 'month' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}-${fixedFormatNumber$1(timex.month, 2)}`; + } + if ('year' in timex) { + return `${fixedFormatNumber$1(timex.year, 4)}`; + } + if ('month' in timex && 'weekOfMonth' in timex && 'dayOfWeek' in timex) { + return `XXXX-${fixedFormatNumber$1(timex.month, 2)}-WXX-${timex.weekOfMonth}-${timex.dayOfWeek}`; + } + if ('month' in timex && 'weekOfMonth' in timex) { + return `XXXX-${fixedFormatNumber$1(timex.month, 2)}-WXX-${timex.weekOfMonth}`; + } + if ('month' in timex) { + return `XXXX-${fixedFormatNumber$1(timex.month, 2)}`; + } + return ''; +}; + +const formatTimeRange = function (timex) { + if ('partOfDay' in timex) { + return `T${timex.partOfDay}`; + } + return ''; +}; + +const format = function(timex) { + + const types = ('types' in timex) ? timex.types : timexInference.infer(timex); + + if (types.has('present')) { + return 'PRESENT_REF'; + } + if ((types.has('datetimerange') || types.has('daterange') || types.has('timerange')) && types.has('duration')) { + const range = timexHelpers.expandDateTimeRange(timex); + return `(${format(range.start)},${format(range.end)},${format(range.duration)})`; + } + if (types.has('datetimerange')) { + return `${formatDate(timex)}${formatTimeRange(timex)}`; + } + if (types.has('daterange')) { + return `${formatDateRange(timex)}`; + } + if (types.has('timerange')) { + return `${formatTimeRange(timex)}`; + } + if (types.has('datetime')) { + return `${formatDate(timex)}${formatTime(timex)}`; + } + if (types.has('duration')) { + return `${formatDuration(timex)}`; + } + if (types.has('date')) { + return `${formatDate(timex)}`; + } + if (types.has('time')) { + return `${formatTime(timex)}`; + } + return ''; +}; + +var format_1 = format; + +var timexFormat$1 = { + format: format_1 +}; + +var timexFormat$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexFormat$1, + __moduleExports: timexFormat$1, + format: format_1 +}); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +var days = [ + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday' +]; + +var months = [ + 'January', + 'Februrary', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December' +]; + +var dateAbbreviation = { 0: 'th', 1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th', 6: 'th', 7: 'th', 8: 'th', 9: 'th' }; + +var hours = [ + 'midnight', '1AM', '2AM', '3AM', '4AM', '5AM', '6AM', '7AM', '8AM', '9AM', '10AM', '11AM', + 'midday', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM', '10PM', '11PM' +]; + +var seasons = { SP: 'spring', SU: 'summer', FA: 'fall', WI: 'winter' }; + +var weeks = [ 'first', 'second', 'third', 'forth' ]; + +var dayParts = { DT: 'daytime', NI: 'night', MO: 'morning', AF: 'afternoon', EV: 'evening' }; + +var timexConstants$1 = { + days: days, + months: months, + dateAbbreviation: dateAbbreviation, + hours: hours, + seasons: seasons, + weeks: weeks, + dayParts: dayParts +}; + +var timexConstants$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexConstants$1, + __moduleExports: timexConstants$1, + days: days, + months: months, + dateAbbreviation: dateAbbreviation, + hours: hours, + seasons: seasons, + weeks: weeks, + dayParts: dayParts +}); + +var timexConstants = ( timexConstants$2 && timexConstants$1 ) || timexConstants$2; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + + +const convertDate$1 = function(timex) { + if ('dayOfWeek' in timex) { + return timexConstants.days[timex.dayOfWeek - 1]; + } + const month = timexConstants.months[timex.month - 1]; + const date = timex.dayOfMonth.toString(); + const abbreviation = timexConstants.dateAbbreviation[date.slice(-1)]; + if ('year' in timex) { + return `${date}${abbreviation} ${month} ${timex.year}`.trim(); + } + return `${date}${abbreviation} ${month}`; +}; + +const convertTime = function(timex) { + if (timex.hour === 0 && timex.minute === 0 && timex.second === 0) { + return 'midnight'; + } + if (timex.hour === 12 && timex.minute === 0 && timex.second === 0) { + return 'midday'; + } + const pad = function (s) { return (s.length === 1) ? '0' + s : s; }; + const hour = (timex.hour === 0) ? '12' : (timex.hour > 12) ? (timex.hour - 12).toString() : timex.hour.toString(); + const minute = (timex.minute === 0 && timex.second === 0) ? '' : ':' + pad(timex.minute.toString()); + const second = (timex.second === 0) ? '' : ':' + pad(timex.second.toString()); + const period = timex.hour < 12 ? 'AM' : 'PM'; + return `${hour}${minute}${second}${period}`; +}; + +const convertDurationPropertyToString = function (timex, property, includeSingleCount) { + const propertyName = property + 's'; + const value = timex[propertyName]; + if (value !== undefined) { + if (value === 1) { + return includeSingleCount ? '1 ' + property : property; + } + else { + return `${value} ${property}s`; + } + } + return false; +}; + +const convertTimexDurationToString = function (timex, includeSingleCount) { + return convertDurationPropertyToString(timex, 'year', includeSingleCount) + || convertDurationPropertyToString(timex, 'month', includeSingleCount) + || convertDurationPropertyToString(timex, 'week', includeSingleCount) + || convertDurationPropertyToString(timex, 'day', includeSingleCount) + || convertDurationPropertyToString(timex, 'hour', includeSingleCount) + || convertDurationPropertyToString(timex, 'minute', includeSingleCount) + || convertDurationPropertyToString(timex, 'second', includeSingleCount); +}; + +const convertDuration = function(timex) { + return convertTimexDurationToString(timex, true); +}; + +const convertDateRange$1 = function(timex) { + const season = ('season' in timex) ? timexConstants.seasons[timex.season] : ''; + const year = ('year' in timex) ? timex.year.toString() : ''; + if ('weekOfYear' in timex) { + if (timex.weekend) { + return ''; + } + else { + return ''; + } + } + if ('month' in timex) { + const month = `${timexConstants.months[timex.month - 1]}`; + if ('weekOfMonth' in timex) { + return `${timexConstants.weeks[timex.weekOfMonth - 1]} week of ${month}`; + } + else { + return `${month} ${year}`.trim(); + } + } + return `${season} ${year}`.trim(); +}; + +const convertTimeRange = function(timex) { + return timexConstants.dayParts[timex.partOfDay]; +}; + +const convertDateTime$1 = function(timex) { + return `${convertTime(timex)} ${convertDate$1(timex)}`; +}; + +const convertDateTimeRange$1 = function(timex) { + if (timex.types.has('timerange')) { + return `${convertDate$1(timex)} ${convertTimeRange(timex)}`; + } + // date + time + duration + // - OR - + // date + duration + return ''; +}; + +const convertTimexToString = function (timex) { + + const types = ('types' in timex) ? timex.types : timexInference.infer(timex); + + if (types.has('present')) { + return 'now'; + } + if (types.has('datetimerange')) { + return convertDateTimeRange$1(timex); + } + if (types.has('daterange')) { + return convertDateRange$1(timex); + } + if (types.has('duration')) { + return convertDuration(timex); + } + if (types.has('timerange')) { + return convertTimeRange(timex); + } + + // TODO: where appropriate delegate most the formatting delegate to Date.toLocaleString(options) + if (types.has('datetime')) { + return convertDateTime$1(timex); + } + if (types.has('date')) { + return convertDate$1(timex); + } + if (types.has('time')) { + return convertTime(timex); + } + return ''; +}; + +const convertTimexSetToString = function(timexSet) { + + const timex = timexSet.timex; + if (timex.types.has('duration')) { + return `every ${convertTimexDurationToString(timex, false)}`; + } + else { + return `every ${convertTimexToString(timex)}`; + } +}; + +var timexConvert$4 = { + convertDate: convertDate$1, + convertTime: convertTime, + convertTimexToString: convertTimexToString, + convertTimexSetToString: convertTimexSetToString +}; +var timexConvert_1$1 = timexConvert$4.convertDate; +var timexConvert_2$1 = timexConvert$4.convertTime; +var timexConvert_3 = timexConvert$4.convertTimexToString; +var timexConvert_4 = timexConvert$4.convertTimexSetToString; + +var timexConvert$5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexConvert$4, + __moduleExports: timexConvert$4, + convertDate: timexConvert_1$1, + convertTime: timexConvert_2$1, + convertTimexToString: timexConvert_3, + convertTimexSetToString: timexConvert_4 +}); + +var timexConvert$3 = ( timexConvert$5 && timexConvert$4 ) || timexConvert$5; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + +var timexConvert$1 = { + convertTimexToString: timexConvert$3.convertTimexToString, + convertTimexSetToString: timexConvert$3.convertTimexSetToString +}; +var timexConvert_1 = timexConvert$1.convertTimexToString; +var timexConvert_2 = timexConvert$1.convertTimexSetToString; + +var timexConvert$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexConvert$1, + __moduleExports: timexConvert$1, + convertTimexToString: timexConvert_1, + convertTimexSetToString: timexConvert_2 +}); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + + + + +const getDateDay = function (day) { + const index = (day === 0) ? 6 : day - 1; + return timexConstants.days[index]; +}; + +const convertDate = function(timex, date) { + if ('year' in timex && 'month' in timex && 'dayOfMonth' in timex) { + const timexDate = new Date(timex.year, timex.month - 1, timex.dayOfMonth); + + if (require$$1$1.datePartEquals(timexDate, date)) { + return 'today'; + } + const tomorrow = require$$1$1.tomorrow(date); + if (require$$1$1.datePartEquals(timexDate, tomorrow)) { + return 'tomorrow'; + } + const yesterday = require$$1$1.yesterday(date); + if (require$$1$1.datePartEquals(timexDate, yesterday)) { + return 'yesterday'; + } + if (require$$1$1.isThisWeek(timexDate, date)) { + return `this ${getDateDay(timexDate.getDay())}`; + } + if (require$$1$1.isNextWeek(timexDate, date)) { + return `next ${getDateDay(timexDate.getDay())}`; + } + if (require$$1$1.isLastWeek(timexDate, date)) { + return `last ${getDateDay(timexDate.getDay())}`; + } + } + return timexConvert$3.convertDate(timex); +}; + +const convertDateTime = function (timex, date) { + return `${convertDate(timex, date)} ${timexConvert$3.convertTime(timex)}`; +}; + +const convertDateRange = function(timex, date) { + if ('year' in timex) { + const year = date.getFullYear(); + if (timex.year === year) { + if ('weekOfYear' in timex) { + const thisWeek = require$$1$1.weekOfYear(date); + if (thisWeek === timex.weekOfYear) { + return timex.weekend ? 'this weekend' : 'this week'; + } + if (thisWeek === timex.weekOfYear + 1) { + return timex.weekend ? 'last weekend' : 'last week'; + } + if (thisWeek === timex.weekOfYear - 1) { + return timex.weekend ? 'next weekend' : 'next week'; + } + } + if ('month' in timex) { + const isoMonth = date.getMonth() + 1; + if (timex.month === isoMonth) { + return 'this month'; + } + if (timex.month === isoMonth + 1) { + return 'next month'; + } + if (timex.month === isoMonth - 1) { + return 'last month'; + } + } + return ('season' in timex) ? `this ${timexConstants.seasons[timex.season]}` : 'this year'; + } + if (timex.year === year + 1) { + return ('season' in timex) ? `next ${timexConstants.seasons[timex.season]}` : 'next year'; + } + if (timex.year === year - 1) { + return ('season' in timex) ? `last ${timexConstants.seasons[timex.season]}` : 'last year'; + } + } + return ''; +}; + +const convertDateTimeRange = function(timex, date) { + if ('year' in timex && 'month' in timex && 'dayOfMonth' in timex) { + const timexDate = new Date(timex.year, timex.month - 1, timex.dayOfMonth); + + if ('partOfDay' in timex) { + if (require$$1$1.datePartEquals(timexDate, date)) { + if (timex.partOfDay === 'NI') { + return 'tonight'; + } + else { + return `this ${timexConstants.dayParts[timex.partOfDay]}`; + } + } + const tomorrow = require$$1$1.tomorrow(date); + if (require$$1$1.datePartEquals(timexDate, tomorrow)) { + return `tomorrow ${timexConstants.dayParts[timex.partOfDay]}`; + } + const yesterday = require$$1$1.yesterday(date); + if (require$$1$1.datePartEquals(timexDate, yesterday)) { + return `yesterday ${timexConstants.dayParts[timex.partOfDay]}`; + } + + if (require$$1$1.isNextWeek(timexDate, date)) { + return `next ${getDateDay(timexDate.getDay())} ${timexConstants.dayParts[timex.partOfDay]}`; + } + + if (require$$1$1.isLastWeek(timexDate, date)) { + return `last ${getDateDay(timexDate.getDay())} ${timexConstants.dayParts[timex.partOfDay]}`; + } + } + } + return ''; +}; + +const convertTimexToStringRelative$1 = function (timex, date) { + + const types = ('types' in timex) ? timex.types : timexInference.infer(timex); + + if (types.has('datetimerange')) { + return convertDateTimeRange(timex, date); + } + if (types.has('daterange')) { + return convertDateRange(timex, date); + } + if (types.has('datetime')) { + return convertDateTime(timex, date); + } + if (types.has('date')) { + return convertDate(timex, date); + } + + return timexConvert$3.convertTimexToString(timex); +}; + +var convertTimexToStringRelative_1 = convertTimexToStringRelative$1; + +var timexRelativeConvert$3 = { + convertTimexToStringRelative: convertTimexToStringRelative_1 +}; + +var timexRelativeConvert$4 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexRelativeConvert$3, + __moduleExports: timexRelativeConvert$3, + convertTimexToStringRelative: convertTimexToStringRelative_1 +}); + +var require$$0$2 = ( timexRelativeConvert$4 && timexRelativeConvert$3 ) || timexRelativeConvert$4; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +var convertTimexToStringRelative = require$$0$2.convertTimexToStringRelative; + +var timexRelativeConvert$1 = { + convertTimexToStringRelative: convertTimexToStringRelative +}; + +var timexRelativeConvert$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexRelativeConvert$1, + __moduleExports: timexRelativeConvert$1, + convertTimexToStringRelative: convertTimexToStringRelative +}); + +var timexParsing = ( timexParsing$2 && timexParsing$1 ) || timexParsing$2; + +var timexFormat = ( timexFormat$2 && timexFormat$1 ) || timexFormat$2; + +var timexConvert = ( timexConvert$2 && timexConvert$1 ) || timexConvert$2; + +var timexRelativeConvert = ( timexRelativeConvert$2 && timexRelativeConvert$1 ) || timexRelativeConvert$2; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + + + + + +class TimexProperty$4 { + constructor (timex) { + if (typeof timex === 'string') { + timexParsing.parseString(timex, this); + } + else { + timexParsing.fromObject(timex, this); + } + // TODO: constructing a Timex from a Timex should be very cheap + } + + get timex() { + return timexFormat.format(this); + } + + get types () { + return timexInference.infer(this); + } + + toString () { + return timexConvert.convertTimexToString(this); + } + + // TODO: consider [locales[, options]] similar to Date.toLocaleString([locales[, options]]) + toNaturalLanguage (referenceDate) { + return timexRelativeConvert.convertTimexToStringRelative(this, referenceDate); + } + + static fromDate (date) { + return new TimexProperty$4({ + year: date.getFullYear(), + month: date.getMonth() + 1, + dayOfMonth: date.getDate() + }); + } + + static fromDateTime (date) { + return new TimexProperty$4({ + year: date.getFullYear(), + month: date.getMonth() + 1, + dayOfMonth: date.getDate(), + hour: date.getHours(), + minute: date.getMinutes(), + second: date.getSeconds() + }); + } + + static fromTime (time) { + return new TimexProperty$4(time); + } +} + +var TimexProperty_1 = TimexProperty$4; + +var timexProperty = { + TimexProperty: TimexProperty_1 +}; + +var timexProperty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexProperty, + __moduleExports: timexProperty, + TimexProperty: TimexProperty_1 +}); + +var require$$1$2 = ( timexProperty$1 && timexProperty ) || timexProperty$1; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const TimexProperty$3 = require$$1$2.TimexProperty; + +class TimexSet { + constructor (timex) { + this.timex = new TimexProperty$3(timex); + } +} + +var TimexSet_1 = TimexSet; + +var timexSet = { + TimexSet: TimexSet_1 +}; + +var timexSet$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexSet, + __moduleExports: timexSet, + TimexSet: TimexSet_1 +}); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + +const TimexProperty$2 = require$$1$2.TimexProperty; + +const today = function (date) { + return TimexProperty$2.fromDate(date || new Date()).timex; +}; + +const tomorrow = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + d.setDate(d.getDate() + 1); + return TimexProperty$2.fromDate(d).timex; +}; + +const yesterday = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + d.setDate(d.getDate() - 1); + return TimexProperty$2.fromDate(d).timex; +}; + +const weekFromToday = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(d), { days: 7 }))).timex; +}; + +const weekBackFromToday = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + d.setDate(d.getDate() - 7); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(d), { days: 7 }))).timex; +}; + +const thisWeek = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + d.setDate(d.getDate() - 7); + const start = require$$1$1.dateOfNextDay(1, d); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(start), { days: 7 }))).timex; +}; + +const nextWeek = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + const start = require$$1$1.dateOfNextDay(1, d); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(start), { days: 7 }))).timex; +}; + +const lastWeek = function (date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + const start = require$$1$1.dateOfLastDay(1, d); + start.setDate(start.getDate() - 7); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(start), { days: 7 }))).timex; +}; + +const nextWeeksFromToday = function (n, date) { + const d = (date === undefined) ? new Date() : new Date(date.getTime()); + return (new TimexProperty$2(Object.assign(TimexProperty$2.fromDate(d), { days: 7 * n }))).timex; +}; + +// The following constants are consistent with the Recognizer results +const monday = 'XXXX-WXX-1'; +const tuesday = 'XXXX-WXX-2'; +const wednesday = 'XXXX-WXX-3'; +const thursday = 'XXXX-WXX-4'; +const friday = 'XXXX-WXX-5'; +const saturday = 'XXXX-WXX-6'; +const sunday = 'XXXX-WXX-7'; +const morning = '(T08,T12,PT4H)'; +const afternoon = '(T12,T16,PT4H)'; +const evening = '(T16,T20,PT4H)'; +const daytime = '(T08,T18,PT10H)'; + +var timexCreator = { + today: today, + tomorrow: tomorrow, + yesterday: yesterday, + weekFromToday: weekFromToday, + weekBackFromToday: weekBackFromToday, + thisWeek: thisWeek, + nextWeek: nextWeek, + lastWeek: lastWeek, + nextWeeksFromToday: nextWeeksFromToday, + monday: monday, + tuesday: tuesday, + wednesday: wednesday, + thursday: thursday, + friday: friday, + saturday: saturday, + sunday: sunday, + morning: morning, + afternoon: afternoon, + evening: evening, + daytime: daytime +}; +var timexCreator_1 = timexCreator.today; +var timexCreator_2 = timexCreator.tomorrow; +var timexCreator_3 = timexCreator.yesterday; +var timexCreator_4 = timexCreator.weekFromToday; +var timexCreator_5 = timexCreator.weekBackFromToday; +var timexCreator_6 = timexCreator.thisWeek; +var timexCreator_7 = timexCreator.nextWeek; +var timexCreator_8 = timexCreator.lastWeek; +var timexCreator_9 = timexCreator.nextWeeksFromToday; +var timexCreator_10 = timexCreator.monday; +var timexCreator_11 = timexCreator.tuesday; +var timexCreator_12 = timexCreator.wednesday; +var timexCreator_13 = timexCreator.thursday; +var timexCreator_14 = timexCreator.friday; +var timexCreator_15 = timexCreator.saturday; +var timexCreator_16 = timexCreator.sunday; +var timexCreator_17 = timexCreator.morning; +var timexCreator_18 = timexCreator.afternoon; +var timexCreator_19 = timexCreator.evening; +var timexCreator_20 = timexCreator.daytime; + +var timexCreator$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexCreator, + __moduleExports: timexCreator, + today: timexCreator_1, + tomorrow: timexCreator_2, + yesterday: timexCreator_3, + weekFromToday: timexCreator_4, + weekBackFromToday: timexCreator_5, + thisWeek: timexCreator_6, + nextWeek: timexCreator_7, + lastWeek: timexCreator_8, + nextWeeksFromToday: timexCreator_9, + monday: timexCreator_10, + tuesday: timexCreator_11, + wednesday: timexCreator_12, + thursday: timexCreator_13, + friday: timexCreator_14, + saturday: timexCreator_15, + sunday: timexCreator_16, + morning: timexCreator_17, + afternoon: timexCreator_18, + evening: timexCreator_19, + daytime: timexCreator_20 +}); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const isOverlapping = function (r1, r2) { + return r1.end.getTime() > r2.start.getTime() && r1.start.getTime() <= r2.start.getTime() + || r1.start.getTime() < r2.end.getTime() && r1.start.getTime() >= r2.start.getTime(); +}; + +const collapseOverlapping = function (r1, r2, T) { + return { + start: new T(Math.max(r1.start.getTime(), r2.start.getTime())), + end: new T(Math.min(r1.end.getTime(), r2.end.getTime())) + }; +}; + +const innerCollapse = function (ranges, T) { + if (ranges.length === 1) { + return false; + } + for (let i=0; i a.start.getTime() - b.start.getTime()); + return r; +}; + +var timexConstraintsHelper$1 = { + collapse: collapse, + isOverlapping: isOverlapping +}; +var timexConstraintsHelper_1 = timexConstraintsHelper$1.collapse; +var timexConstraintsHelper_2 = timexConstraintsHelper$1.isOverlapping; + +var timexConstraintsHelper$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexConstraintsHelper$1, + __moduleExports: timexConstraintsHelper$1, + collapse: timexConstraintsHelper_1, + isOverlapping: timexConstraintsHelper_2 +}); + +var timexConstraintsHelper = ( timexConstraintsHelper$2 && timexConstraintsHelper$1 ) || timexConstraintsHelper$2; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + + + +const Time = require$$0$1$1.Time; +const TimexProperty$1 = require$$1$2.TimexProperty; + +const resolveDefiniteAgainstConstraint = function (timex, constraint) { + const timexDate = timexHelpers.dateFromTimex(timex); + if (timexDate.getTime() >= constraint.start.getTime() && timexDate.getTime() < constraint.end.getTime()) { + return [ timex.timex ]; + } + return []; +}; + +const resolveDateAgainstConstraint = function (timex, constraint) { + if ('month' in timex && 'dayOfMonth' in timex) { + const result = []; + for (let year = constraint.start.getFullYear(); year <= constraint.end.getFullYear(); year++) { + const r = resolveDefiniteAgainstConstraint(new TimexProperty$1(Object.assign({}, timex, { year: year })), constraint); + if (r.length > 0) { + result.push(r[0]); + } + } + return result; + } + if ('dayOfWeek' in timex) { + const day = timex.dayOfWeek === 7 ? 0 : timex.dayOfWeek; + const dates = require$$1$1.datesMatchingDay(day, constraint.start, constraint.end); + const result = []; + for (const d of dates) { + const t = Object.assign({}, timex); + delete t.dayOfWeek; + const r = new TimexProperty$1(Object.assign({}, t, { year: d.getFullYear(), month: d.getMonth() + 1, dayOfMonth: d.getDate() })); + result.push(r.timex); + } + return result; + } + return []; +}; + +const resolveDate$1 = function (timex, constraints) { + const result = []; + for (const constraint of constraints) { + Array.prototype.push.apply(result, resolveDateAgainstConstraint(timex, constraint)); + } + return result; +}; + +const resolveTimeAgainstConstraint = function (timex, constraint) { + const t = new Time(timex.hour, timex.minute, timex.second); + if (t.getTime() >= constraint.start.getTime() && t.getTime() < constraint.end.getTime()) { + return [ timex.timex ]; + } + return []; +}; + +const resolveTime$1 = function (timex, constraints) { + const result = []; + for (const constraint of constraints) { + Array.prototype.push.apply(result, resolveTimeAgainstConstraint(timex, constraint)); + } + return result; +}; + +const removeDuplicates = function (array) { + var seen = new Set(); + return array.filter(item => { return seen.has(item) ? false : seen.add(item); }); +}; + +const resolveByDateRangeConstraints = function (candidates, timexConstraints) { + + const dateRangeConstraints = timexConstraints + .filter((timex) => { + return timex.types.has('daterange'); }) + .map((timex) => { + return timexHelpers.dateRangeFromTimex(timex); + }); + const collapsedDateRanges = timexConstraintsHelper.collapse(dateRangeConstraints, Date); + + if (collapsedDateRanges.length === 0) { + return candidates; + } + + const resolution = []; + for (const timex of candidates) { + const r = resolveDate$1(new TimexProperty$1(timex), collapsedDateRanges); + Array.prototype.push.apply(resolution, r); + } + + return removeDuplicates(resolution); +}; + +const resolveByTimeConstraints = function (candidates, timexConstraints) { + + const times = timexConstraints + .filter((timex) => { + return timex.types.has('time'); }) + .map((timex) => { + return timexHelpers.timeFromTimex(timex); + }); + + if (times.length === 0) { + return candidates; + } + + const resolution = []; + for (const timex of candidates.map(t => new TimexProperty$1(t))) { + if (timex.types.has('date') && !timex.types.has('time')) { + for (const time of times) { + timex.hour = time.hour; + timex.minute = time.minute; + timex.second = time.second; + resolution.push(timex.timex); + } + } + else { + resolution.push(timex.timex); + } + } + return removeDuplicates(resolution); +}; + +const resolveByTimeRangeConstraints = function (candidates, timexConstraints) { + + const timeRangeConstraints = timexConstraints + .filter((timex) => { + return timex.types.has('timerange'); }) + .map((timex) => { + return timexHelpers.timeRangeFromTimex(timex); + }); + const collapsedTimeRanges = timexConstraintsHelper.collapse(timeRangeConstraints, Time); + + if (collapsedTimeRanges.length === 0) { + return candidates; + } + + const resolution = []; + for (const timex of candidates) { + const t = new TimexProperty$1(timex); + if (t.types.has('timerange')) { + const r = resolveTimeRange$1(t, collapsedTimeRanges); + Array.prototype.push.apply(resolution, r); + } + else if (t.types.has('time')) { + const r = resolveTime$1(t, collapsedTimeRanges); + Array.prototype.push.apply(resolution, r); + } + } + + return removeDuplicates(resolution); +}; + +const resolveTimeRange$1 = function (timex, constraints) { + + const candidate = timexHelpers.timeRangeFromTimex(timex); + + const result = []; + for (const constraint of constraints) { + + if (timexConstraintsHelper.isOverlapping(candidate, constraint)) { + + const start = Math.max(candidate.start.getTime(), constraint.start.getTime()); + const time = new Time(start); + + // TODO: refer to comments in C# - consider first classing this clone/overwrite behavior + const resolved = new TimexProperty$1(timex.timex); + delete resolved.partOfDay; + delete resolved.seconds; + delete resolved.minutes; + delete resolved.hours; + resolved.second = time.second; + resolved.minute = time.minute; + resolved.hour = time.hour; + + result.push(resolved.timex); + } + } + return result; +}; + +const resolveDuration$1 = function (candidate, constraints) { + const results = []; + for (const constraint of constraints) { + if (constraint.types.has('datetime')) { + results.push(new TimexProperty$1(timexHelpers.timexDateTimeAdd(constraint, candidate))); + } + else if (constraint.types.has('time')) { + results.push(new TimexProperty$1(timexHelpers.timexTimeAdd(constraint, candidate))); + } + } + return results; +}; + +const resolveDurations = function (candidates, constraints) { + const results = []; + for (const candidate of candidates) { + const timex = new TimexProperty$1(candidate); + if (timex.types.has('duration')) { + const r = resolveDuration$1(timex, constraints); + for (const resolved of r) { + results.push(resolved.timex); + } + } + else { + results.push(candidate); + } + } + return results; +}; + +const evaluate = function (candidates, constraints) { + const timexConstraints = constraints.map((x) => { return new TimexProperty$1(x); }); + const candidatesWithDurationsResolved = resolveDurations(candidates, timexConstraints); + const candidatesAccordingToDate = resolveByDateRangeConstraints(candidatesWithDurationsResolved, timexConstraints); + const candidatesWithAddedTime = resolveByTimeConstraints(candidatesAccordingToDate, timexConstraints); + const candidatesFilteredByTime = resolveByTimeRangeConstraints(candidatesWithAddedTime, timexConstraints); + const timexResults = candidatesFilteredByTime.map((x) => { return new TimexProperty$1(x); }); + return timexResults; +}; + +var timexRangeResolver = { + evaluate: evaluate +}; +var timexRangeResolver_1 = timexRangeResolver.evaluate; + +var timexRangeResolver$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexRangeResolver, + __moduleExports: timexRangeResolver, + evaluate: timexRangeResolver_1 +}); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const fixedFormatNumber = require$$1$1.fixedFormatNumber; + +const dateValue = function (obj) { + if (obj.year !== undefined && obj.month !== undefined && obj.dayOfMonth !== undefined) { + return `${fixedFormatNumber(obj.year, 4)}-${fixedFormatNumber(obj.month, 2)}-${fixedFormatNumber(obj.dayOfMonth, 2)}`; + } + return ''; +}; + +const timeValue = function (obj) { + if (obj.hour !== undefined && obj.minute !== undefined && obj.second !== undefined) { + return `${fixedFormatNumber(obj.hour, 2)}:${fixedFormatNumber(obj.minute, 2)}:${fixedFormatNumber(obj.second, 2)}`; + } + return ''; +}; + +const datetimeValue = function (obj) { + return `${dateValue(obj)} ${timeValue(obj)}`; +}; + +const durationValue = function (obj) { + if (obj.years !== undefined) { + return (31536000 * obj.years).toString(); + } + if (obj.months !== undefined) { + return (2592000 * obj.months).toString(); + } + if (obj.weeks !== undefined) { + return (604800 * obj.weeks).toString(); + } + if (obj.days !== undefined) { + return (86400 * obj.days).toString(); + } + if (obj.hours !== undefined) { + return (3600 * obj.hours).toString(); + } + if (obj.minutes !== undefined) { + return (60 * obj.minutes).toString(); + } + if (obj.seconds !== undefined) { + return obj.seconds.toString(); + } + return ''; +}; + +var timexValue$1 = { + dateValue: dateValue, + timeValue: timeValue, + datetimeValue: datetimeValue, + durationValue: durationValue +}; +var timexValue_1 = timexValue$1.dateValue; +var timexValue_2 = timexValue$1.timeValue; +var timexValue_3 = timexValue$1.datetimeValue; +var timexValue_4 = timexValue$1.durationValue; + +var timexValue$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexValue$1, + __moduleExports: timexValue$1, + dateValue: timexValue_1, + timeValue: timexValue_2, + datetimeValue: timexValue_3, + durationValue: timexValue_4 +}); + +var timexValue = ( timexValue$2 && timexValue$1 ) || timexValue$2; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +const TimexProperty = require$$1$2.TimexProperty; + + + + +const dateOfLastDay = require$$1$1.dateOfLastDay; +const dateOfNextDay = require$$1$1.dateOfNextDay; + +const resolveDefiniteTime = function (timex, date) { + return [{ timex: timex.timex, type: 'datetime', value: `${timexValue.dateValue(timex)} ${timexValue.timeValue(timex)}` }]; +}; + +const resolveDefinite = function (timex, date) { + return [{ timex: timex.timex, type: 'date', value: timexValue.dateValue(timex) }]; +}; + +const lastDateValue = function (timex, date) { + if (timex.month !== undefined && timex.dayOfMonth !== undefined) { + return timexValue.dateValue({ year: date.getFullYear() - 1, month: timex.month, dayOfMonth: timex.dayOfMonth }); + } + if (timex.dayOfWeek !== undefined) { + const day = timex.dayOfWeek === 7 ? 0 : timex.dayOfWeek; + const result = dateOfLastDay(day, date); + return timexValue.dateValue({ year: result.getFullYear(), month: result.getMonth() + 1, dayOfMonth: result.getDate() }); + } +}; + +const nextDateValue = function (timex, date) { + if (timex.month !== undefined && timex.dayOfMonth !== undefined) { + return timexValue.dateValue({ year: date.getFullYear(), month: timex.month, dayOfMonth: timex.dayOfMonth }); + } + if (timex.dayOfWeek !== undefined) { + const day = timex.dayOfWeek === 7 ? 0 : timex.dayOfWeek; + const result = dateOfNextDay(day, date); + return timexValue.dateValue({ year: result.getFullYear(), month: result.getMonth() + 1, dayOfMonth: result.getDate() }); + } +}; + +const resolveDate = function (timex, date) { + return [ + { timex: timex.timex, type: 'date', value: lastDateValue(timex, date) }, + { timex: timex.timex, type: 'date', value: nextDateValue(timex, date) } + ]; +}; + +const resolveTime = function (timex) { + return [ { timex: timex.timex, type: 'time', value: timexValue.timeValue(timex) } ]; +}; + +const resolveDuration = function (timex) { + return [ { timex: timex.timex, type: 'duration', value: timexValue.durationValue(timex) }]; +}; + +const weekDateRange = function (year, weekOfYear) { + var dateInWeek = new Date(year, 0, 1); + dateInWeek.setDate(dateInWeek.getDate() + ((weekOfYear - 1) * 7)); + + var start = dateOfLastDay(1, dateInWeek); + dateInWeek.setDate(dateInWeek.getDate() + 7); + var end = dateOfLastDay(1, dateInWeek); + + return { + start: timexValue.dateValue({ year: start.getFullYear(), month: start.getMonth() + 1, dayOfMonth: start.getDate() }), + end: timexValue.dateValue({ year: end.getFullYear(), month: end.getMonth() + 1, dayOfMonth: end.getDate() }) + } +}; + +const monthDateRange = function (year, month) { + return { + start: timexValue.dateValue({ year: year, month: month, dayOfMonth: 1 }), + end: timexValue.dateValue({ year: month == 12 ? year + 1 : year, month: month == 12 ? 1 : month + 1, dayOfMonth: 1 }) + }; +}; + +const yearDateRange = function (year) { + return { + start: timexValue.dateValue({ year: year, month: 1, dayOfMonth: 1 }), + end: timexValue.dateValue({ year: year + 1, month: 1, dayOfMonth: 1 }) + }; +}; + +const resolveDateRange = function (timex, date) { + if ('season' in timex) { + return [{ timex: timex.timex, type: 'daterange', value: 'not resolved' }]; + } + else { + if (timex.year !== undefined && timex.month !== undefined) { + const dateRange = monthDateRange(timex.year, timex.month); + return [{ timex: timex.timex, type: 'daterange', start: dateRange.start, end: dateRange.end }]; + } + if (timex.year !== undefined && timex.weekOfYear !== undefined) { + const dateRange = weekDateRange(timex.year, timex.weekOfYear); + return [{ timex: timex.timex, type: 'daterange', start: dateRange.start, end: dateRange.end }]; + } + if (timex.month !== undefined) { + const y = date.getFullYear(); + const lastYearDateRange = monthDateRange(y - 1, timex.month); + const thisYearDateRange = monthDateRange(y, timex.month); + + return [ + { timex: timex.timex, type: 'daterange', start: lastYearDateRange.start, end: lastYearDateRange.end }, + { timex: timex.timex, type: 'daterange', start: thisYearDateRange.start, end: thisYearDateRange.end } + ]; + } + if (timex.year !== undefined) { + const dateRange = yearDateRange(timex.year); + return [{ timex: timex.timex, type: 'daterange', start: dateRange.start, end: dateRange.end }]; + } + return []; + } +}; + +const partOfDayTimeRange = function (timex) { + switch (timex.partOfDay) { + case 'MO': return { start: '08:00:00', end: '12:00:00' }; + case 'AF': return { start: '12:00:00', end: '16:00:00' }; + case 'EV': return { start: '16:00:00', end: '20:00:00' }; + case 'NI': return { start: '20:00:00', end: '24:00:00' }; + } + return { start: 'not resolved', end: 'not resolved' }; +}; + +const resolveTimeRange = function (timex, date) { + if ('partOfDay' in timex) { + const range = partOfDayTimeRange(timex); + return [{ timex: timex.timex, type: 'timerange', start: range.start, end: range.end }]; + } + else { + const range = timexHelpers.expandTimeRange(timex); + return [{ + timex: timex.timex, + type: 'timerange', + start: timexValue.timeValue(range.start), + end: timexValue.timeValue(range.end) + }]; + } +}; + +const resolveDateTime = function (timex, date) { + const resolvedDates = resolveDate(timex, date); + for (const resolved of resolvedDates) { + resolved.type = 'datetime'; + resolved.value = `${resolved.value} ${timexValue.timeValue(timex)}`; + + } + return resolvedDates; +}; + +const resolveDateTimeRange = function (timex) { + if ('partOfDay' in timex) { + const date = timexValue.dateValue(timex); + const timeRange = partOfDayTimeRange(timex); + return [{ + timex: timex.timex, + type: 'datetimerange', + start: `${date} ${timeRange.start}`, + end: `${date} ${timeRange.end}` + }]; + } + else { + const range = timexHelpers.expandDateTimeRange(timex); + return [{ + timex: timex.timex, + type: 'datetimerange', + start: `${timexValue.dateValue(range.start)} ${timexValue.timeValue(range.start)}`, + end: `${timexValue.dateValue(range.end)} ${timexValue.timeValue(range.end)}` + }]; + } +}; + +const resolveDefiniteDateRange = function (timex) { + var range = timexHelpers.expandDateTimeRange(timex); + return [{ + timex: timex.timex, + type: 'daterange', + start: `${timexValue.dateValue(range.start)}`, + end: `${timexValue.dateValue(range.end)}` + }]; +}; + +const resolveTimex = function (timex, date) { + + const types = ('types' in timex) ? timex.types : timexInference.infer(timex); + + if (types.has('datetimerange')) { + return resolveDateTimeRange(timex); + } + if (types.has('definite') && types.has('time')) { + return resolveDefiniteTime(timex); + } + if (types.has('definite') && types.has('daterange')) { + return resolveDefiniteDateRange(timex); + } + if (types.has('definite')) { + return resolveDefinite(timex); + } + if (types.has('daterange')) { + return resolveDateRange(timex, date); + } + if (types.has('timerange')) { + return resolveTimeRange(timex); + } + if (types.has('datetime')) { + return resolveDateTime(timex, date); + } + if (types.has('duration')) { + return resolveDuration(timex); + } + if (types.has('date')) { + return resolveDate(timex, date); + } + if (types.has('time')) { + return resolveTime(timex); + } + return []; +}; + +const resolve = function (timexArray, date) { + const resolution = { values: [] }; + for (const timex of timexArray) { + const t = new TimexProperty(timex); + const r = resolveTimex(t, date); + Array.prototype.push.apply(resolution.values, r); + } + return resolution; +}; + +var timexResolver = { + resolve: resolve +}; +var timexResolver_1 = timexResolver.resolve; + +var timexResolver$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': timexResolver, + __moduleExports: timexResolver, + resolve: timexResolver_1 +}); + +var require$$2 = ( timexSet$1 && timexSet ) || timexSet$1; + +var require$$3 = ( timexCreator$1 && timexCreator ) || timexCreator$1; + +var require$$4 = ( timexRangeResolver$1 && timexRangeResolver ) || timexRangeResolver$1; + +var require$$5 = ( timexResolver$1 && timexResolver ) || timexResolver$1; + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +var datatypesDateTime = { + Time: require$$0$1$1.Time, + TimexProperty: require$$1$2.TimexProperty, + TimexSet: require$$2.TimexSet, + creator: require$$3, + resolver: require$$4, + valueResolver: require$$5 +}; +var datatypesDateTime_1 = datatypesDateTime.Time; +var datatypesDateTime_2 = datatypesDateTime.TimexProperty; +var datatypesDateTime_3 = datatypesDateTime.TimexSet; +var datatypesDateTime_4 = datatypesDateTime.creator; +var datatypesDateTime_5 = datatypesDateTime.resolver; +var datatypesDateTime_6 = datatypesDateTime.valueResolver; + +var recognizersTextDataTypesTimexExpression_es5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Time: datatypesDateTime_1, + TimexProperty: datatypesDateTime_2, + TimexSet: datatypesDateTime_3, + creator: datatypesDateTime_4, + default: datatypesDateTime, + resolver: datatypesDateTime_5, + valueResolver: datatypesDateTime_6 +}); + +var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(recognizersTextDataTypesTimexExpression_es5); + +var BigInteger = {exports: {}}; + +var hasRequiredBigInteger; + +function requireBigInteger () { + if (hasRequiredBigInteger) return BigInteger.exports; + hasRequiredBigInteger = 1; + (function (module) { + var bigInt = (function (undefined$1) { + + var BASE = 1e7, + LOG_BASE = 7, + MAX_INT = 9007199254740992, + MAX_INT_ARR = smallToArray(MAX_INT), + DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; + + var supportsNativeBigInt = typeof BigInt === "function"; + + function Integer(v, radix, alphabet, caseSensitive) { + if (typeof v === "undefined") return Integer[0]; + if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive); + return parseValue(v); + } + + function BigInteger(value, sign) { + this.value = value; + this.sign = sign; + this.isSmall = false; + } + BigInteger.prototype = Object.create(Integer.prototype); + + function SmallInteger(value) { + this.value = value; + this.sign = value < 0; + this.isSmall = true; + } + SmallInteger.prototype = Object.create(Integer.prototype); + + function NativeBigInt(value) { + this.value = value; + } + NativeBigInt.prototype = Object.create(Integer.prototype); + + function isPrecise(n) { + return -MAX_INT < n && n < MAX_INT; + } + + function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes + if (n < 1e7) + return [n]; + if (n < 1e14) + return [n % 1e7, Math.floor(n / 1e7)]; + return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)]; + } + + function arrayToSmall(arr) { // If BASE changes this function may need to change + trim(arr); + var length = arr.length; + if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) { + switch (length) { + case 0: return 0; + case 1: return arr[0]; + case 2: return arr[0] + arr[1] * BASE; + default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE; + } + } + return arr; + } + + function trim(v) { + var i = v.length; + while (v[--i] === 0); + v.length = i + 1; + } + + function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger + var x = new Array(length); + var i = -1; + while (++i < length) { + x[i] = 0; + } + return x; + } + + function truncate(n) { + if (n > 0) return Math.floor(n); + return Math.ceil(n); + } + + function add(a, b) { // assumes a and b are arrays with a.length >= b.length + var l_a = a.length, + l_b = b.length, + r = new Array(l_a), + carry = 0, + base = BASE, + sum, i; + for (i = 0; i < l_b; i++) { + sum = a[i] + b[i] + carry; + carry = sum >= base ? 1 : 0; + r[i] = sum - carry * base; + } + while (i < l_a) { + sum = a[i] + carry; + carry = sum === base ? 1 : 0; + r[i++] = sum - carry * base; + } + if (carry > 0) r.push(carry); + return r; + } + + function addAny(a, b) { + if (a.length >= b.length) return add(a, b); + return add(b, a); + } + + function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT + var l = a.length, + r = new Array(l), + base = BASE, + sum, i; + for (i = 0; i < l; i++) { + sum = a[i] - base + carry; + carry = Math.floor(sum / base); + r[i] = sum - carry * base; + carry += 1; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + BigInteger.prototype.add = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.subtract(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) { + return new BigInteger(addSmall(a, Math.abs(b)), this.sign); + } + return new BigInteger(addAny(a, b), this.sign); + }; + BigInteger.prototype.plus = BigInteger.prototype.add; + + SmallInteger.prototype.add = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.subtract(n.negate()); + } + var b = n.value; + if (n.isSmall) { + if (isPrecise(a + b)) return new SmallInteger(a + b); + b = smallToArray(Math.abs(b)); + } + return new BigInteger(addSmall(b, Math.abs(a)), a < 0); + }; + SmallInteger.prototype.plus = SmallInteger.prototype.add; + + NativeBigInt.prototype.add = function (v) { + return new NativeBigInt(this.value + parseValue(v).value); + }; + NativeBigInt.prototype.plus = NativeBigInt.prototype.add; + + function subtract(a, b) { // assumes a and b are arrays with a >= b + var a_l = a.length, + b_l = b.length, + r = new Array(a_l), + borrow = 0, + base = BASE, + i, difference; + for (i = 0; i < b_l; i++) { + difference = a[i] - borrow - b[i]; + if (difference < 0) { + difference += base; + borrow = 1; + } else borrow = 0; + r[i] = difference; + } + for (i = b_l; i < a_l; i++) { + difference = a[i] - borrow; + if (difference < 0) difference += base; + else { + r[i++] = difference; + break; + } + r[i] = difference; + } + for (; i < a_l; i++) { + r[i] = a[i]; + } + trim(r); + return r; + } + + function subtractAny(a, b, sign) { + var value; + if (compareAbs(a, b) >= 0) { + value = subtract(a, b); + } else { + value = subtract(b, a); + sign = !sign; + } + value = arrayToSmall(value); + if (typeof value === "number") { + if (sign) value = -value; + return new SmallInteger(value); + } + return new BigInteger(value, sign); + } + + function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT + var l = a.length, + r = new Array(l), + carry = -b, + base = BASE, + i, difference; + for (i = 0; i < l; i++) { + difference = a[i] + carry; + carry = Math.floor(difference / base); + difference %= base; + r[i] = difference < 0 ? difference + base : difference; + } + r = arrayToSmall(r); + if (typeof r === "number") { + if (sign) r = -r; + return new SmallInteger(r); + } return new BigInteger(r, sign); + } + + BigInteger.prototype.subtract = function (v) { + var n = parseValue(v); + if (this.sign !== n.sign) { + return this.add(n.negate()); + } + var a = this.value, b = n.value; + if (n.isSmall) + return subtractSmall(a, Math.abs(b), this.sign); + return subtractAny(a, b, this.sign); + }; + BigInteger.prototype.minus = BigInteger.prototype.subtract; + + SmallInteger.prototype.subtract = function (v) { + var n = parseValue(v); + var a = this.value; + if (a < 0 !== n.sign) { + return this.add(n.negate()); + } + var b = n.value; + if (n.isSmall) { + return new SmallInteger(a - b); + } + return subtractSmall(b, Math.abs(a), a >= 0); + }; + SmallInteger.prototype.minus = SmallInteger.prototype.subtract; + + NativeBigInt.prototype.subtract = function (v) { + return new NativeBigInt(this.value - parseValue(v).value); + }; + NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract; + + BigInteger.prototype.negate = function () { + return new BigInteger(this.value, !this.sign); + }; + SmallInteger.prototype.negate = function () { + var sign = this.sign; + var small = new SmallInteger(-this.value); + small.sign = !sign; + return small; + }; + NativeBigInt.prototype.negate = function () { + return new NativeBigInt(-this.value); + }; + + BigInteger.prototype.abs = function () { + return new BigInteger(this.value, false); + }; + SmallInteger.prototype.abs = function () { + return new SmallInteger(Math.abs(this.value)); + }; + NativeBigInt.prototype.abs = function () { + return new NativeBigInt(this.value >= 0 ? this.value : -this.value); + }; + + + function multiplyLong(a, b) { + var a_l = a.length, + b_l = b.length, + l = a_l + b_l, + r = createArray(l), + base = BASE, + product, carry, i, a_i, b_j; + for (i = 0; i < a_l; ++i) { + a_i = a[i]; + for (var j = 0; j < b_l; ++j) { + b_j = b[j]; + product = a_i * b_j + r[i + j]; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + r[i + j + 1] += carry; + } + } + trim(r); + return r; + } + + function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE + var l = a.length, + r = new Array(l), + base = BASE, + carry = 0, + product, i; + for (i = 0; i < l; i++) { + product = a[i] * b + carry; + carry = Math.floor(product / base); + r[i] = product - carry * base; + } + while (carry > 0) { + r[i++] = carry % base; + carry = Math.floor(carry / base); + } + return r; + } + + function shiftLeft(x, n) { + var r = []; + while (n-- > 0) r.push(0); + return r.concat(x); + } + + function multiplyKaratsuba(x, y) { + var n = Math.max(x.length, y.length); + + if (n <= 30) return multiplyLong(x, y); + n = Math.ceil(n / 2); + + var b = x.slice(n), + a = x.slice(0, n), + d = y.slice(n), + c = y.slice(0, n); + + var ac = multiplyKaratsuba(a, c), + bd = multiplyKaratsuba(b, d), + abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d)); + + var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n)); + trim(product); + return product; + } + + // The following function is derived from a surface fit of a graph plotting the performance difference + // between long multiplication and karatsuba multiplication versus the lengths of the two arrays. + function useKaratsuba(l1, l2) { + return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0; + } + + BigInteger.prototype.multiply = function (v) { + var n = parseValue(v), + a = this.value, b = n.value, + sign = this.sign !== n.sign, + abs; + if (n.isSmall) { + if (b === 0) return Integer[0]; + if (b === 1) return this; + if (b === -1) return this.negate(); + abs = Math.abs(b); + if (abs < BASE) { + return new BigInteger(multiplySmall(a, abs), sign); + } + b = smallToArray(abs); + } + if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes + return new BigInteger(multiplyKaratsuba(a, b), sign); + return new BigInteger(multiplyLong(a, b), sign); + }; + + BigInteger.prototype.times = BigInteger.prototype.multiply; + + function multiplySmallAndArray(a, b, sign) { // a >= 0 + if (a < BASE) { + return new BigInteger(multiplySmall(b, a), sign); + } + return new BigInteger(multiplyLong(b, smallToArray(a)), sign); + } + SmallInteger.prototype._multiplyBySmall = function (a) { + if (isPrecise(a.value * this.value)) { + return new SmallInteger(a.value * this.value); + } + return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign); + }; + BigInteger.prototype._multiplyBySmall = function (a) { + if (a.value === 0) return Integer[0]; + if (a.value === 1) return this; + if (a.value === -1) return this.negate(); + return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign); + }; + SmallInteger.prototype.multiply = function (v) { + return parseValue(v)._multiplyBySmall(this); + }; + SmallInteger.prototype.times = SmallInteger.prototype.multiply; + + NativeBigInt.prototype.multiply = function (v) { + return new NativeBigInt(this.value * parseValue(v).value); + }; + NativeBigInt.prototype.times = NativeBigInt.prototype.multiply; + + function square(a) { + //console.assert(2 * BASE * BASE < MAX_INT); + var l = a.length, + r = createArray(l + l), + base = BASE, + product, carry, i, a_i, a_j; + for (i = 0; i < l; i++) { + a_i = a[i]; + carry = 0 - a_i * a_i; + for (var j = i; j < l; j++) { + a_j = a[j]; + product = 2 * (a_i * a_j) + r[i + j] + carry; + carry = Math.floor(product / base); + r[i + j] = product - carry * base; + } + r[i + l] = carry; + } + trim(r); + return r; + } + + BigInteger.prototype.square = function () { + return new BigInteger(square(this.value), false); + }; + + SmallInteger.prototype.square = function () { + var value = this.value * this.value; + if (isPrecise(value)) return new SmallInteger(value); + return new BigInteger(square(smallToArray(Math.abs(this.value))), false); + }; + + NativeBigInt.prototype.square = function (v) { + return new NativeBigInt(this.value * this.value); + }; + + function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes. + var a_l = a.length, + b_l = b.length, + base = BASE, + result = createArray(b.length), + divisorMostSignificantDigit = b[b_l - 1], + // normalization + lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)), + remainder = multiplySmall(a, lambda), + divisor = multiplySmall(b, lambda), + quotientDigit, shift, carry, borrow, i, l, q; + if (remainder.length <= a_l) remainder.push(0); + divisor.push(0); + divisorMostSignificantDigit = divisor[b_l - 1]; + for (shift = a_l - b_l; shift >= 0; shift--) { + quotientDigit = base - 1; + if (remainder[shift + b_l] !== divisorMostSignificantDigit) { + quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit); + } + // quotientDigit <= base - 1 + carry = 0; + borrow = 0; + l = divisor.length; + for (i = 0; i < l; i++) { + carry += quotientDigit * divisor[i]; + q = Math.floor(carry / base); + borrow += remainder[shift + i] - (carry - q * base); + carry = q; + if (borrow < 0) { + remainder[shift + i] = borrow + base; + borrow = -1; + } else { + remainder[shift + i] = borrow; + borrow = 0; + } + } + while (borrow !== 0) { + quotientDigit -= 1; + carry = 0; + for (i = 0; i < l; i++) { + carry += remainder[shift + i] - base + divisor[i]; + if (carry < 0) { + remainder[shift + i] = carry + base; + carry = 0; + } else { + remainder[shift + i] = carry; + carry = 1; + } + } + borrow += carry; + } + result[shift] = quotientDigit; + } + // denormalization + remainder = divModSmall(remainder, lambda)[0]; + return [arrayToSmall(result), arrayToSmall(remainder)]; + } + + function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/ + // Performs faster than divMod1 on larger input sizes. + var a_l = a.length, + b_l = b.length, + result = [], + part = [], + base = BASE, + guess, xlen, highx, highy, check; + while (a_l) { + part.unshift(a[--a_l]); + trim(part); + if (compareAbs(part, b) < 0) { + result.push(0); + continue; + } + xlen = part.length; + highx = part[xlen - 1] * base + part[xlen - 2]; + highy = b[b_l - 1] * base + b[b_l - 2]; + if (xlen > b_l) { + highx = (highx + 1) * base; + } + guess = Math.ceil(highx / highy); + do { + check = multiplySmall(b, guess); + if (compareAbs(check, part) <= 0) break; + guess--; + } while (guess); + result.push(guess); + part = subtract(part, check); + } + result.reverse(); + return [arrayToSmall(result), arrayToSmall(part)]; + } + + function divModSmall(value, lambda) { + var length = value.length, + quotient = createArray(length), + base = BASE, + i, q, remainder, divisor; + remainder = 0; + for (i = length - 1; i >= 0; --i) { + divisor = remainder * base + value[i]; + q = truncate(divisor / lambda); + remainder = divisor - q * lambda; + quotient[i] = q | 0; + } + return [quotient, remainder | 0]; + } + + function divModAny(self, v) { + var value, n = parseValue(v); + if (supportsNativeBigInt) { + return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)]; + } + var a = self.value, b = n.value; + var quotient; + if (b === 0) throw new Error("Cannot divide by zero"); + if (self.isSmall) { + if (n.isSmall) { + return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)]; + } + return [Integer[0], self]; + } + if (n.isSmall) { + if (b === 1) return [self, Integer[0]]; + if (b == -1) return [self.negate(), Integer[0]]; + var abs = Math.abs(b); + if (abs < BASE) { + value = divModSmall(a, abs); + quotient = arrayToSmall(value[0]); + var remainder = value[1]; + if (self.sign) remainder = -remainder; + if (typeof quotient === "number") { + if (self.sign !== n.sign) quotient = -quotient; + return [new SmallInteger(quotient), new SmallInteger(remainder)]; + } + return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)]; + } + b = smallToArray(abs); + } + var comparison = compareAbs(a, b); + if (comparison === -1) return [Integer[0], self]; + if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]]; + + // divMod1 is faster on smaller input sizes + if (a.length + b.length <= 200) + value = divMod1(a, b); + else value = divMod2(a, b); + + quotient = value[0]; + var qSign = self.sign !== n.sign, + mod = value[1], + mSign = self.sign; + if (typeof quotient === "number") { + if (qSign) quotient = -quotient; + quotient = new SmallInteger(quotient); + } else quotient = new BigInteger(quotient, qSign); + if (typeof mod === "number") { + if (mSign) mod = -mod; + mod = new SmallInteger(mod); + } else mod = new BigInteger(mod, mSign); + return [quotient, mod]; + } + + BigInteger.prototype.divmod = function (v) { + var result = divModAny(this, v); + return { + quotient: result[0], + remainder: result[1] + }; + }; + NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod; + + + BigInteger.prototype.divide = function (v) { + return divModAny(this, v)[0]; + }; + NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) { + return new NativeBigInt(this.value / parseValue(v).value); + }; + SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide; + + BigInteger.prototype.mod = function (v) { + return divModAny(this, v)[1]; + }; + NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) { + return new NativeBigInt(this.value % parseValue(v).value); + }; + SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod; + + BigInteger.prototype.pow = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value, + value, x, y; + if (b === 0) return Integer[1]; + if (a === 0) return Integer[0]; + if (a === 1) return Integer[1]; + if (a === -1) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.sign) { + return Integer[0]; + } + if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large."); + if (this.isSmall) { + if (isPrecise(value = Math.pow(a, b))) + return new SmallInteger(truncate(value)); + } + x = this; + y = Integer[1]; + while (true) { + if (b & 1 === 1) { + y = y.times(x); + --b; + } + if (b === 0) break; + b /= 2; + x = x.square(); + } + return y; + }; + SmallInteger.prototype.pow = BigInteger.prototype.pow; + + NativeBigInt.prototype.pow = function (v) { + var n = parseValue(v); + var a = this.value, b = n.value; + var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2); + if (b === _0) return Integer[1]; + if (a === _0) return Integer[0]; + if (a === _1) return Integer[1]; + if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1]; + if (n.isNegative()) return new NativeBigInt(_0); + var x = this; + var y = Integer[1]; + while (true) { + if ((b & _1) === _1) { + y = y.times(x); + --b; + } + if (b === _0) break; + b /= _2; + x = x.square(); + } + return y; + }; + + BigInteger.prototype.modPow = function (exp, mod) { + exp = parseValue(exp); + mod = parseValue(mod); + if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0"); + var r = Integer[1], + base = this.mod(mod); + if (exp.isNegative()) { + exp = exp.multiply(Integer[-1]); + base = base.modInv(mod); + } + while (exp.isPositive()) { + if (base.isZero()) return Integer[0]; + if (exp.isOdd()) r = r.multiply(base).mod(mod); + exp = exp.divide(2); + base = base.square().mod(mod); + } + return r; + }; + NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow; + + function compareAbs(a, b) { + if (a.length !== b.length) { + return a.length > b.length ? 1 : -1; + } + for (var i = a.length - 1; i >= 0; i--) { + if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1; + } + return 0; + } + + BigInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) return 1; + return compareAbs(a, b); + }; + SmallInteger.prototype.compareAbs = function (v) { + var n = parseValue(v), + a = Math.abs(this.value), + b = n.value; + if (n.isSmall) { + b = Math.abs(b); + return a === b ? 0 : a > b ? 1 : -1; + } + return -1; + }; + NativeBigInt.prototype.compareAbs = function (v) { + var a = this.value; + var b = parseValue(v).value; + a = a >= 0 ? a : -a; + b = b >= 0 ? b : -b; + return a === b ? 0 : a > b ? 1 : -1; + }; + + BigInteger.prototype.compare = function (v) { + // See discussion about comparison with Infinity: + // https://github.com/peterolson/BigInteger.js/issues/61 + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (this.sign !== n.sign) { + return n.sign ? 1 : -1; + } + if (n.isSmall) { + return this.sign ? -1 : 1; + } + return compareAbs(a, b) * (this.sign ? -1 : 1); + }; + BigInteger.prototype.compareTo = BigInteger.prototype.compare; + + SmallInteger.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + + var n = parseValue(v), + a = this.value, + b = n.value; + if (n.isSmall) { + return a == b ? 0 : a > b ? 1 : -1; + } + if (a < 0 !== n.sign) { + return a < 0 ? -1 : 1; + } + return a < 0 ? 1 : -1; + }; + SmallInteger.prototype.compareTo = SmallInteger.prototype.compare; + + NativeBigInt.prototype.compare = function (v) { + if (v === Infinity) { + return -1; + } + if (v === -Infinity) { + return 1; + } + var a = this.value; + var b = parseValue(v).value; + return a === b ? 0 : a > b ? 1 : -1; + }; + NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare; + + BigInteger.prototype.equals = function (v) { + return this.compare(v) === 0; + }; + NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals; + + BigInteger.prototype.notEquals = function (v) { + return this.compare(v) !== 0; + }; + NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals; + + BigInteger.prototype.greater = function (v) { + return this.compare(v) > 0; + }; + NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater; + + BigInteger.prototype.lesser = function (v) { + return this.compare(v) < 0; + }; + NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser; + + BigInteger.prototype.greaterOrEquals = function (v) { + return this.compare(v) >= 0; + }; + NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals; + + BigInteger.prototype.lesserOrEquals = function (v) { + return this.compare(v) <= 0; + }; + NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals; + + BigInteger.prototype.isEven = function () { + return (this.value[0] & 1) === 0; + }; + SmallInteger.prototype.isEven = function () { + return (this.value & 1) === 0; + }; + NativeBigInt.prototype.isEven = function () { + return (this.value & BigInt(1)) === BigInt(0); + }; + + BigInteger.prototype.isOdd = function () { + return (this.value[0] & 1) === 1; + }; + SmallInteger.prototype.isOdd = function () { + return (this.value & 1) === 1; + }; + NativeBigInt.prototype.isOdd = function () { + return (this.value & BigInt(1)) === BigInt(1); + }; + + BigInteger.prototype.isPositive = function () { + return !this.sign; + }; + SmallInteger.prototype.isPositive = function () { + return this.value > 0; + }; + NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive; + + BigInteger.prototype.isNegative = function () { + return this.sign; + }; + SmallInteger.prototype.isNegative = function () { + return this.value < 0; + }; + NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative; + + BigInteger.prototype.isUnit = function () { + return false; + }; + SmallInteger.prototype.isUnit = function () { + return Math.abs(this.value) === 1; + }; + NativeBigInt.prototype.isUnit = function () { + return this.abs().value === BigInt(1); + }; + + BigInteger.prototype.isZero = function () { + return false; + }; + SmallInteger.prototype.isZero = function () { + return this.value === 0; + }; + NativeBigInt.prototype.isZero = function () { + return this.value === BigInt(0); + }; + + BigInteger.prototype.isDivisibleBy = function (v) { + var n = parseValue(v); + if (n.isZero()) return false; + if (n.isUnit()) return true; + if (n.compareAbs(2) === 0) return this.isEven(); + return this.mod(n).isZero(); + }; + NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy; + + function isBasicPrime(v) { + var n = v.abs(); + if (n.isUnit()) return false; + if (n.equals(2) || n.equals(3) || n.equals(5)) return true; + if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false; + if (n.lesser(49)) return true; + // we don't know if it's prime: let the other functions figure it out + } + + function millerRabinTest(n, a) { + var nPrev = n.prev(), + b = nPrev, + r = 0, + d, i, x; + while (b.isEven()) b = b.divide(2), r++; + next: for (i = 0; i < a.length; i++) { + if (n.lesser(a[i])) continue; + x = bigInt(a[i]).modPow(b, n); + if (x.isUnit() || x.equals(nPrev)) continue; + for (d = r - 1; d != 0; d--) { + x = x.square().mod(n); + if (x.isUnit()) return false; + if (x.equals(nPrev)) continue next; + } + return false; + } + return true; + } + + // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2 + BigInteger.prototype.isPrime = function (strict) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var bits = n.bitLength(); + if (bits <= 64) + return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]); + var logN = Math.log(2) * bits.toJSNumber(); + var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN); + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt(i + 2)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime; + + BigInteger.prototype.isProbablePrime = function (iterations, rng) { + var isPrime = isBasicPrime(this); + if (isPrime !== undefined$1) return isPrime; + var n = this.abs(); + var t = iterations === undefined$1 ? 5 : iterations; + for (var a = [], i = 0; i < t; i++) { + a.push(bigInt.randBetween(2, n.minus(2), rng)); + } + return millerRabinTest(n, a); + }; + NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime; + + BigInteger.prototype.modInv = function (n) { + var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR; + while (!newR.isZero()) { + q = r.divide(newR); + lastT = t; + lastR = r; + t = newT; + r = newR; + newT = lastT.subtract(q.multiply(newT)); + newR = lastR.subtract(q.multiply(newR)); + } + if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime"); + if (t.compare(0) === -1) { + t = t.add(n); + } + if (this.isNegative()) { + return t.negate(); + } + return t; + }; + + NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv; + + BigInteger.prototype.next = function () { + var value = this.value; + if (this.sign) { + return subtractSmall(value, 1, this.sign); + } + return new BigInteger(addSmall(value, 1), this.sign); + }; + SmallInteger.prototype.next = function () { + var value = this.value; + if (value + 1 < MAX_INT) return new SmallInteger(value + 1); + return new BigInteger(MAX_INT_ARR, false); + }; + NativeBigInt.prototype.next = function () { + return new NativeBigInt(this.value + BigInt(1)); + }; + + BigInteger.prototype.prev = function () { + var value = this.value; + if (this.sign) { + return new BigInteger(addSmall(value, 1), true); + } + return subtractSmall(value, 1, this.sign); + }; + SmallInteger.prototype.prev = function () { + var value = this.value; + if (value - 1 > -MAX_INT) return new SmallInteger(value - 1); + return new BigInteger(MAX_INT_ARR, true); + }; + NativeBigInt.prototype.prev = function () { + return new NativeBigInt(this.value - BigInt(1)); + }; + + var powersOfTwo = [1]; + while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]); + var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1]; + + function shift_isSmall(n) { + return Math.abs(n) <= BASE; + } + + BigInteger.prototype.shiftLeft = function (v) { + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftRight(-n); + var result = this; + if (result.isZero()) return result; + while (n >= powers2Length) { + result = result.multiply(highestPower2); + n -= powers2Length - 1; + } + return result.multiply(powersOfTwo[n]); + }; + NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft; + + BigInteger.prototype.shiftRight = function (v) { + var remQuo; + var n = parseValue(v).toJSNumber(); + if (!shift_isSmall(n)) { + throw new Error(String(n) + " is too large for shifting."); + } + if (n < 0) return this.shiftLeft(-n); + var result = this; + while (n >= powers2Length) { + if (result.isZero() || (result.isNegative() && result.isUnit())) return result; + remQuo = divModAny(result, highestPower2); + result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + n -= powers2Length - 1; + } + remQuo = divModAny(result, powersOfTwo[n]); + return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0]; + }; + NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight; + + function bitwise(x, y, fn) { + y = parseValue(y); + var xSign = x.isNegative(), ySign = y.isNegative(); + var xRem = xSign ? x.not() : x, + yRem = ySign ? y.not() : y; + var xDigit = 0, yDigit = 0; + var xDivMod = null, yDivMod = null; + var result = []; + while (!xRem.isZero() || !yRem.isZero()) { + xDivMod = divModAny(xRem, highestPower2); + xDigit = xDivMod[1].toJSNumber(); + if (xSign) { + xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers + } + + yDivMod = divModAny(yRem, highestPower2); + yDigit = yDivMod[1].toJSNumber(); + if (ySign) { + yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers + } + + xRem = xDivMod[0]; + yRem = yDivMod[0]; + result.push(fn(xDigit, yDigit)); + } + var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0); + for (var i = result.length - 1; i >= 0; i -= 1) { + sum = sum.multiply(highestPower2).add(bigInt(result[i])); + } + return sum; + } + + BigInteger.prototype.not = function () { + return this.negate().prev(); + }; + NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not; + + BigInteger.prototype.and = function (n) { + return bitwise(this, n, function (a, b) { return a & b; }); + }; + NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and; + + BigInteger.prototype.or = function (n) { + return bitwise(this, n, function (a, b) { return a | b; }); + }; + NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or; + + BigInteger.prototype.xor = function (n) { + return bitwise(this, n, function (a, b) { return a ^ b; }); + }; + NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor; + + var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I; + function roughLOB(n) { // get lowestOneBit (rough) + // SmallInteger: return Min(lowestOneBit(n), 1 << 30) + // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7] + var v = n.value, + x = typeof v === "number" ? v | LOBMASK_I : + typeof v === "bigint" ? v | BigInt(LOBMASK_I) : + v[0] + v[1] * BASE | LOBMASK_BI; + return x & -x; + } + + function integerLogarithm(value, base) { + if (base.compareTo(value) <= 0) { + var tmp = integerLogarithm(value, base.square(base)); + var p = tmp.p; + var e = tmp.e; + var t = p.multiply(base); + return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 }; + } + return { p: bigInt(1), e: 0 }; + } + + BigInteger.prototype.bitLength = function () { + var n = this; + if (n.compareTo(bigInt(0)) < 0) { + n = n.negate().subtract(bigInt(1)); + } + if (n.compareTo(bigInt(0)) === 0) { + return bigInt(0); + } + return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1)); + }; + NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength; + + function max(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.greater(b) ? a : b; + } + function min(a, b) { + a = parseValue(a); + b = parseValue(b); + return a.lesser(b) ? a : b; + } + function gcd(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + if (a.equals(b)) return a; + if (a.isZero()) return b; + if (b.isZero()) return a; + var c = Integer[1], d, t; + while (a.isEven() && b.isEven()) { + d = min(roughLOB(a), roughLOB(b)); + a = a.divide(d); + b = b.divide(d); + c = c.multiply(d); + } + while (a.isEven()) { + a = a.divide(roughLOB(a)); + } + do { + while (b.isEven()) { + b = b.divide(roughLOB(b)); + } + if (a.greater(b)) { + t = b; b = a; a = t; + } + b = b.subtract(a); + } while (!b.isZero()); + return c.isUnit() ? a : a.multiply(c); + } + function lcm(a, b) { + a = parseValue(a).abs(); + b = parseValue(b).abs(); + return a.divide(gcd(a, b)).multiply(b); + } + function randBetween(a, b, rng) { + a = parseValue(a); + b = parseValue(b); + var usedRNG = rng || Math.random; + var low = min(a, b), high = max(a, b); + var range = high.subtract(low).add(1); + if (range.isSmall) return low.add(Math.floor(usedRNG() * range)); + var digits = toBase(range, BASE).value; + var result = [], restricted = true; + for (var i = 0; i < digits.length; i++) { + var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE; + var digit = truncate(usedRNG() * top); + result.push(digit); + if (digit < digits[i]) restricted = false; + } + return low.add(Integer.fromArray(result, BASE, false)); + } + + var parseBase = function (text, base, alphabet, caseSensitive) { + alphabet = alphabet || DEFAULT_ALPHABET; + text = String(text); + if (!caseSensitive) { + text = text.toLowerCase(); + alphabet = alphabet.toLowerCase(); + } + var length = text.length; + var i; + var absBase = Math.abs(base); + var alphabetValues = {}; + for (i = 0; i < alphabet.length; i++) { + alphabetValues[alphabet[i]] = i; + } + for (i = 0; i < length; i++) { + var c = text[i]; + if (c === "-") continue; + if (c in alphabetValues) { + if (alphabetValues[c] >= absBase) { + if (c === "1" && absBase === 1) continue; + throw new Error(c + " is not a valid digit in base " + base + "."); + } + } + } + base = parseValue(base); + var digits = []; + var isNegative = text[0] === "-"; + for (i = isNegative ? 1 : 0; i < text.length; i++) { + var c = text[i]; + if (c in alphabetValues) digits.push(parseValue(alphabetValues[c])); + else if (c === "<") { + var start = i; + do { i++; } while (text[i] !== ">" && i < text.length); + digits.push(parseValue(text.slice(start + 1, i))); + } + else throw new Error(c + " is not a valid character"); + } + return parseBaseFromArray(digits, base, isNegative); + }; + + function parseBaseFromArray(digits, base, isNegative) { + var val = Integer[0], pow = Integer[1], i; + for (i = digits.length - 1; i >= 0; i--) { + val = val.add(digits[i].times(pow)); + pow = pow.times(base); + } + return isNegative ? val.negate() : val; + } + + function stringify(digit, alphabet) { + alphabet = alphabet || DEFAULT_ALPHABET; + if (digit < alphabet.length) { + return alphabet[digit]; + } + return "<" + digit + ">"; + } + + function toBase(n, base) { + base = bigInt(base); + if (base.isZero()) { + if (n.isZero()) return { value: [0], isNegative: false }; + throw new Error("Cannot convert nonzero numbers to base 0."); + } + if (base.equals(-1)) { + if (n.isZero()) return { value: [0], isNegative: false }; + if (n.isNegative()) + return { + value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber())) + .map(Array.prototype.valueOf, [1, 0]) + ), + isNegative: false + }; + + var arr = Array.apply(null, Array(n.toJSNumber() - 1)) + .map(Array.prototype.valueOf, [0, 1]); + arr.unshift([1]); + return { + value: [].concat.apply([], arr), + isNegative: false + }; + } + + var neg = false; + if (n.isNegative() && base.isPositive()) { + neg = true; + n = n.abs(); + } + if (base.isUnit()) { + if (n.isZero()) return { value: [0], isNegative: false }; + + return { + value: Array.apply(null, Array(n.toJSNumber())) + .map(Number.prototype.valueOf, 1), + isNegative: neg + }; + } + var out = []; + var left = n, divmod; + while (left.isNegative() || left.compareAbs(base) >= 0) { + divmod = left.divmod(base); + left = divmod.quotient; + var digit = divmod.remainder; + if (digit.isNegative()) { + digit = base.minus(digit).abs(); + left = left.next(); + } + out.push(digit.toJSNumber()); + } + out.push(left.toJSNumber()); + return { value: out.reverse(), isNegative: neg }; + } + + function toBaseString(n, base, alphabet) { + var arr = toBase(n, base); + return (arr.isNegative ? "-" : "") + arr.value.map(function (x) { + return stringify(x, alphabet); + }).join(''); + } + + BigInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + SmallInteger.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + NativeBigInt.prototype.toArray = function (radix) { + return toBase(this, radix); + }; + + BigInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix !== 10 || alphabet) return toBaseString(this, radix, alphabet); + var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit; + while (--l >= 0) { + digit = String(v[l]); + str += zeros.slice(digit.length) + digit; + } + var sign = this.sign ? "-" : ""; + return sign + str; + }; + + SmallInteger.prototype.toString = function (radix, alphabet) { + if (radix === undefined$1) radix = 10; + if (radix != 10 || alphabet) return toBaseString(this, radix, alphabet); + return String(this.value); + }; + + NativeBigInt.prototype.toString = SmallInteger.prototype.toString; + + NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }; + + BigInteger.prototype.valueOf = function () { + return parseInt(this.toString(), 10); + }; + BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf; + + SmallInteger.prototype.valueOf = function () { + return this.value; + }; + SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf; + NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () { + return parseInt(this.toString(), 10); + }; + + function parseStringValue(v) { + if (isPrecise(+v)) { + var x = +v; + if (x === truncate(x)) + return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x); + throw new Error("Invalid integer: " + v); + } + var sign = v[0] === "-"; + if (sign) v = v.slice(1); + var split = v.split(/e/i); + if (split.length > 2) throw new Error("Invalid integer: " + split.join("e")); + if (split.length === 2) { + var exp = split[1]; + if (exp[0] === "+") exp = exp.slice(1); + exp = +exp; + if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent."); + var text = split[0]; + var decimalPlace = text.indexOf("."); + if (decimalPlace >= 0) { + exp -= text.length - decimalPlace - 1; + text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1); + } + if (exp < 0) throw new Error("Cannot include negative exponent part for integers"); + text += (new Array(exp + 1)).join("0"); + v = text; + } + var isValid = /^([0-9][0-9]*)$/.test(v); + if (!isValid) throw new Error("Invalid integer: " + v); + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(sign ? "-" + v : v)); + } + var r = [], max = v.length, l = LOG_BASE, min = max - l; + while (max > 0) { + r.push(+v.slice(min, max)); + min -= l; + if (min < 0) min = 0; + max -= l; + } + trim(r); + return new BigInteger(r, sign); + } + + function parseNumberValue(v) { + if (supportsNativeBigInt) { + return new NativeBigInt(BigInt(v)); + } + if (isPrecise(v)) { + if (v !== truncate(v)) throw new Error(v + " is not an integer."); + return new SmallInteger(v); + } + return parseStringValue(v.toString()); + } + + function parseValue(v) { + if (typeof v === "number") { + return parseNumberValue(v); + } + if (typeof v === "string") { + return parseStringValue(v); + } + if (typeof v === "bigint") { + return new NativeBigInt(v); + } + return v; + } + // Pre-define numbers in range [-999,999] + for (var i = 0; i < 1000; i++) { + Integer[i] = parseValue(i); + if (i > 0) Integer[-i] = parseValue(-i); + } + // Backwards compatibility + Integer.one = Integer[1]; + Integer.zero = Integer[0]; + Integer.minusOne = Integer[-1]; + Integer.max = max; + Integer.min = min; + Integer.gcd = gcd; + Integer.lcm = lcm; + Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; }; + Integer.randBetween = randBetween; + + Integer.fromArray = function (digits, base, isNegative) { + return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative); + }; + + return Integer; + })(); + + // Node.js check + if (module.hasOwnProperty("exports")) { + module.exports = bigInt; + } + } (BigInteger)); + return BigInteger.exports; +} + +var hasRequiredFunctionUtils_internal; + +function requireFunctionUtils_internal () { + if (hasRequiredFunctionUtils_internal) return functionUtils_internal; + hasRequiredFunctionUtils_internal = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (functionUtils_internal && functionUtils_internal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(functionUtils_internal, "__esModule", { value: true }); + functionUtils_internal.InternalFunctionUtils = void 0; + const constant_1 = requireConstant(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionType_1 = requireExpressionType(); + const memory_1 = requireMemory(); + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + const big_integer_1 = __importDefault(requireBigInteger()); + const util_1 = __importDefault(require$$6); + /** + * Utility functions only used internal + */ + class InternalFunctionUtils { + /** + * Parse timex funcition. + * + * @param timexExpr String or TimexProperty input. + * @returns TimexProperty and error. + */ + static parseTimexProperty(timexExpr) { + let parsed; + if (timexExpr instanceof recognizers_text_data_types_timex_expression_1.TimexProperty) { + parsed = timexExpr; + } + else if (typeof timexExpr === 'string') { + parsed = new recognizers_text_data_types_timex_expression_1.TimexProperty(timexExpr); + } + else { + parsed = new recognizers_text_data_types_timex_expression_1.TimexProperty(timexExpr); + if (parsed === undefined || Object.keys(parsed).length === 0) { + return { + timexProperty: parsed, + error: `${timexExpr} requires a TimexProperty or a string as a argument`, + }; + } + } + return { timexProperty: parsed, error: undefined }; + } + /** + * Sort helper function. + * + * @param isDescending Descending flag. + * @returns The sorted array. + */ + static sortBy(isDescending) { + return (expression, state, options) => { + let result; + const { value: oriArr, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (Array.isArray(oriArr)) { + // Ensures we don't mutate the array in place. + const arr = oriArr.slice(0); + if (expression.children.length === 1) { + if (isDescending) { + result = arr.sort().reverse(); + } + else { + result = arr.sort(); + } + } + else { + let propertyName; + ({ value: propertyName, error } = expression.children[1].tryEvaluate(state, options)); + if (!error) { + propertyName = propertyName || ''; + } + if (isDescending) { + result = arr.sort(InternalFunctionUtils.sortByKey(propertyName)).reverse(); + } + else { + result = arr.sort(InternalFunctionUtils.sortByKey(propertyName)); + } + } + } + else { + error = `${expression.children[0]} is not an array`; + } + } + return { value: result, error }; + }; + } + /** + * Lookup a string or number index of an Object. + * + * @param instance Instance with property. + * @param index Property to lookup. + * @returns Value and error information if any. + */ + static accessIndex(instance, index) { + // NOTE: This returns undefined rather than an error if instance is not present + if (instance == null) { + return { value: undefined, error: undefined }; + } + let value; + let error; + if (Array.isArray(instance)) { + if (index >= 0 && index < instance.length) { + value = instance[index]; + } + else { + error = `${index} is out of range for ${instance}`; + } + } + else { + error = `${instance} is not a collection.`; + } + return { value, error }; + } + /** + * Verify a timestamp string is valid timestamp format. + * + * @param value Timestamp string to check. + * @returns Error or undefined if invalid. + */ + static verifyTimestamp(value) { + let error; + try { + const parsedData = new Date(value); + if (Number.isNaN(parsedData.getTime())) { + error = `${value} is not a valid datetime string.`; + } + } + catch (_a) { + error = `${value} is not a valid datetime string.`; + } + return error; + } + /** + * Verify a timestamp string is valid ISO timestamp format. + * + * @param value Timestamp string to check. + * @returns Error or undefined if invalid. + */ + static verifyISOTimestamp(value) { + let error; + try { + const parsedData = new Date(value); + if (Number.isNaN(parsedData.getTime())) { + error = `${value} is not a valid datetime string.`; + } + else if (parsedData.toISOString() !== value) { + error = `${value} is not a ISO format datetime string.`; + } + } + catch (_a) { + error = `${value} is not a valid datetime string.`; + } + return error; + } + /** + * Convert a string input to ticks number. + * + * @param timeStamp String timestamp input. + * @returns The string converted in ticks. + */ + static ticks(timeStamp) { + let result; + const error = this.verifyISOTimestamp(timeStamp); + if (!error) { + const unixMilliSec = (0, dayjs_1.default)(timeStamp).utc().valueOf(); + result = this.UnixMilliSecondToTicksConstant.add((0, big_integer_1.default)(unixMilliSec).times(this.MillisecondToTickConstant)); + } + return { value: result, error }; + } + /** + * Lookup a property in Map or Object. + * + * @param instance Instance with property. + * @param property Property to lookup. + * @returns Value and error information if any. + */ + static accessProperty(instance, property) { + // NOTE: This returns undefined rather than an error if property is not present + if (!instance) { + return { value: undefined, error: undefined }; + } + let value; + let error; + if (instance instanceof Map && instance !== undefined) { + const instanceMap = instance; + value = instanceMap.get(property); + if (value === undefined) { + const prop = Array.from(instanceMap.keys()).find((k) => k.toLowerCase() === property.toLowerCase()); + if (prop !== undefined) { + value = instanceMap.get(prop); + } + } + } + else { + const prop = Object.keys(instance).find((k) => k.toLowerCase() === property.toLowerCase()); + if (prop !== undefined) { + value = instance[prop]; + } + } + return { value, error }; + } + /** + * Get the value of a path from a memory. + * + * @param state Memory. + * @param path Path string. + * @param options Options. + * @returns The value of a path from a memory. + */ + static wrapGetValue(state, path, options) { + const result = state.getValue(path); + if (result !== undefined) { + return result; + } + if (options.nullSubstitution !== undefined) { + return options.nullSubstitution(path); + } + return undefined; + } + /** + * Wrap string or undefined into string. Default to empty string. + * + * @param input Input string + * @returns The wrapped string. + */ + static parseStringOrUndefined(input) { + if (typeof input === 'string') { + return input; + } + else { + return ''; + } + } + /** + * Test result to see if True in logical comparison functions. + * + * @param instance Computed value. + * @returns True if boolean true or non-null. + */ + static isLogicTrue(instance) { + let result = true; + if (typeof instance === 'boolean') { + result = instance; + } + else if (instance == null) { + result = false; + } + return result; + } + /** + * Evaluator for foreach and select functions. + * + * @param expression Expression. + * @param state Memory scope. + * @param options Options. + * @returns The evaluated list. + */ + static foreach(expression, state, options) { + let result; + const { value: instance, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!instance) { + error = `'${expression.children[0]}' evaluated to null.`; + } + if (!error) { + const list = InternalFunctionUtils.convertToList(instance); + if (!list) { + error = `${expression.children[0]} is not a collection or structure object to run Foreach`; + } + else { + result = []; + InternalFunctionUtils.lambdaEvaluator(expression, state, options, list, (currentItem, r, e) => { + if (e) { + error = e; + return true; + } + else { + result.push(r); + return false; + } + }); + } + } + return { value: result, error }; + } + /** + * Lambda evaluator. + * + * @param expression expression. + * @param state memory state. + * @param options options. + * @param list item list. + * @param callback call back. return the should break flag. + */ + static lambdaEvaluator(expression, state, options, list, callback) { + const firstChild = expression.children[1].children[0]; + if (!(firstChild instanceof constant_1.Constant) || typeof firstChild.value !== 'string') { + return; + } + const iteratorName = firstChild.value; + const stackedMemory = memory_1.StackedMemory.wrap(state); + for (const item of list) { + const currentItem = item; + const local = new Map([[iteratorName, item]]); + // the local iterator is pushed as one memory layer in the memory stack + stackedMemory.push(memory_1.SimpleObjectMemory.wrap(local)); + const { value: r, error: e } = expression.children[2].tryEvaluate(stackedMemory, options); + stackedMemory.pop(); + const shouldBreak = callback(currentItem, r, e); + if (shouldBreak) { + break; + } + } + } + /** + * Convert an object into array. + * If the instance is array, return itself. + * If the instance is object, return {key, value} pair list. + * Else return undefined. + * + * @param instance input instance. + * @returns The generated list. + */ + static convertToList(instance) { + let arr; + if (Array.isArray(instance)) { + arr = instance; + } + else if (typeof instance === 'object') { + arr = []; + Object.keys(instance).forEach((u) => arr.push({ key: u, value: instance[u] })); + } + return arr; + } + /** + * Validator for foreach, select, and where functions. + * + * @param expression The expression to validate. + */ + static ValidateLambdaExpression(expression) { + if (expression.children.length !== 3) { + throw new Error(`Lambda expression expect 3 parameters, found ${expression.children.length}`); + } + const second = expression.children[1]; + if (!(second.type === expressionType_1.ExpressionType.Accessor && second.children.length === 1)) { + throw new Error(`Second parameter is not an identifier : ${second}`); + } + } + /** + * Parse string into URL object. + * + * @param uri Input string uri. + * @returns The parsed URL object. + */ + static parseUri(uri) { + let result; + let error; + try { + result = new URL(uri); + } + catch (_a) { + error = `Invalid URI: ${uri}`; + } + return { value: result, error }; + } + /** + * Transform C# period and unit into js period and unit. + * + * @param duration C# duration. + * @param cSharpStr C# unit. + * @returns The transformed timeUnit. + */ + static timeUnitTransformer(duration, cSharpStr) { + switch (cSharpStr) { + case 'Day': + return { duration, tsStr: 'day' }; + case 'Week': + return { duration: duration * 7, tsStr: 'day' }; + case 'Second': + return { duration, tsStr: 'second' }; + case 'Minute': + return { duration, tsStr: 'minute' }; + case 'Hour': + return { duration, tsStr: 'hour' }; + case 'Month': + return { duration, tsStr: 'month' }; + case 'Year': + return { duration, tsStr: 'year' }; + default: + return { duration, tsStr: undefined }; + } + } + /** + * TextEncoder helper function. + * + * @returns The text encoder. + */ + static getTextEncoder() { + if (typeof window !== 'undefined' || typeof self !== 'undefined') { + return new TextEncoder(); + } + return new util_1.default.TextEncoder(); + } + /** + * TextDecoder helper function. + * + * @param code The encoding format. + * @returns The text decoder. + */ + static getTextDecoder(code = 'utf-8') { + if (typeof window !== 'undefined' || typeof self !== 'undefined') { + return new TextDecoder(code); + } + return new util_1.default.TextDecoder(code); + } + /** + * Common Stringify an object. + * + * @param input input object. + * @returns the stringified object. + */ + static commonStringify(input) { + if (input == null) { + return ''; + } + if (typeof input === 'object') { + return JSON.stringify(input) + .replace(/(^['"]*)/g, '') + .replace(/(['"]*$)/g, ''); + } + else { + return input.toString(); + } + } + /** + * @private + */ + static sortByKey(key) { + return (a, b) => (a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0); + } + } + functionUtils_internal.InternalFunctionUtils = InternalFunctionUtils; + /** + * Constant for converting unix timestamp to ticks. + */ + InternalFunctionUtils.UnixMilliSecondToTicksConstant = (0, big_integer_1.default)('621355968000000000'); + /** + * Constant to convert between ticks and ms. + */ + InternalFunctionUtils.MillisecondToTickConstant = (0, big_integer_1.default)('10000'); + + return functionUtils_internal; +} + +var hasRequiredAccessor; + +function requireAccessor () { + if (hasRequiredAccessor) return accessor; + hasRequiredAccessor = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(accessor, "__esModule", { value: true }); + accessor.Accessor = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const simpleObjectMemory_1 = requireSimpleObjectMemory(); + const returnType_1 = requireReturnType(); + /** + * Used to access the variable value corresponding to the path. + */ + class Accessor extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Accessor](xref:adaptive-expressions.Accessor) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Accessor, Accessor.evaluator, returnType_1.ReturnType.Object, Accessor.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + const { path, left, error } = functionUtils_1.FunctionUtils.tryAccumulatePath(expression, state, options); + if (error) { + return { value: undefined, error }; + } + if (left == null) { + // fully converted to path, so we just delegate to memory scope + return { value: functionUtils_internal_1.InternalFunctionUtils.wrapGetValue(state, path, options), error: undefined }; + } + else { + const { value: newScope, error: err } = left.tryEvaluate(state, options); + if (err) { + return { value: undefined, error: err }; + } + return { + value: functionUtils_internal_1.InternalFunctionUtils.wrapGetValue(new simpleObjectMemory_1.SimpleObjectMemory(newScope), path, options), + error: undefined, + }; + } + } + /** + * @private + */ + static validator(expression) { + const children = expression.children; + if (children.length === 0 || + children[0].type !== expressionType_1.ExpressionType.Constant || + children[0].returnType !== returnType_1.ReturnType.String) { + throw new Error(`${expression} must have a string as first argument.`); + } + if (children.length > 2) { + throw new Error(`${expression} has more than 2 children.`); + } + if (children.length === 2 && (children[1].returnType & returnType_1.ReturnType.Object) === 0) { + throw new Error(`${expression} must have an object as its second argument.`); + } + } + } + accessor.Accessor = Accessor; + + return accessor; +} + +var add = {}; + +var hasRequiredAdd; + +function requireAdd () { + if (hasRequiredAdd) return add; + hasRequiredAdd = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(add, "__esModule", { value: true }); + add.Add = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the result from adding two or more numbers (pure number case) or concatting two or more strings (other case). + */ + class Add extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Add](xref:adaptive-expressions.Add) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Add, Add.evaluator(), returnType_1.ReturnType.String | returnType_1.ReturnType.Number, Add.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applySequenceWithError((args) => { + let value; + let error; + const stringConcat = !functionUtils_1.FunctionUtils.isNumber(args[0]) || !functionUtils_1.FunctionUtils.isNumber(args[1]); + if ((args[0] == null && functionUtils_1.FunctionUtils.isNumber(args[1])) || + (args[1] == null && functionUtils_1.FunctionUtils.isNumber(args[0]))) { + error = "Operator '+' or add cannot be applied to operands of type 'number' and null object."; + } + else if (stringConcat) { + if (args[0] == null && args[1] == null) { + value = ''; + } + else if (args[0] == null) { + value = args[1].toString(); + } + else if (args[1] == null) { + value = args[0].toString(); + } + else { + value = args[0].toString() + args[1].toString(); + } + } + else { + value = args[0] + args[1]; + } + return { value, error }; + }, functionUtils_1.FunctionUtils.verifyNumberOrStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 2, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.String | returnType_1.ReturnType.Number); + } + } + add.Add = Add; + + return add; +} + +var addDays = {}; + +var timeTransformEvaluator = {}; + +var hasRequiredTimeTransformEvaluator; + +function requireTimeTransformEvaluator () { + if (hasRequiredTimeTransformEvaluator) return timeTransformEvaluator; + hasRequiredTimeTransformEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (timeTransformEvaluator && timeTransformEvaluator.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(timeTransformEvaluator, "__esModule", { value: true }); + timeTransformEvaluator.TimeTransformEvaluator = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Evaluator that transforms a datetime to another datetime. + */ + class TimeTransformEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [TimeTransformEvaluator](xref:adaptive-expressions.TimeTransformEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The evaluation function, it takes a timestamp and the number of transformation, and returns a `Date`. + */ + constructor(type, func) { + super(type, TimeTransformEvaluator.evaluator(func), returnType_1.ReturnType.String, TimeTransformEvaluator.validator); + } + /** + * @private + */ + static evaluator(func) { + return (expression, state, options) => { + let result; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 4, format, locale)); + if (typeof args[0] === 'string' && functionUtils_1.FunctionUtils.isNumber(args[1])) { + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + result = (0, dayjs_1.default)(func(new Date(args[0]), args[1])) + .locale(locale) + .utc() + .format(format); + } + } + else { + error = `${expression} should contain an ISO format timestamp and a time interval integer.`; + } + } + return { value: result, error }; + }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String, returnType_1.ReturnType.Number); + } + } + timeTransformEvaluator.TimeTransformEvaluator = TimeTransformEvaluator; + + return timeTransformEvaluator; +} + +var hasRequiredAddDays; + +function requireAddDays () { + if (hasRequiredAddDays) return addDays; + hasRequiredAddDays = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addDays, "__esModule", { value: true }); + addDays.AddDays = void 0; + const expressionType_1 = requireExpressionType(); + const timeTransformEvaluator_1 = requireTimeTransformEvaluator(); + /** + * Add a number of days to a timestamp. + */ + class AddDays extends timeTransformEvaluator_1.TimeTransformEvaluator { + /** + * Initializes a new instance of the [AddDays](xref:adaptive-expressions.AddDays) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddDays, (ts, num) => { + const newDate = new Date(ts); + newDate.setDate(ts.getDate() + num); + return newDate; + }); + } + } + addDays.AddDays = AddDays; + + return addDays; +} + +var addHours = {}; + +var hasRequiredAddHours; + +function requireAddHours () { + if (hasRequiredAddHours) return addHours; + hasRequiredAddHours = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addHours, "__esModule", { value: true }); + addHours.AddHours = void 0; + const expressionType_1 = requireExpressionType(); + const timeTransformEvaluator_1 = requireTimeTransformEvaluator(); + /** + * Add a number of hours to a timestamp. + */ + class AddHours extends timeTransformEvaluator_1.TimeTransformEvaluator { + /** + * Initializes a new instance of the [AddHours](xref:adaptive-expressions.AddHours) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddHours, (ts, num) => { + const newDate = new Date(ts); + newDate.setHours(ts.getHours() + num); + return newDate; + }); + } + } + addHours.AddHours = AddHours; + + return addHours; +} + +var addMinutes = {}; + +var hasRequiredAddMinutes; + +function requireAddMinutes () { + if (hasRequiredAddMinutes) return addMinutes; + hasRequiredAddMinutes = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addMinutes, "__esModule", { value: true }); + addMinutes.AddMinutes = void 0; + const expressionType_1 = requireExpressionType(); + const timeTransformEvaluator_1 = requireTimeTransformEvaluator(); + /** + * Add a number of minutes to a timestamp. + */ + class AddMinutes extends timeTransformEvaluator_1.TimeTransformEvaluator { + /** + * Initializes a new instance of the [AddMinutes](xref:adaptive-expressions.AddMinutes) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddMinutes, (ts, num) => { + const newDate = new Date(ts); + newDate.setMinutes(ts.getMinutes() + num); + return newDate; + }); + } + } + addMinutes.AddMinutes = AddMinutes; + + return addMinutes; +} + +var addOrdinal = {}; + +var hasRequiredAddOrdinal; + +function requireAddOrdinal () { + if (hasRequiredAddOrdinal) return addOrdinal; + hasRequiredAddOrdinal = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addOrdinal, "__esModule", { value: true }); + addOrdinal.AddOrdinal = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the ordinal number of the input number. + */ + class AddOrdinal extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [AddOrdinal](xref:adaptive-expressions.AddOrdinal) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddOrdinal, AddOrdinal.evaluator(), returnType_1.ReturnType.String, AddOrdinal.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => AddOrdinal.evalAddOrdinal(args[0]), functionUtils_1.FunctionUtils.verifyInteger); + } + /** + * @private + */ + static evalAddOrdinal(num) { + let hasResult = false; + let ordinalResult = num.toString(); + if (num > 0) { + switch (num % 100) { + case 11: + case 12: + case 13: + ordinalResult += 'th'; + hasResult = true; + break; + } + if (!hasResult) { + switch (num % 10) { + case 1: + ordinalResult += 'st'; + break; + case 2: + ordinalResult += 'nd'; + break; + case 3: + ordinalResult += 'rd'; + break; + default: + ordinalResult += 'th'; + break; + } + } + } + return ordinalResult; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.Number); + } + } + addOrdinal.AddOrdinal = AddOrdinal; + + return addOrdinal; +} + +var addProperty = {}; + +var hasRequiredAddProperty; + +function requireAddProperty () { + if (hasRequiredAddProperty) return addProperty; + hasRequiredAddProperty = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addProperty, "__esModule", { value: true }); + addProperty.AddProperty = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Add a property and its value, or name-value pair, to a JSON object, and return the updated object. + * If the object already exists at runtime the function throws an error. + */ + class AddProperty extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [AddProperty](xref:adaptive-expressions.AddProperty) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddProperty, AddProperty.evaluator(), returnType_1.ReturnType.Object, AddProperty.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error; + const temp = args[0]; + const prop = String(args[1]); + if (prop in temp) { + error = `${prop} already exists`; + } + else { + temp[String(args[1])] = args[2]; + } + return { value: temp, error }; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Object, returnType_1.ReturnType.String, returnType_1.ReturnType.Object); + } + } + addProperty.AddProperty = AddProperty; + + return addProperty; +} + +var addSeconds = {}; + +var hasRequiredAddSeconds; + +function requireAddSeconds () { + if (hasRequiredAddSeconds) return addSeconds; + hasRequiredAddSeconds = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(addSeconds, "__esModule", { value: true }); + addSeconds.AddSeconds = void 0; + const expressionType_1 = requireExpressionType(); + const timeTransformEvaluator_1 = requireTimeTransformEvaluator(); + /** + * Add a number of seconds to a timestamp. + */ + class AddSeconds extends timeTransformEvaluator_1.TimeTransformEvaluator { + /** + * Initializes a new instance of the [AddSeconds](xref:adaptive-expressions.AddSeconds) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddSeconds, (ts, num) => { + const newDate = new Date(ts); + newDate.setSeconds(ts.getSeconds() + num); + return newDate; + }); + } + } + addSeconds.AddSeconds = AddSeconds; + + return addSeconds; +} + +var addToTime = {}; + +var hasRequiredAddToTime; + +function requireAddToTime () { + if (hasRequiredAddToTime) return addToTime; + hasRequiredAddToTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (addToTime && addToTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(addToTime, "__esModule", { value: true }); + addToTime.AddToTime = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Add a number of time units to a timestamp. + */ + class AddToTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [AddToTime](xref:adaptive-expressions.AddToTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.AddToTime, AddToTime.evaluator, returnType_1.ReturnType.String, AddToTime.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 5, format, locale)); + if (typeof args[0] === 'string' && Number.isInteger(args[1]) && typeof args[2] === 'string') { + ({ value, error } = AddToTime.evalAddToTime(args[0], args[1], args[2], format, locale)); + } + else { + error = `${expression} should contain an ISO format timestamp, a time interval integer, a string unit of time and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalAddToTime(timeStamp, interval, timeUnit, format, locale) { + let result; + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(timeStamp); + if (!error) { + const { duration, tsStr } = functionUtils_internal_1.InternalFunctionUtils.timeUnitTransformer(interval, timeUnit); + result = (0, dayjs_1.default)(timeStamp).locale(locale).utc().add(duration, tsStr).format(format); + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String, returnType_1.ReturnType.Number, returnType_1.ReturnType.String); + } + } + addToTime.AddToTime = AddToTime; + + return addToTime; +} + +var all = {}; + +var hasRequiredAll; + +function requireAll () { + if (hasRequiredAll) return all; + hasRequiredAll = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(all, "__esModule", { value: true }); + all.All = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Determines whether all elements of a sequence satisfy a condition. + */ + class All extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [All](xref:adaptive-expressions.All) class. + */ + constructor() { + super(expressionType_1.ExpressionType.All, All.evaluator, returnType_1.ReturnType.Boolean, functionUtils_internal_1.InternalFunctionUtils.ValidateLambdaExpression); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = true; + const { value: instance, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + const list = functionUtils_internal_1.InternalFunctionUtils.convertToList(instance); + if (!list) { + error = `${expression.children[0]} is not a collection or structure object to run Any`; + } + else { + functionUtils_internal_1.InternalFunctionUtils.lambdaEvaluator(expression, state, options, list, (currentItem, r, e) => { + if (e || !functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(r)) { + result = false; + return true; + } + return false; + }); + } + } + return { value: result, error }; + } + } + all.All = All; + + return all; +} + +var and = {}; + +var hasRequiredAnd; + +function requireAnd () { + if (hasRequiredAnd) return and; + hasRequiredAnd = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(and, "__esModule", { value: true }); + and.And = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const options_1 = requireOptions(); + const returnType_1 = requireReturnType(); + /** + * Return true if all expressions are true or return false if at least one expression is false. + */ + class And extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [And](xref:adaptive-expressions.And) class. + */ + constructor() { + super(expressionType_1.ExpressionType.And, And.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = true; + let error; + for (const child of expression.children) { + const newOptions = new options_1.Options(options); + newOptions.nullSubstitution = undefined; + ({ value: result, error } = child.tryEvaluate(state, newOptions)); + if (!error) { + if (functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(result)) { + result = true; + } + else { + result = false; + break; + } + } + else { + result = false; + error = undefined; + break; + } + } + return { value: result, error }; + } + } + and.And = And; + + return and; +} + +var any = {}; + +var hasRequiredAny; + +function requireAny () { + if (hasRequiredAny) return any; + hasRequiredAny = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(any, "__esModule", { value: true }); + any.Any = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Determines whether any element of a sequence satisfies a condition. + */ + class Any extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Any](xref:adaptive-expressions.Any) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Any, Any.evaluator, returnType_1.ReturnType.Boolean, functionUtils_internal_1.InternalFunctionUtils.ValidateLambdaExpression); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = false; + const { value: instance, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + const list = functionUtils_internal_1.InternalFunctionUtils.convertToList(instance); + if (!list) { + error = `${expression.children[0]} is not a collection or structure object to run Any`; + } + else { + functionUtils_internal_1.InternalFunctionUtils.lambdaEvaluator(expression, state, options, list, (currentItem, r, e) => { + if (!e && functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(r)) { + result = true; + return true; + } + return false; + }); + } + } + return { value: result, error }; + } + } + any.Any = Any; + + return any; +} + +var average = {}; + +var hasRequiredAverage; + +function requireAverage () { + if (hasRequiredAverage) return average; + hasRequiredAverage = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(average, "__esModule", { value: true }); + average.Average = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the average of a numeric array. + */ + class Average extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Average](xref:adaptive-expressions.Average) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Average, Average.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => args[0].reduce((x, y) => x + y) / args[0].length, functionUtils_1.FunctionUtils.verifyNumericList); + } + } + average.Average = Average; + + return average; +} + +var base64 = {}; + +var btoaNode; +var hasRequiredBtoaNode; + +function requireBtoaNode () { + if (hasRequiredBtoaNode) return btoaNode; + hasRequiredBtoaNode = 1; + btoaNode = function btoa(str) { + return new Buffer(str).toString('base64') + }; + return btoaNode; +} + +var hasRequiredBase64; + +function requireBase64 () { + if (hasRequiredBase64) return base64; + hasRequiredBase64 = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (base64 && base64.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(base64, "__esModule", { value: true }); + base64.Base64 = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const btoa_lite_1 = __importDefault(requireBtoaNode()); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + /** + * Return the base64-encoded version of a string or byte array. + */ + class Base64 extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Base64](xref:adaptive-expressions.Base64) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Base64, Base64.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let result; + const firstChild = args[0]; + if (typeof firstChild === 'string') { + result = (0, btoa_lite_1.default)(firstChild); + } + if (firstChild instanceof Uint8Array) { + const stringContent = functionUtils_internal_1.InternalFunctionUtils.getTextDecoder().decode(firstChild); + result = (0, btoa_lite_1.default)(stringContent); + } + return result; + }); + } + } + base64.Base64 = Base64; + + return base64; +} + +var base64ToBinary = {}; + +var atobNode; +var hasRequiredAtobNode; + +function requireAtobNode () { + if (hasRequiredAtobNode) return atobNode; + hasRequiredAtobNode = 1; + atobNode = function atob(str) { + return Buffer.from(str, 'base64').toString('binary') + }; + return atobNode; +} + +var hasRequiredBase64ToBinary; + +function requireBase64ToBinary () { + if (hasRequiredBase64ToBinary) return base64ToBinary; + hasRequiredBase64ToBinary = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (base64ToBinary && base64ToBinary.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(base64ToBinary, "__esModule", { value: true }); + base64ToBinary.Base64ToBinary = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + const atob_lite_1 = __importDefault(requireAtobNode()); + /** + * Return the binary array of a base64-encoded string. + */ + class Base64ToBinary extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Base64ToBinary](xref:adaptive-expressions.Base64ToBinary) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Base64ToBinary, Base64ToBinary.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + const raw = (0, atob_lite_1.default)(args[0].toString()); + return functionUtils_internal_1.InternalFunctionUtils.getTextEncoder().encode(raw); + }, functionUtils_1.FunctionUtils.verifyString); + } + } + base64ToBinary.Base64ToBinary = Base64ToBinary; + + return base64ToBinary; +} + +var base64ToString = {}; + +var hasRequiredBase64ToString; + +function requireBase64ToString () { + if (hasRequiredBase64ToString) return base64ToString; + hasRequiredBase64ToString = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (base64ToString && base64ToString.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(base64ToString, "__esModule", { value: true }); + base64ToString.Base64ToString = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const atob_lite_1 = __importDefault(requireAtobNode()); + /** + * Return the string version of a base64-encoded string, effectively decoding the base64 string. + */ + class Base64ToString extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Base64ToString](xref:adaptive-expressions.Base64ToString) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Base64ToString, Base64ToString.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => (0, atob_lite_1.default)(args[0]), functionUtils_1.FunctionUtils.verifyString); + } + } + base64ToString.Base64ToString = Base64ToString; + + return base64ToString; +} + +var binary = {}; + +var hasRequiredBinary; + +function requireBinary () { + if (hasRequiredBinary) return binary; + hasRequiredBinary = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(binary, "__esModule", { value: true }); + binary.Binary = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the binary version of a string. + */ + class Binary extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Binary](xref:adaptive-expressions.Binary) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Binary, Binary.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.getTextEncoder().encode(args[0]), functionUtils_1.FunctionUtils.verifyString); + } + } + binary.Binary = Binary; + + return binary; +} + +var bool = {}; + +var comparisonEvaluator = {}; + +var hasRequiredComparisonEvaluator; + +function requireComparisonEvaluator () { + if (hasRequiredComparisonEvaluator) return comparisonEvaluator; + hasRequiredComparisonEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(comparisonEvaluator, "__esModule", { value: true }); + comparisonEvaluator.ComparisonEvaluator = void 0; + const __1 = requireLib(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Comparison operators. + * A comparison operator returns false if the comparison is false, or there is an error. This prevents errors from short-circuiting boolean expressions. + */ + class ComparisonEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [ComparisonEvaluator](xref:adaptive-expressions.ComparisonEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The comparison function, it takes a list of objects and returns a boolean. + * @param validator [ValidateExpressionDelegate](xref:adaptive-expressions.ValidateExpressionDelegate) for input arguments. + * @param verify Optional. [VerifyExpression](xref:adaptive-expressions.VerifyExpression) function to verify each child's result. + */ + constructor(type, func, validator, verify) { + super(type, ComparisonEvaluator.evaluator(func, verify), returnType_1.ReturnType.Boolean, validator); + } + /** + * @private + */ + static evaluator(func, verify) { + return (expression, state, options) => { + let result = false; + const newOptions = new __1.Options(options); + newOptions.nullSubstitution = undefined; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, newOptions, verify); + let error = childrenError; + if (!error) { + try { + result = func(args); + } + catch (e) { + // NOTE: This should not happen in normal execution + error = e.message; + } + } + else { + error = undefined; + } + return { value: result, error }; + }; + } + } + comparisonEvaluator.ComparisonEvaluator = ComparisonEvaluator; + + return comparisonEvaluator; +} + +var hasRequiredBool; + +function requireBool () { + if (hasRequiredBool) return bool; + hasRequiredBool = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(bool, "__esModule", { value: true }); + bool.Bool = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Return the Boolean version of a value. + */ + class Bool extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [Bool](xref:adaptive-expressions.Bool) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Bool, Bool.func, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static func(args) { + if (functionUtils_1.FunctionUtils.isNumber(args[0])) { + return args[0] !== 0; + } + if (/false/i.test(args[0])) { + return false; + } + return functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(args[0]); + } + } + bool.Bool = Bool; + + return bool; +} + +var ceiling = {}; + +var hasRequiredCeiling; + +function requireCeiling () { + if (hasRequiredCeiling) return ceiling; + hasRequiredCeiling = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(ceiling, "__esModule", { value: true }); + ceiling.Ceiling = void 0; + const expressionType_1 = requireExpressionType(); + const numberTransformEvaluator_1 = requireNumberTransformEvaluator(); + /** + * Returns the smallest integral value that is greater than or equal to the specified number. + */ + class Ceiling extends numberTransformEvaluator_1.NumberTransformEvaluator { + /** + * Initializes a new instance of the [Ceiling](xref:adaptive-expressions.Ceiling) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Ceiling, Ceiling.func); + } + /** + * @private + */ + static func(args) { + return Math.ceil(args[0]); + } + } + ceiling.Ceiling = Ceiling; + + return ceiling; +} + +var coalesce = {}; + +var hasRequiredCoalesce; + +function requireCoalesce () { + if (hasRequiredCoalesce) return coalesce; + hasRequiredCoalesce = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(coalesce, "__esModule", { value: true }); + coalesce.Coalesce = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the first non-null value from one or more parameters. + * Empty strings, empty arrays, and empty objects are not null. + */ + class Coalesce extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Coalesce](xref:adaptive-expressions.Coalesce) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Coalesce, Coalesce.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => Coalesce.evalCoalesce(args)); + } + /** + * @private + */ + static evalCoalesce(objectList) { + for (const obj of objectList) { + if (obj != null) { + return obj; + } + } + return undefined; + } + } + coalesce.Coalesce = Coalesce; + + return coalesce; +} + +var concat = {}; + +var hasRequiredConcat; + +function requireConcat () { + if (hasRequiredConcat) return concat; + hasRequiredConcat = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(concat, "__esModule", { value: true }); + concat.Concat = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + /** + * Combine two or more strings, and return the combined string. + */ + class Concat extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Concat](xref:adaptive-expressions.Concat) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Concat, Concat.evaluator(), returnType_1.ReturnType.String | returnType_1.ReturnType.Array, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applySequence((args) => { + const firstItem = args[0]; + const secondItem = args[1]; + const isFirstList = Array.isArray(firstItem); + const isSecondList = Array.isArray(secondItem); + if (firstItem == null && secondItem == null) { + return undefined; + } + else if (firstItem == null && isSecondList) { + return secondItem; + } + else if (secondItem == null && isFirstList) { + return firstItem; + } + else if (isFirstList && isSecondList) { + return firstItem.concat(secondItem); + } + else { + return (functionUtils_internal_1.InternalFunctionUtils.commonStringify(firstItem) + functionUtils_internal_1.InternalFunctionUtils.commonStringify(secondItem)); + } + }); + } + } + concat.Concat = Concat; + + return concat; +} + +var contains = {}; + +var hasRequiredContains; + +function requireContains () { + if (hasRequiredContains) return contains; + hasRequiredContains = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(contains, "__esModule", { value: true }); + contains.Contains = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Check whether a collection has a specific item. Return true if the item is found, or return false if not found. + * This function is case-sensitive. + */ + class Contains extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Contains](xref:adaptive-expressions.Contains) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Contains, Contains.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateBinary); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let found = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string' && typeof args[1] === 'string') { + found = args[0].includes(args[1]); + } + else if (Array.isArray(args[0])) { + for (const item of args[0]) { + if (functionUtils_1.FunctionUtils.commonEquals(item, args[1])) { + found = true; + break; + } + } + } + else if (typeof args[1] === 'string') { + let value; + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.accessProperty(args[0], args[1])); + found = !error && value !== undefined; + } + } + return { value: found, error: undefined }; + } + } + contains.Contains = Contains; + + return contains; +} + +var convertFromUTC = {}; + +var timezone$1 = {exports: {}}; + +var timezone = timezone$1.exports; + +var hasRequiredTimezone; + +function requireTimezone () { + if (hasRequiredTimezone) return timezone$1.exports; + hasRequiredTimezone = 1; + (function (module, exports) { + !function(t,e){module.exports=e();}(timezone,(function(){var t={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(n,i,o){var r,a=function(t,n,i){ void 0===i&&(i={});var o=new Date(t),r=function(t,n){ void 0===n&&(n={});var i=n.timeZoneName||"short",o=t+"|"+i,r=e[o];return r||(r=new Intl.DateTimeFormat("en-US",{hour12:false,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:i}),e[o]=r),r}(n,i);return r.formatToParts(o)},u=function(e,n){for(var i=a(e,n),r=[],u=0;u=0&&(r[c]=parseInt(m,10));}var d=r[3],l=24===d?0:d,h=r[0]+"-"+r[1]+"-"+r[2]+" "+l+":"+r[4]+":"+r[5]+":000",v=+e;return (o.utc(h).valueOf()-(v-=v%1e3))/6e4},f=i.prototype;f.tz=function(t,e){ void 0===t&&(t=r);var n,i=this.utcOffset(),a=this.toDate(),u=a.toLocaleString("en-US",{timeZone:t}),f=Math.round((a-new Date(u))/1e3/60),s=15*-Math.round(a.getTimezoneOffset()/15)-f;if(!Number(s))n=this.utcOffset(0,e);else if(n=o(u,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(s,true),e){var m=n.utcOffset();n=n.add(i-m,"minute");}return n.$x.$timezone=t,n},f.offsetName=function(t){var e=this.$x.$timezone||o.tz.guess(),n=a(this.valueOf(),e,{timeZoneName:t}).find((function(t){return "timezonename"===t.type.toLowerCase()}));return n&&n.value};var s=f.startOf;f.startOf=function(t,e){if(!this.$x||!this.$x.$timezone)return s.call(this,t,e);var n=o(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return s.call(n,t,e).tz(this.$x.$timezone,true)},o.tz=function(t,e,n){var i=n&&e,a=n||e||r,f=u(+o(),a);if("string"!=typeof t)return o(t).tz(a);var s=function(t,e,n){var i=t-60*e*1e3,o=u(i,n);if(e===o)return [i,e];var r=u(i-=60*(o-e)*1e3,n);return o===r?[i,o]:[t-60*Math.min(o,r)*1e3,Math.max(o,r)]}(o.utc(t,i).valueOf(),f,a),m=s[0],c=s[1],d=o(m).utcOffset(c);return d.$x.$timezone=a,d},o.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},o.tz.setDefault=function(t){r=t;};}})); + } (timezone$1)); + return timezone$1.exports; +} + +var timeZoneConverter = {}; + +var hasRequiredTimeZoneConverter; + +function requireTimeZoneConverter () { + if (hasRequiredTimeZoneConverter) return timeZoneConverter; + hasRequiredTimeZoneConverter = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(timeZoneConverter, "__esModule", { value: true }); + timeZoneConverter.TimeZoneConverter = void 0; + /** + * Time zone converter. + * (1) From Windows (.NET) timezone to iana timezone. + * (2) From iana timezone to windows (.NET) timezone. + * windows ref: https://support.microsoft.com/en-us/help/22803/daylight-saving-time. + * iana ref: https://www.iana.org/time-zones. + */ + class TimeZoneConverter { + /** + * convert IANA timezone format to windows timezone format. + * + * @param ianaTimeZoneId IANA timezone format. + * @returns windows timezone format. + */ + static ianaToWindows(ianaTimeZoneId) { + this.loadData(); + if (this.ianaToWindowsMap.has(ianaTimeZoneId)) { + return this.ianaToWindowsMap.get(ianaTimeZoneId); + } + return ianaTimeZoneId; + } + /** + * Convert windows timezone to iana timezone. + * + * @param windowsTimeZoneId Windows timezone format. + * @returns Iana timezone format. + */ + static windowsToIana(windowsTimeZoneId) { + this.loadData(); + if (this.windowsToIanaMap.has(`001|${windowsTimeZoneId}`)) { + return this.windowsToIanaMap.get(`001|${windowsTimeZoneId}`); + } + return windowsTimeZoneId; + } + /** + * Verify the string is windows timezone or iana string + * + * @param timezoneStr time zone string + * @returns is the string is time zone string + */ + static verifyTimeZoneStr(timezoneStr) { + this.loadData(); + return this.validTimezonStr.includes(timezoneStr); + } + /** + * @private + */ + static loadData() { + const data = this.mappingString; + const lines = data.split(this.seperator); + for (const line of lines) { + const tokens = line.split(','); + const windowsID = tokens[0]; + const territory = tokens[1]; + const ianaIDs = tokens[2].split(' '); + for (const ianaID of ianaIDs) { + if (!this.ianaToWindowsMap.has(ianaID)) { + this.ianaToWindowsMap.set(ianaID, windowsID); + } + if (!this.validTimezonStr.includes(ianaID)) { + this.validTimezonStr.push(ianaID); + } + } + if (!this.windowsToIanaMap.has(`${territory}|${windowsID}`)) { + this.windowsToIanaMap.set(`${territory}|${windowsID}`, ianaIDs[0]); + } + if (!this.validTimezonStr.includes(windowsID)) { + this.validTimezonStr.push(windowsID); + } + } + } + } + timeZoneConverter.TimeZoneConverter = TimeZoneConverter; + TimeZoneConverter.ianaToWindowsMap = new Map(); + TimeZoneConverter.windowsToIanaMap = new Map(); + TimeZoneConverter.validTimezonStr = []; + TimeZoneConverter.seperator = ' '; + TimeZoneConverter.mappingString = 'AUS Central Standard Time,001,Australia/Darwin\ + AUS Central Standard Time,AU,Australia/Darwin\ + AUS Eastern Standard Time,001,Australia/Sydney\ + AUS Eastern Standard Time,AU,Australia/Sydney Australia/Melbourne\ + Afghanistan Standard Time,001,Asia/Kabul\ + Afghanistan Standard Time,AF,Asia/Kabul\ + Alaskan Standard Time,001,America/Anchorage\ + Alaskan Standard Time,US,America/Anchorage America/Juneau America/Metlakatla America/Nome America/Sitka America/Yakutat\ + Aleutian Standard Time,001,America/Adak\ + Aleutian Standard Time,US,America/Adak\ + Altai Standard Time,001,Asia/Barnaul\ + Altai Standard Time,RU,Asia/Barnaul\ + Arab Standard Time,001,Asia/Riyadh\ + Arab Standard Time,BH,Asia/Qatar\ + Arab Standard Time,KW,Asia/Riyadh\ + Arab Standard Time,QA,Asia/Qatar\ + Arab Standard Time,SA,Asia/Riyadh\ + Arab Standard Time,YE,Asia/Riyadh\ + Arabian Standard Time,001,Asia/Dubai\ + Arabian Standard Time,AE,Asia/Dubai\ + Arabian Standard Time,OM,Asia/Dubai\ + Arabian Standard Time,ZZ,Etc/GMT-4\ + Arabic Standard Time,001,Asia/Baghdad\ + Arabic Standard Time,IQ,Asia/Baghdad\ + Argentina Standard Time,001,America/Argentina/Buenos_Aires\ + Argentina Standard Time,AR,America/Argentina/Buenos_Aires America/Argentina/La_Rioja America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Argentina/Catamarca America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/Mendoza\ + Astrakhan Standard Time,001,Europe/Astrakhan\ + Astrakhan Standard Time,RU,Europe/Astrakhan Europe/Ulyanovsk\ + Atlantic Standard Time,001,America/Halifax\ + Atlantic Standard Time,BM,Atlantic/Bermuda\ + Atlantic Standard Time,CA,America/Halifax America/Glace_Bay America/Goose_Bay America/Moncton\ + Atlantic Standard Time,GL,America/Thule\ + Aus Central W. Standard Time,001,Australia/Eucla\ + Aus Central W. Standard Time,AU,Australia/Eucla\ + Azerbaijan Standard Time,001,Asia/Baku\ + Azerbaijan Standard Time,AZ,Asia/Baku\ + Azores Standard Time,001,Atlantic/Azores\ + Azores Standard Time,GL,America/Scoresbysund\ + Azores Standard Time,PT,Atlantic/Azores\ + Bahia Standard Time,001,America/Bahia\ + Bahia Standard Time,BR,America/Bahia\ + Bangladesh Standard Time,001,Asia/Dhaka\ + Bangladesh Standard Time,BD,Asia/Dhaka\ + Bangladesh Standard Time,BT,Asia/Thimphu\ + Belarus Standard Time,001,Europe/Minsk\ + Belarus Standard Time,BY,Europe/Minsk\ + Bougainville Standard Time,001,Pacific/Bougainville\ + Bougainville Standard Time,PG,Pacific/Bougainville\ + Canada Central Standard Time,001,America/Regina\ + Canada Central Standard Time,CA,America/Regina America/Swift_Current\ + Cape Verde Standard Time,001,Atlantic/Cape_Verde\ + Cape Verde Standard Time,CV,Atlantic/Cape_Verde\ + Cape Verde Standard Time,ZZ,Etc/GMT+1\ + Caucasus Standard Time,001,Asia/Yerevan\ + Caucasus Standard Time,AM,Asia/Yerevan\ + Cen. Australia Standard Time,001,Australia/Adelaide\ + Cen. Australia Standard Time,AU,Australia/Adelaide Australia/Broken_Hill\ + Central America Standard Time,001,America/Guatemala\ + Central America Standard Time,BZ,America/Belize\ + Central America Standard Time,CR,America/Costa_Rica\ + Central America Standard Time,EC,Pacific/Galapagos\ + Central America Standard Time,GT,America/Guatemala\ + Central America Standard Time,HN,America/Tegucigalpa\ + Central America Standard Time,NI,America/Managua\ + Central America Standard Time,SV,America/El_Salvador\ + Central America Standard Time,ZZ,Etc/GMT+6\ + Central Asia Standard Time,001,Asia/Almaty\ + Central Asia Standard Time,AQ,Antarctica/Vostok\ + Central Asia Standard Time,CN,Asia/Urumqi\ + Central Asia Standard Time,DG,Indian/Chagos\ + Central Asia Standard Time,IO,Indian/Chagos\ + Central Asia Standard Time,KG,Asia/Bishkek\ + Central Asia Standard Time,KZ,Asia/Almaty Asia/Qyzylorda\ + Central Asia Standard Time,ZZ,Etc/GMT-6\ + Central Brazilian Standard Time,001,America/Cuiaba\ + Central Brazilian Standard Time,BR,America/Cuiaba America/Campo_Grande\ + Central Europe Standard Time,001,Europe/Budapest\ + Central Europe Standard Time,AL,Europe/Tirane\ + Central Europe Standard Time,CZ,Europe/Prague\ + Central Europe Standard Time,HU,Europe/Budapest\ + Central Europe Standard Time,ME,Europe/Belgrade\ + Central Europe Standard Time,RS,Europe/Belgrade\ + Central Europe Standard Time,SI,Europe/Belgrade\ + Central Europe Standard Time,SK,Europe/Prague\ + Central Europe Standard Time,XK,Europe/Belgrade\ + Central European Standard Time,001,Europe/Warsaw\ + Central European Standard Time,BA,Europe/Belgrade\ + Central European Standard Time,HR,Europe/Belgrade\ + Central European Standard Time,MK,Europe/Belgrade\ + Central European Standard Time,PL,Europe/Warsaw\ + Central Pacific Standard Time,001,Pacific/Guadalcanal\ + Central Pacific Standard Time,AU,Antarctica/Macquarie\ + Central Pacific Standard Time,FM,Pacific/Pohnpei Pacific/Kosrae\ + Central Pacific Standard Time,NC,Pacific/Noumea\ + Central Pacific Standard Time,SB,Pacific/Guadalcanal\ + Central Pacific Standard Time,VU,Pacific/Efate\ + Central Pacific Standard Time,ZZ,Etc/GMT-11\ + Central Standard Time (Mexico),001,America/Mexico_City\ + Central Standard Time (Mexico),MX,America/Mexico_City America/Bahia_Banderas America/Merida America/Monterrey\ + Central Standard Time,001,America/Chicago\ + Central Standard Time,CA,America/Winnipeg America/Rainy_River America/Rankin_Inlet America/Resolute\ + Central Standard Time,MX,America/Matamoros\ + Central Standard Time,US,America/Chicago America/Indiana/Knox America/Indiana/Tell_City America/Menominee America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem\ + Central Standard Time,ZZ,CST6CDT\ + Chatham Islands Standard Time,001,Pacific/Chatham\ + Chatham Islands Standard Time,NZ,Pacific/Chatham\ + China Standard Time,001,Asia/Shanghai\ + China Standard Time,CN,Asia/Shanghai\ + China Standard Time,HK,Asia/Hong_Kong\ + China Standard Time,MO,Asia/Macau\ + Cuba Standard Time,001,America/Havana\ + Cuba Standard Time,CU,America/Havana\ + Dateline Standard Time,001,Etc/GMT+12\ + Dateline Standard Time,ZZ,Etc/GMT+12\ + E. Africa Standard Time,001,Africa/Nairobi\ + E. Africa Standard Time,AQ,Antarctica/Syowa\ + E. Africa Standard Time,DJ,Africa/Nairobi\ + E. Africa Standard Time,ER,Africa/Nairobi\ + E. Africa Standard Time,ET,Africa/Nairobi\ + E. Africa Standard Time,KE,Africa/Nairobi\ + E. Africa Standard Time,KM,Africa/Nairobi\ + E. Africa Standard Time,MG,Africa/Nairobi\ + E. Africa Standard Time,SO,Africa/Nairobi\ + E. Africa Standard Time,SS,Africa/Juba\ + E. Africa Standard Time,TZ,Africa/Nairobi\ + E. Africa Standard Time,UG,Africa/Nairobi\ + E. Africa Standard Time,YT,Africa/Nairobi\ + E. Africa Standard Time,ZZ,Etc/GMT-3\ + E. Australia Standard Time,001,Australia/Brisbane\ + E. Australia Standard Time,AU,Australia/Brisbane Australia/Lindeman\ + E. Europe Standard Time,001,Europe/Chisinau\ + E. Europe Standard Time,MD,Europe/Chisinau\ + E. South America Standard Time,001,America/Sao_Paulo\ + E. South America Standard Time,BR,America/Sao_Paulo\ + Easter Island Standard Time,001,Pacific/Easter\ + Easter Island Standard Time,CL,Pacific/Easter\ + Eastern Standard Time (Mexico),001,America/Cancun\ + Eastern Standard Time (Mexico),MX,America/Cancun\ + Eastern Standard Time,001,America/New_York\ + Eastern Standard Time,BS,America/Nassau\ + Eastern Standard Time,CA,America/Toronto America/Iqaluit America/Nipigon America/Pangnirtung America/Thunder_Bay\ + Eastern Standard Time,US,America/New_York America/Detroit America/Indiana/Petersburg America/Indiana/Vincennes America/Indiana/Winamac America/Kentucky/Monticello America/Kentucky/Louisville\ + Eastern Standard Time,ZZ,EST5EDT\ + Egypt Standard Time,001,Africa/Cairo\ + Egypt Standard Time,EG,Africa/Cairo\ + Ekaterinburg Standard Time,001,Asia/Yekaterinburg\ + Ekaterinburg Standard Time,RU,Asia/Yekaterinburg\ + FLE Standard Time,001,Europe/Kiev\ + FLE Standard Time,AX,Europe/Helsinki\ + FLE Standard Time,BG,Europe/Sofia\ + FLE Standard Time,EE,Europe/Tallinn\ + FLE Standard Time,FI,Europe/Helsinki\ + FLE Standard Time,LT,Europe/Vilnius\ + FLE Standard Time,LV,Europe/Riga\ + FLE Standard Time,UA,Europe/Kiev Europe/Uzhgorod Europe/Zaporozhye\ + Fiji Standard Time,001,Pacific/Fiji\ + Fiji Standard Time,FJ,Pacific/Fiji\ + GMT Standard Time,001,Europe/London\ + GMT Standard Time,ES,Atlantic/Canary\ + GMT Standard Time,FO,Atlantic/Faroe\ + GMT Standard Time,GB,Europe/London\ + GMT Standard Time,GG,Europe/London\ + GMT Standard Time,IC,Atlantic/Canary\ + GMT Standard Time,IE,Europe/Dublin\ + GMT Standard Time,IM,Europe/London\ + GMT Standard Time,JE,Europe/London\ + GMT Standard Time,PT,Europe/Lisbon Atlantic/Madeira\ + GTB Standard Time,001,Europe/Bucharest\ + GTB Standard Time,CY,Asia/Nicosia Asia/Famagusta\ + GTB Standard Time,GR,Europe/Athens\ + GTB Standard Time,RO,Europe/Bucharest\ + Georgian Standard Time,001,Asia/Tbilisi\ + Georgian Standard Time,GE,Asia/Tbilisi\ + Greenland Standard Time,001,America/Godthab\ + Greenland Standard Time,GL,America/Godthab\ + Greenwich Standard Time,001,Atlantic/Reykjavik\ + Greenwich Standard Time,AC,Atlantic/St_Helena\ + Greenwich Standard Time,BF,Africa/Abidjan\ + Greenwich Standard Time,CI,Africa/Abidjan\ + Greenwich Standard Time,GH,Africa/Accra\ + Greenwich Standard Time,GM,Africa/Abidjan\ + Greenwich Standard Time,GN,Africa/Abidjan\ + Greenwich Standard Time,GW,Africa/Bissau\ + Greenwich Standard Time,IS,Atlantic/Reykjavik\ + Greenwich Standard Time,LR,Africa/Monrovia\ + Greenwich Standard Time,ML,Africa/Abidjan\ + Greenwich Standard Time,MR,Africa/Abidjan\ + Greenwich Standard Time,SH,Africa/Abidjan\ + Greenwich Standard Time,SL,Africa/Abidjan\ + Greenwich Standard Time,SN,Africa/Abidjan\ + Greenwich Standard Time,TA,Atlantic/St_Helena\ + Greenwich Standard Time,TG,Africa/Abidjan\ + Haiti Standard Time,001,America/Port-au-Prince\ + Haiti Standard Time,HT,America/Port-au-Prince\ + Hawaiian Standard Time,001,Pacific/Honolulu\ + Hawaiian Standard Time,CK,Pacific/Rarotonga\ + Hawaiian Standard Time,PF,Pacific/Tahiti\ + Hawaiian Standard Time,UM,Pacific/Honolulu\ + Hawaiian Standard Time,US,Pacific/Honolulu\ + Hawaiian Standard Time,ZZ,Etc/GMT+10\ + India Standard Time,001,Asia/Kolkata\ + India Standard Time,IN,Asia/Kolkata\ + Iran Standard Time,001,Asia/Tehran\ + Iran Standard Time,IR,Asia/Tehran\ + Israel Standard Time,001,Asia/Jerusalem\ + Israel Standard Time,IL,Asia/Jerusalem\ + Jordan Standard Time,001,Asia/Amman\ + Jordan Standard Time,JO,Asia/Amman\ + Kaliningrad Standard Time,001,Europe/Kaliningrad\ + Kaliningrad Standard Time,RU,Europe/Kaliningrad\ + Kamchatka Standard Time,001,Asia/Kamchatka\ + Korea Standard Time,001,Asia/Seoul\ + Korea Standard Time,KR,Asia/Seoul\ + Libya Standard Time,001,Africa/Tripoli\ + Libya Standard Time,LY,Africa/Tripoli\ + Line Islands Standard Time,001,Pacific/Kiritimati\ + Line Islands Standard Time,KI,Pacific/Kiritimati\ + Line Islands Standard Time,ZZ,Etc/GMT-14\ + Lord Howe Standard Time,001,Australia/Lord_Howe\ + Lord Howe Standard Time,AU,Australia/Lord_Howe\ + Magadan Standard Time,001,Asia/Magadan\ + Magadan Standard Time,RU,Asia/Magadan\ + Magallanes Standard Time,001,America/Punta_Arenas\ + Magallanes Standard Time,AQ,Antarctica/Palmer\ + Magallanes Standard Time,CL,America/Punta_Arenas\ + Marquesas Standard Time,001,Pacific/Marquesas\ + Marquesas Standard Time,PF,Pacific/Marquesas\ + Mauritius Standard Time,001,Indian/Mauritius\ + Mauritius Standard Time,MU,Indian/Mauritius\ + Mauritius Standard Time,RE,Indian/Reunion\ + Mauritius Standard Time,SC,Indian/Mahe\ + Mid-Atlantic Standard Time,001,Etc/GMT+2\ + Middle East Standard Time,001,Asia/Beirut\ + Middle East Standard Time,LB,Asia/Beirut\ + Montevideo Standard Time,001,America/Montevideo\ + Montevideo Standard Time,UY,America/Montevideo\ + Morocco Standard Time,001,Africa/Casablanca\ + Morocco Standard Time,EH,Africa/El_Aaiun\ + Morocco Standard Time,MA,Africa/Casablanca\ + Mountain Standard Time (Mexico),001,America/Chihuahua\ + Mountain Standard Time (Mexico),MX,America/Chihuahua America/Mazatlan\ + Mountain Standard Time,001,America/Denver\ + Mountain Standard Time,CA,America/Edmonton America/Cambridge_Bay America/Inuvik America/Yellowknife\ + Mountain Standard Time,MX,America/Ojinaga\ + Mountain Standard Time,US,America/Denver America/Boise\ + Mountain Standard Time,ZZ,MST7MDT\ + Myanmar Standard Time,001,Asia/Yangon\ + Myanmar Standard Time,CC,Indian/Cocos\ + Myanmar Standard Time,MM,Asia/Yangon\ + N. Central Asia Standard Time,001,Asia/Novosibirsk\ + N. Central Asia Standard Time,RU,Asia/Novosibirsk\ + Namibia Standard Time,001,Africa/Windhoek\ + Namibia Standard Time,NA,Africa/Windhoek\ + Nepal Standard Time,001,Asia/Kathmandu\ + Nepal Standard Time,NP,Asia/Kathmandu\ + New Zealand Standard Time,001,Pacific/Auckland\ + New Zealand Standard Time,AQ,Pacific/Auckland\ + New Zealand Standard Time,NZ,Pacific/Auckland\ + Newfoundland Standard Time,001,America/St_Johns\ + Newfoundland Standard Time,CA,America/St_Johns\ + Norfolk Standard Time,001,Pacific/Norfolk\ + Norfolk Standard Time,NF,Pacific/Norfolk\ + North Asia East Standard Time,001,Asia/Irkutsk\ + North Asia East Standard Time,RU,Asia/Irkutsk\ + North Asia Standard Time,001,Asia/Krasnoyarsk\ + North Asia Standard Time,RU,Asia/Krasnoyarsk Asia/Novokuznetsk\ + North Korea Standard Time,001,Asia/Pyongyang\ + North Korea Standard Time,KP,Asia/Pyongyang\ + Omsk Standard Time,001,Asia/Omsk\ + Omsk Standard Time,RU,Asia/Omsk\ + Pacific SA Standard Time,001,America/Santiago\ + Pacific SA Standard Time,CL,America/Santiago\ + Pacific Standard Time (Mexico),001,America/Tijuana\ + Pacific Standard Time (Mexico),MX,America/Tijuana\ + Pacific Standard Time,001,America/Los_Angeles\ + Pacific Standard Time,CA,America/Vancouver America/Dawson America/Whitehorse\ + Pacific Standard Time,US,America/Los_Angeles\ + Pacific Standard Time,ZZ,PST8PDT\ + Pakistan Standard Time,001,Asia/Karachi\ + Pakistan Standard Time,PK,Asia/Karachi\ + Paraguay Standard Time,001,America/Asuncion\ + Paraguay Standard Time,PY,America/Asuncion\ + Romance Standard Time,001,Europe/Paris\ + Romance Standard Time,BE,Europe/Brussels\ + Romance Standard Time,DK,Europe/Copenhagen\ + Romance Standard Time,EA,Africa/Ceuta\ + Romance Standard Time,ES,Europe/Madrid Africa/Ceuta\ + Romance Standard Time,FR,Europe/Paris\ + Russia Time Zone 10,001,Asia/Srednekolymsk\ + Russia Time Zone 10,RU,Asia/Srednekolymsk\ + Russia Time Zone 11,001,Asia/Kamchatka\ + Russia Time Zone 11,RU,Asia/Kamchatka Asia/Anadyr\ + Russia Time Zone 3,001,Europe/Samara\ + Russia Time Zone 3,RU,Europe/Samara\ + Russian Standard Time,001,Europe/Moscow\ + Russian Standard Time,RU,Europe/Moscow Europe/Kirov Europe/Volgograd\ + Russian Standard Time,UA,Europe/Simferopol\ + SA Eastern Standard Time,001,America/Cayenne\ + SA Eastern Standard Time,AQ,Antarctica/Rothera\ + SA Eastern Standard Time,BR,America/Fortaleza America/Belem America/Maceio America/Recife America/Santarem\ + SA Eastern Standard Time,FK,Atlantic/Stanley\ + SA Eastern Standard Time,GF,America/Cayenne\ + SA Eastern Standard Time,SR,America/Paramaribo\ + SA Eastern Standard Time,ZZ,Etc/GMT+3\ + SA Pacific Standard Time,001,America/Bogota\ + SA Pacific Standard Time,BR,America/Rio_Branco America/Eirunepe\ + SA Pacific Standard Time,CA,America/Atikokan\ + SA Pacific Standard Time,CO,America/Bogota\ + SA Pacific Standard Time,EC,America/Guayaquil\ + SA Pacific Standard Time,JM,America/Jamaica\ + SA Pacific Standard Time,KY,America/Panama\ + SA Pacific Standard Time,PA,America/Panama\ + SA Pacific Standard Time,PE,America/Lima\ + SA Pacific Standard Time,ZZ,Etc/GMT+5\ + SA Western Standard Time,001,America/La_Paz\ + SA Western Standard Time,AG,America/Port_of_Spain\ + SA Western Standard Time,AI,America/Port_of_Spain\ + SA Western Standard Time,AW,America/Curacao\ + SA Western Standard Time,BB,America/Barbados\ + SA Western Standard Time,BL,America/Port_of_Spain\ + SA Western Standard Time,BO,America/La_Paz\ + SA Western Standard Time,BQ,America/Curacao\ + SA Western Standard Time,BR,America/Manaus America/Boa_Vista America/Porto_Velho\ + SA Western Standard Time,CA,America/Blanc-Sablon\ + SA Western Standard Time,CW,America/Curacao\ + SA Western Standard Time,DM,America/Port_of_Spain\ + SA Western Standard Time,DO,America/Santo_Domingo\ + SA Western Standard Time,GD,America/Port_of_Spain\ + SA Western Standard Time,GP,America/Port_of_Spain\ + SA Western Standard Time,GY,America/Guyana\ + SA Western Standard Time,KN,America/Port_of_Spain\ + SA Western Standard Time,LC,America/Port_of_Spain\ + SA Western Standard Time,MF,America/Port_of_Spain\ + SA Western Standard Time,MQ,America/Martinique\ + SA Western Standard Time,MS,America/Port_of_Spain\ + SA Western Standard Time,PR,America/Puerto_Rico\ + SA Western Standard Time,SX,America/Curacao\ + SA Western Standard Time,TT,America/Port_of_Spain\ + SA Western Standard Time,VC,America/Port_of_Spain\ + SA Western Standard Time,VG,America/Port_of_Spain\ + SA Western Standard Time,VI,America/Port_of_Spain\ + SA Western Standard Time,ZZ,Etc/GMT+4\ + SE Asia Standard Time,001,Asia/Bangkok\ + SE Asia Standard Time,AQ,Antarctica/Davis\ + SE Asia Standard Time,CX,Indian/Christmas\ + SE Asia Standard Time,ID,Asia/Jakarta Asia/Pontianak\ + SE Asia Standard Time,KH,Asia/Bangkok\ + SE Asia Standard Time,LA,Asia/Bangkok\ + SE Asia Standard Time,TH,Asia/Bangkok\ + SE Asia Standard Time,VN,Asia/Ho_Chi_Minh\ + SE Asia Standard Time,ZZ,Etc/GMT-7\ + Saint Pierre Standard Time,001,America/Miquelon\ + Saint Pierre Standard Time,PM,America/Miquelon\ + Sakhalin Standard Time,001,Asia/Sakhalin\ + Sakhalin Standard Time,RU,Asia/Sakhalin\ + Samoa Standard Time,001,Pacific/Apia\ + Samoa Standard Time,WS,Pacific/Apia\ + Sao Tome Standard Time,001,Africa/Sao_Tome\ + Sao Tome Standard Time,ST,Africa/Sao_Tome\ + Saratov Standard Time,001,Europe/Saratov\ + Saratov Standard Time,RU,Europe/Saratov\ + Singapore Standard Time,001,Asia/Singapore\ + Singapore Standard Time,BN,Asia/Brunei\ + Singapore Standard Time,ID,Asia/Makassar\ + Singapore Standard Time,MY,Asia/Kuala_Lumpur Asia/Kuching\ + Singapore Standard Time,PH,Asia/Manila\ + Singapore Standard Time,SG,Asia/Singapore\ + Singapore Standard Time,ZZ,Etc/GMT-8\ + South Africa Standard Time,001,Africa/Johannesburg\ + South Africa Standard Time,BI,Africa/Maputo\ + South Africa Standard Time,BW,Africa/Maputo\ + South Africa Standard Time,CD,Africa/Maputo\ + South Africa Standard Time,LS,Africa/Johannesburg\ + South Africa Standard Time,MW,Africa/Maputo\ + South Africa Standard Time,MZ,Africa/Maputo\ + South Africa Standard Time,RW,Africa/Maputo\ + South Africa Standard Time,SZ,Africa/Johannesburg\ + South Africa Standard Time,ZA,Africa/Johannesburg\ + South Africa Standard Time,ZM,Africa/Maputo\ + South Africa Standard Time,ZW,Africa/Maputo\ + South Africa Standard Time,ZZ,Etc/GMT-2\ + Sri Lanka Standard Time,001,Asia/Colombo\ + Sri Lanka Standard Time,LK,Asia/Colombo\ + Sudan Standard Time,001,Africa/Khartoum\ + Sudan Standard Time,SD,Africa/Khartoum\ + Syria Standard Time,001,Asia/Damascus\ + Syria Standard Time,SY,Asia/Damascus\ + Taipei Standard Time,001,Asia/Taipei\ + Taipei Standard Time,TW,Asia/Taipei\ + Tasmania Standard Time,001,Australia/Hobart\ + Tasmania Standard Time,AU,Australia/Hobart Australia/Currie\ + Tocantins Standard Time,001,America/Araguaina\ + Tocantins Standard Time,BR,America/Araguaina\ + Tokyo Standard Time,001,Asia/Tokyo\ + Tokyo Standard Time,ID,Asia/Jayapura\ + Tokyo Standard Time,JP,Asia/Tokyo\ + Tokyo Standard Time,PW,Pacific/Palau\ + Tokyo Standard Time,TL,Asia/Dili\ + Tokyo Standard Time,ZZ,Etc/GMT-9\ + Tomsk Standard Time,001,Asia/Tomsk\ + Tomsk Standard Time,RU,Asia/Tomsk\ + Tonga Standard Time,001,Pacific/Tongatapu\ + Tonga Standard Time,TO,Pacific/Tongatapu\ + Transbaikal Standard Time,001,Asia/Chita\ + Transbaikal Standard Time,RU,Asia/Chita\ + Turkey Standard Time,001,Europe/Istanbul\ + Turkey Standard Time,TR,Europe/Istanbul\ + Turks And Caicos Standard Time,001,America/Grand_Turk\ + Turks And Caicos Standard Time,TC,America/Grand_Turk\ + US Eastern Standard Time,001,America/Indiana/Indianapolis\ + US Eastern Standard Time,US,America/Indiana/Indianapolis America/Indiana/Marengo America/Indiana/Vevay\ + US Mountain Standard Time,001,America/Phoenix\ + US Mountain Standard Time,CA,America/Dawson_Creek America/Creston America/Fort_Nelson\ + US Mountain Standard Time,MX,America/Hermosillo\ + US Mountain Standard Time,US,America/Phoenix\ + US Mountain Standard Time,ZZ,Etc/GMT+7\ + UTC+12,001,Etc/GMT-12\ + UTC+12,KI,Pacific/Tarawa\ + UTC+12,MH,Pacific/Majuro Pacific/Kwajalein\ + UTC+12,NR,Pacific/Nauru\ + UTC+12,TV,Pacific/Funafuti\ + UTC+12,UM,Pacific/Wake\ + UTC+12,WF,Pacific/Wallis\ + UTC+12,ZZ,Etc/GMT-12\ + UTC+13,001,Etc/GMT-13\ + UTC+13,KI,Pacific/Enderbury\ + UTC+13,TK,Pacific/Fakaofo\ + UTC+13,ZZ,Etc/GMT-13\ + UTC,001,Etc/UTC\ + UTC,GL,America/Danmarkshavn\ + UTC,ZZ,Etc/UTC\ + UTC-02,001,Etc/GMT+2\ + UTC-02,BR,America/Noronha\ + UTC-02,GS,Atlantic/South_Georgia\ + UTC-02,ZZ,Etc/GMT+2\ + UTC-08,001,Etc/GMT+8\ + UTC-08,PN,Pacific/Pitcairn\ + UTC-08,ZZ,Etc/GMT+8\ + UTC-09,001,Etc/GMT+9\ + UTC-09,PF,Pacific/Gambier\ + UTC-09,ZZ,Etc/GMT+9\ + UTC-11,001,Etc/GMT+11\ + UTC-11,AS,Pacific/Pago_Pago\ + UTC-11,NU,Pacific/Niue\ + UTC-11,UM,Pacific/Pago_Pago\ + UTC-11,ZZ,Etc/GMT+11\ + Ulaanbaatar Standard Time,001,Asia/Ulaanbaatar\ + Ulaanbaatar Standard Time,MN,Asia/Ulaanbaatar Asia/Choibalsan\ + Venezuela Standard Time,001,America/Caracas\ + Venezuela Standard Time,VE,America/Caracas\ + Vladivostok Standard Time,001,Asia/Vladivostok\ + Vladivostok Standard Time,RU,Asia/Vladivostok Asia/Ust-Nera\ + W. Australia Standard Time,001,Australia/Perth\ + W. Australia Standard Time,AQ,Antarctica/Casey\ + W. Australia Standard Time,AU,Australia/Perth\ + W. Central Africa Standard Time,001,Africa/Lagos\ + W. Central Africa Standard Time,AO,Africa/Lagos\ + W. Central Africa Standard Time,BJ,Africa/Lagos\ + W. Central Africa Standard Time,CD,Africa/Lagos\ + W. Central Africa Standard Time,CF,Africa/Lagos\ + W. Central Africa Standard Time,CG,Africa/Lagos\ + W. Central Africa Standard Time,CM,Africa/Lagos\ + W. Central Africa Standard Time,DZ,Africa/Algiers\ + W. Central Africa Standard Time,GA,Africa/Lagos\ + W. Central Africa Standard Time,GQ,Africa/Lagos\ + W. Central Africa Standard Time,NE,Africa/Lagos\ + W. Central Africa Standard Time,NG,Africa/Lagos\ + W. Central Africa Standard Time,TD,Africa/Ndjamena\ + W. Central Africa Standard Time,TN,Africa/Tunis\ + W. Central Africa Standard Time,ZZ,Etc/GMT-1\ + W. Europe Standard Time,001,Europe/Berlin\ + W. Europe Standard Time,AD,Europe/Andorra\ + W. Europe Standard Time,AT,Europe/Vienna\ + W. Europe Standard Time,CH,Europe/Zurich\ + W. Europe Standard Time,DE,Europe/Berlin Europe/Zurich\ + W. Europe Standard Time,GI,Europe/Gibraltar\ + W. Europe Standard Time,IT,Europe/Rome\ + W. Europe Standard Time,LI,Europe/Zurich\ + W. Europe Standard Time,LU,Europe/Luxembourg\ + W. Europe Standard Time,MC,Europe/Monaco\ + W. Europe Standard Time,MT,Europe/Malta\ + W. Europe Standard Time,NL,Europe/Amsterdam\ + W. Europe Standard Time,NO,Europe/Oslo\ + W. Europe Standard Time,SE,Europe/Stockholm\ + W. Europe Standard Time,SJ,Europe/Oslo\ + W. Europe Standard Time,SM,Europe/Rome\ + W. Europe Standard Time,VA,Europe/Rome\ + W. Mongolia Standard Time,001,Asia/Hovd\ + W. Mongolia Standard Time,MN,Asia/Hovd\ + West Asia Standard Time,001,Asia/Tashkent\ + West Asia Standard Time,AQ,Antarctica/Mawson\ + West Asia Standard Time,KZ,Asia/Oral Asia/Aqtau Asia/Aqtobe Asia/Atyrau\ + West Asia Standard Time,MV,Indian/Maldives\ + West Asia Standard Time,TF,Indian/Kerguelen\ + West Asia Standard Time,TJ,Asia/Dushanbe\ + West Asia Standard Time,TM,Asia/Ashgabat\ + West Asia Standard Time,UZ,Asia/Tashkent Asia/Samarkand\ + West Asia Standard Time,ZZ,Etc/GMT-5\ + West Bank Standard Time,001,Asia/Hebron\ + West Bank Standard Time,PS,Asia/Hebron Asia/Gaza\ + West Pacific Standard Time,001,Pacific/Port_Moresby\ + West Pacific Standard Time,AQ,Antarctica/DumontDUrville\ + West Pacific Standard Time,FM,Pacific/Chuuk\ + West Pacific Standard Time,GU,Pacific/Guam\ + West Pacific Standard Time,MP,Pacific/Guam\ + West Pacific Standard Time,PG,Pacific/Port_Moresby\ + West Pacific Standard Time,ZZ,Etc/GMT-10\ + Yakutsk Standard Time,001,Asia/Yakutsk\ + Yakutsk Standard Time,RU,Asia/Yakutsk Asia/Khandyga'; + + return timeZoneConverter; +} + +var hasRequiredConvertFromUTC; + +function requireConvertFromUTC () { + if (hasRequiredConvertFromUTC) return convertFromUTC; + hasRequiredConvertFromUTC = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (convertFromUTC && convertFromUTC.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(convertFromUTC, "__esModule", { value: true }); + convertFromUTC.ConvertFromUTC = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + /** + * Convert a timestamp from Universal Time Coordinated (UTC) to a target time zone. + */ + class ConvertFromUTC extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [ConvertFromUTC](xref:adaptive-expressions.ConvertFromUTC) class. + */ + constructor() { + super(expressionType_1.ExpressionType.ConvertFromUTC, ConvertFromUTC.evaluator, returnType_1.ReturnType.String, ConvertFromUTC.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = ConvertFromUTC.NoneUtcDefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 4, format, locale)); + if (typeof args[0] === 'string' && typeof args[1] === 'string') { + ({ value, error } = ConvertFromUTC.evalConvertFromUTC(args[0], args[1], format, locale)); + } + else { + error = `${expression} should contain an ISO format timestamp, an origin time zone string and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalConvertFromUTC(timeStamp, destinationTimeZone, format, locale) { + let result; + let error; + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(timeStamp); + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(destinationTimeZone); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${destinationTimeZone} is not a valid timezone`; + } + if (!error) { + try { + result = (0, dayjs_1.default)(timeStamp).locale(locale).tz(timeZone).format(format); + } + catch (_a) { + error = `${format} is not a valid timestamp format`; + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String, returnType_1.ReturnType.String); + } + } + convertFromUTC.ConvertFromUTC = ConvertFromUTC; + ConvertFromUTC.NoneUtcDefaultDateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS0000'; + + return convertFromUTC; +} + +var convertToUTC = {}; + +var hasRequiredConvertToUTC; + +function requireConvertToUTC () { + if (hasRequiredConvertToUTC) return convertToUTC; + hasRequiredConvertToUTC = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (convertToUTC && convertToUTC.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(convertToUTC, "__esModule", { value: true }); + convertToUTC.ConvertToUTC = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + /** + * Convert a timestamp to Universal Time Coordinated (UTC) from the source time zone. + */ + class ConvertToUTC extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [ConvertToUTC](xref:adaptive-expressions.ConvertToUTC) class. + */ + constructor() { + super(expressionType_1.ExpressionType.ConvertToUTC, ConvertToUTC.evaluator, returnType_1.ReturnType.String, ConvertToUTC.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 4, format, locale)); + if (typeof args[0] === 'string' && typeof args[1] === 'string') { + ({ value, error } = ConvertToUTC.evalConvertToUTC(args[0], args[1], format, locale)); + } + else { + error = `${expression} should contain an ISO format timestamp, a destination time zone string and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static verifyTimeStamp(timeStamp) { + const parsed = (0, dayjs_1.default)(timeStamp); + if (parsed.toString() === 'Invalid Date') { + return `${timeStamp} is a invalid datetime`; + } + return undefined; + } + /** + * @private + */ + static evalConvertToUTC(timeStamp, sourceTimezone, format, locale) { + let result; + let error; + let formattedSourceTime; + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(sourceTimezone); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${sourceTimezone} is not a valid timezone`; + } + if (!error) { + error = this.verifyTimeStamp(timeStamp); + if (!error) { + try { + const sourceTime = dayjs_1.default.tz(timeStamp, timeZone); + formattedSourceTime = sourceTime.format(); + } + catch (_a) { + error = `${timeStamp} with ${timeZone} is not a valid timestamp with specified timeZone:`; + } + if (!error) { + try { + result = (0, dayjs_1.default)(formattedSourceTime).locale(locale).tz('Etc/UTC').format(format); + } + catch (_b) { + error = `${format} is not a valid timestamp format`; + } + } + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String, returnType_1.ReturnType.String); + } + } + convertToUTC.ConvertToUTC = ConvertToUTC; + + return convertToUTC; +} + +var count = {}; + +var hasRequiredCount; + +function requireCount () { + if (hasRequiredCount) return count; + hasRequiredCount = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(count, "__esModule", { value: true }); + count.Count = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the number of items in a collection. + */ + class Count extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Count](xref:adaptive-expressions.Count) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Count, Count.evaluator(), returnType_1.ReturnType.Number, Count.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let count; + if (typeof args[0] === 'string' || Array.isArray(args[0])) { + count = args[0].length; + } + else if (args[0] instanceof Map) { + count = args[0].size; + } + else if (typeof args[0] === 'object') { + count = Object.keys(args[0]).length; + } + return count; + }, functionUtils_1.FunctionUtils.verifyContainer); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.String | returnType_1.ReturnType.Array); + } + } + count.Count = Count; + + return count; +} + +var countWord = {}; + +var hasRequiredCountWord; + +function requireCountWord () { + if (hasRequiredCountWord) return countWord; + hasRequiredCountWord = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(countWord, "__esModule", { value: true }); + countWord.CountWord = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the number of words in a string. + */ + class CountWord extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [CountWord](xref:adaptive-expressions.CountWord) class. + */ + constructor() { + super(expressionType_1.ExpressionType.CountWord, CountWord.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).trim().split(/\s+/).length, functionUtils_1.FunctionUtils.verifyStringOrNull); + } + } + countWord.CountWord = CountWord; + + return countWord; +} + +var createArray = {}; + +var hasRequiredCreateArray; + +function requireCreateArray () { + if (hasRequiredCreateArray) return createArray; + hasRequiredCreateArray = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(createArray, "__esModule", { value: true }); + createArray.CreateArray = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return an array from multiple inputs. + */ + class CreateArray extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [CreateArray](xref:adaptive-expressions.CreateArray) class. + */ + constructor() { + super(expressionType_1.ExpressionType.CreateArray, CreateArray.evaluator(), returnType_1.ReturnType.Array); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => Array.from(args)); + } + } + createArray.CreateArray = CreateArray; + + return createArray; +} + +var dataUri = {}; + +var hasRequiredDataUri; + +function requireDataUri () { + if (hasRequiredDataUri) return dataUri; + hasRequiredDataUri = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dataUri && dataUri.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dataUri, "__esModule", { value: true }); + dataUri.DataUri = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const btoa_lite_1 = __importDefault(requireBtoaNode()); + /** + * Return a data uniform resource identifier (URI) of a string. + */ + class DataUri extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DataUri](xref:adaptive-expressions.DataUri) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DataUri, DataUri.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => 'data:text/plain;charset=utf-8;base64,'.concat((0, btoa_lite_1.default)(args[0])), functionUtils_1.FunctionUtils.verifyString); + } + } + dataUri.DataUri = DataUri; + + return dataUri; +} + +var dataUriToBinary = {}; + +var hasRequiredDataUriToBinary; + +function requireDataUriToBinary () { + if (hasRequiredDataUriToBinary) return dataUriToBinary; + hasRequiredDataUriToBinary = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(dataUriToBinary, "__esModule", { value: true }); + dataUriToBinary.DataUriToBinary = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the binary version of a data uniform resource identifier (URI). + */ + class DataUriToBinary extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DataUriToBinary](xref:adaptive-expressions.DataUriToBinary) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DataUriToBinary, DataUriToBinary.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.getTextEncoder().encode(args[0]), functionUtils_1.FunctionUtils.verifyString); + } + } + dataUriToBinary.DataUriToBinary = DataUriToBinary; + + return dataUriToBinary; +} + +var dataUriToString = {}; + +var hasRequiredDataUriToString; + +function requireDataUriToString () { + if (hasRequiredDataUriToString) return dataUriToString; + hasRequiredDataUriToString = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dataUriToString && dataUriToString.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dataUriToString, "__esModule", { value: true }); + dataUriToString.DataUriToString = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const atob_lite_1 = __importDefault(requireAtobNode()); + /** + * Return the string version of a data uniform resource identifier (URI). + */ + class DataUriToString extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DataUriToString](xref:adaptive-expressions.DataUriToString) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DataUriToString, DataUriToString.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => (0, atob_lite_1.default)(args[0].slice(args[0].indexOf(',') + 1)), functionUtils_1.FunctionUtils.verifyString); + } + } + dataUriToString.DataUriToString = DataUriToString; + + return dataUriToString; +} + +var dateFunc = {}; + +var hasRequiredDateFunc; + +function requireDateFunc () { + if (hasRequiredDateFunc) return dateFunc; + hasRequiredDateFunc = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dateFunc && dateFunc.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dateFunc, "__esModule", { value: true }); + dateFunc.DateFunc = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the date of a specified timestamp in m/dd/yyyy format. + */ + class DateFunc extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DateFunc](xref:adaptive-expressions.DateFunc) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Date, DateFunc.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + return { value: (0, dayjs_1.default)(args[0]).utc().format('M/DD/YYYY'), error }; + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + dateFunc.DateFunc = DateFunc; + + return dateFunc; +} + +var dateReadBack = {}; + +var hasRequiredDateReadBack; + +function requireDateReadBack () { + if (hasRequiredDateReadBack) return dateReadBack; + hasRequiredDateReadBack = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dateReadBack && dateReadBack.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dateReadBack, "__esModule", { value: true }); + dateReadBack.DateReadBack = void 0; + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + const dayjs_1 = __importDefault(requireDayjs_min()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Uses the date-time library to provide a date readback. + */ + class DateReadBack extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DateReadBack](xref:adaptive-expressions.DateReadBack) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DateReadBack, DateReadBack.evaluator(), returnType_1.ReturnType.String, DateReadBack.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const dateFormat = 'YYYY-MM-DD'; + let error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + const timestamp1 = (0, dayjs_1.default)(args[0]).toDate(); + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[1]); + if (!error) { + const timestamp2 = (0, dayjs_1.default)(args[1]).format(dateFormat); + const timex = new recognizers_text_data_types_timex_expression_1.TimexProperty(timestamp2); + return { value: timex.toNaturalLanguage(timestamp1), error }; + } + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.String, returnType_1.ReturnType.String); + } + } + dateReadBack.DateReadBack = DateReadBack; + + return dateReadBack; +} + +var dateTimeDiff = {}; + +var hasRequiredDateTimeDiff; + +function requireDateTimeDiff () { + if (hasRequiredDateTimeDiff) return dateTimeDiff; + hasRequiredDateTimeDiff = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dateTimeDiff && dateTimeDiff.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dateTimeDiff, "__esModule", { value: true }); + dateTimeDiff.DateTimeDiff = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const returnType_1 = requireReturnType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + /** + * Return a number of ticks that the two timestamps differ. + */ + class DateTimeDiff extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DateTimeDiff](xref:adaptive-expressions.DateTimeDiff) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DateTimeDiff, DateTimeDiff.evaluator, returnType_1.ReturnType.Number, DateTimeDiff.validator); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[1]); + if (!error) { + value = (0, dayjs_1.default)(args[0]).diff((0, dayjs_1.default)(args[1]), 'milliseconds') * 10000; + } + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.String); + } + } + dateTimeDiff.DateTimeDiff = DateTimeDiff; + + return dateTimeDiff; +} + +var dayOfMonth = {}; + +var hasRequiredDayOfMonth; + +function requireDayOfMonth () { + if (hasRequiredDayOfMonth) return dayOfMonth; + hasRequiredDayOfMonth = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(dayOfMonth, "__esModule", { value: true }); + dayOfMonth.DayOfMonth = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the day of the month from a timestamp. + */ + class DayOfMonth extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DayOfMonth](xref:adaptive-expressions.DayOfMonth) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DayOfMonth, DayOfMonth.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + return { value: new Date(args[0]).getUTCDate(), error }; + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + dayOfMonth.DayOfMonth = DayOfMonth; + + return dayOfMonth; +} + +var dayOfWeek = {}; + +var hasRequiredDayOfWeek; + +function requireDayOfWeek () { + if (hasRequiredDayOfWeek) return dayOfWeek; + hasRequiredDayOfWeek = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(dayOfWeek, "__esModule", { value: true }); + dayOfWeek.DayOfWeek = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the day of the week from a timestamp. + */ + class DayOfWeek extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DayOfWeek](xref:adaptive-expressions.DayOfWeek) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DayOfWeek, DayOfWeek.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + return { value: new Date(args[0]).getUTCDay(), error }; + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + dayOfWeek.DayOfWeek = DayOfWeek; + + return dayOfWeek; +} + +var dayOfYear$2 = {}; + +var dayOfYear$1 = {exports: {}}; + +var dayOfYear = dayOfYear$1.exports; + +var hasRequiredDayOfYear$1; + +function requireDayOfYear$1 () { + if (hasRequiredDayOfYear$1) return dayOfYear$1.exports; + hasRequiredDayOfYear$1 = 1; + (function (module, exports) { + !function(e,t){module.exports=t();}(dayOfYear,(function(){return function(e,t,n){t.prototype.dayOfYear=function(e){var t=Math.round((n(this).startOf("day")-n(this).startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"day")};}})); + } (dayOfYear$1)); + return dayOfYear$1.exports; +} + +var hasRequiredDayOfYear; + +function requireDayOfYear () { + if (hasRequiredDayOfYear) return dayOfYear$2; + hasRequiredDayOfYear = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (dayOfYear$2 && dayOfYear$2.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(dayOfYear$2, "__esModule", { value: true }); + dayOfYear$2.DayOfYear = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const dayOfYear_1 = __importDefault(requireDayOfYear$1()); + dayjs_1.default.extend(dayOfYear_1.default); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the day of the year from a timestamp. + */ + class DayOfYear extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [DayOfYear](xref:adaptive-expressions.DayOfYear) class. + */ + constructor() { + super(expressionType_1.ExpressionType.DayOfYear, DayOfYear.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + return { value: (0, dayjs_1.default)(args[0]).utc().dayOfYear(), error }; + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + dayOfYear$2.DayOfYear = DayOfYear; + + return dayOfYear$2; +} + +var divide = {}; + +var multivariateNumericEvaluator = {}; + +var hasRequiredMultivariateNumericEvaluator; + +function requireMultivariateNumericEvaluator () { + if (hasRequiredMultivariateNumericEvaluator) return multivariateNumericEvaluator; + hasRequiredMultivariateNumericEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(multivariateNumericEvaluator, "__esModule", { value: true }); + multivariateNumericEvaluator.MultivariateNumericEvaluator = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Numeric operators that can have 2 or more args. + */ + class MultivariateNumericEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [MultivariateNumericEvaluator](xref:adaptive-expressions.MultivariateNumericEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The evaluation function, it takes a list of objects and returns a number. + * @param verify Optional. [VerifyExpression](xref:adaptive-expressions.VerifyExpression) function to verify each child's result. + */ + constructor(type, func, verify) { + super(type, MultivariateNumericEvaluator.evaluator(func, verify), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateTwoOrMoreThanTwoNumbers); + } + /** + * @private + */ + static evaluator(func, verify) { + return functionUtils_1.FunctionUtils.applySequence(func, verify || functionUtils_1.FunctionUtils.verifyNumber); + } + } + multivariateNumericEvaluator.MultivariateNumericEvaluator = MultivariateNumericEvaluator; + + return multivariateNumericEvaluator; +} + +var hasRequiredDivide; + +function requireDivide () { + if (hasRequiredDivide) return divide; + hasRequiredDivide = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(divide, "__esModule", { value: true }); + divide.Divide = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const multivariateNumericEvaluator_1 = requireMultivariateNumericEvaluator(); + /** + * Return the integer result from dividing two numbers. + */ + class Divide extends multivariateNumericEvaluator_1.MultivariateNumericEvaluator { + /** + * Initializes a new instance of the [Divide](xref:adaptive-expressions.Divide) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Divide, Divide.func, Divide.verify); + } + /** + * @private + */ + static func(args) { + const result = Number(args[0]) / Number(args[1]); + if (Number.isInteger(args[0]) && Number.isInteger(args[1])) { + return Math.floor(result); + } + return result; + } + /** + * @private + */ + static verify(val, expression, pos) { + let error = functionUtils_1.FunctionUtils.verifyNumber(val, expression, pos); + if (!error && pos > 0 && Number(val) === 0) { + error = `Cannot divide by 0 from ${expression}`; + } + return error; + } + } + divide.Divide = Divide; + + return divide; +} + +var element = {}; + +var hasRequiredElement; + +function requireElement () { + if (hasRequiredElement) return element; + hasRequiredElement = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(element, "__esModule", { value: true }); + element.Element = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const options_1 = requireOptions(); + const returnType_1 = requireReturnType(); + /** + * The indexing operator ([ ]) selects a single element from a sequence. + * Support number index for list or string index for object. + */ + class Element extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Element](xref:adaptive-expressions.Element) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Element, Element.evaluator, returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateBinary); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + const instance = expression.children[0]; + const index = expression.children[1]; + const { value: inst, error: evalError } = instance.tryEvaluate(state, options); + let error = evalError; + if (!error) { + let idxValue; + const newOptions = new options_1.Options(options); + newOptions.nullSubstitution = undefined; + ({ value: idxValue, error } = index.tryEvaluate(state, newOptions)); + if (!error) { + if (Number.isInteger(idxValue)) { + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.accessIndex(inst, Number(idxValue))); + } + else if (typeof idxValue === 'string') { + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.accessProperty(inst, idxValue.toString())); + } + else { + error = `Could not coerce ${index} to an int or string.`; + } + return { value, error }; + } + } + } + } + element.Element = Element; + + return element; +} + +var empty = {}; + +var hasRequiredEmpty; + +function requireEmpty () { + if (hasRequiredEmpty) return empty; + hasRequiredEmpty = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(empty, "__esModule", { value: true }); + empty.Empty = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether an instance is empty. Return true if the input is empty. Empty means: + * 1.Input is null or undefined. + * 2.Input is a null or empty string. + * 3.Input is zero size collection. + * 4.Input is an object with no property. + */ + class Empty extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [Empty](xref:adaptive-expressions.Empty) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Empty, Empty.func, functionUtils_1.FunctionUtils.validateUnary, functionUtils_1.FunctionUtils.verifyContainerOrNull); + } + /** + * @private + */ + static func(args) { + return Empty.isEmpty(args[0]); + } + /** + * @private + */ + static isEmpty(instance) { + let result; + if (instance == null) { + result = true; + } + else if (typeof instance === 'string') { + result = instance === ''; + } + else if (Array.isArray(instance)) { + result = instance.length === 0; + } + else if (instance instanceof Map) { + result = instance.size === 0; + } + else { + result = Object.keys(instance).length === 0; + } + return result; + } + } + empty.Empty = Empty; + + return empty; +} + +var endsWith = {}; + +var hasRequiredEndsWith; + +function requireEndsWith () { + if (hasRequiredEndsWith) return endsWith; + hasRequiredEndsWith = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(endsWith, "__esModule", { value: true }); + endsWith.EndsWith = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Check whether a string ends with a specific substring. Return true if the substring is found, or return false if not found. + * This function is case-insensitive. + */ + class EndsWith extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [EndsWith](xref:adaptive-expressions.EndsWith) class. + */ + constructor() { + super(expressionType_1.ExpressionType.EndsWith, EndsWith.evaluator(), returnType_1.ReturnType.Boolean, EndsWith.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).endsWith(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1])), functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.String); + } + } + endsWith.EndsWith = EndsWith; + + return endsWith; +} + +var eol = {}; + +var hasRequiredEol; + +function requireEol () { + if (hasRequiredEol) return eol; + hasRequiredEol = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (eol && eol.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(eol, "__esModule", { value: true }); + eol.EOL = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const os_1 = __importDefault(os__default); + /** + * Return the newline string according to the environment. + */ + class EOL extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [EOL](xref:adaptive-expressions.EOL) class. + */ + constructor() { + super(expressionType_1.ExpressionType.EOL, EOL.evaluator(), returnType_1.ReturnType.String, EOL.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply(() => EOL.platformSpecificEOL()); + } + /** + * @private + */ + static platformSpecificEOL() { + if (typeof window !== 'undefined') { + return window.navigator.platform.includes('Win') ? '\r\n' : '\n'; + } + else if (typeof self !== 'undefined') { + return self.navigator.platform.includes('Win') ? '\r\n' : '\n'; + } + else { + return os_1.default.EOL; + } + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 0, 0); + } + } + eol.EOL = EOL; + + return eol; +} + +var equal = {}; + +var hasRequiredEqual; + +function requireEqual () { + if (hasRequiredEqual) return equal; + hasRequiredEqual = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(equal, "__esModule", { value: true }); + equal.Equal = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether both values, expressions, or objects are equivalent. + * Return true if both are equivalent, or return false if they're not equivalent. + */ + class Equal extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [Equal](xref:adaptive-expressions.Equal) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Equal, (args) => functionUtils_1.FunctionUtils.commonEquals(args[0], args[1]), functionUtils_1.FunctionUtils.validateBinary); + } + } + equal.Equal = Equal; + + return equal; +} + +var exists = {}; + +var hasRequiredExists; + +function requireExists () { + if (hasRequiredExists) return exists; + hasRequiredExists = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(exists, "__esModule", { value: true }); + exists.Exists = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Evaluates an expression for truthiness. + */ + class Exists extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [Exists](xref:adaptive-expressions.Exists) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Exists, Exists.func, functionUtils_1.FunctionUtils.validateUnary, functionUtils_1.FunctionUtils.verifyNotNull); + } + /** + * @private + */ + static func(args) { + return args[0] != null; + } + } + exists.Exists = Exists; + + return exists; +} + +var flatten = {}; + +var hasRequiredFlatten; + +function requireFlatten () { + if (hasRequiredFlatten) return flatten; + hasRequiredFlatten = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(flatten, "__esModule", { value: true }); + flatten.Flatten = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Flatten an array into non-array values. You can optionally set the maximum depth to flatten to. + */ + class Flatten extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Flatten](xref:adaptive-expressions.Flatten) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Flatten, Flatten.evaluator(), returnType_1.ReturnType.Array, Flatten.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + const array = args[0]; + const depth = args.length > 1 ? args[1] : 100; + return Flatten.evalFlatten(array, depth); + }); + } + /** + * @private + */ + static evalFlatten(arr, dept) { + if (!functionUtils_1.FunctionUtils.isNumber(dept) || dept < 1) { + dept = 1; + } + let res = JSON.parse(JSON.stringify(arr)); + const reduceArr = (_arr) => _arr.reduce((prevItem, curItem) => prevItem.concat(curItem), []); + for (let i = 0; i < dept; i++) { + const hasArrayItem = res.some((item) => Array.isArray(item)); + if (hasArrayItem) { + res = reduceArr(res); + } + else { + break; + } + } + return res; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.Number], returnType_1.ReturnType.Array); + } + } + flatten.Flatten = Flatten; + + return flatten; +} + +var first = {}; + +var hasRequiredFirst; + +function requireFirst () { + if (hasRequiredFirst) return first; + hasRequiredFirst = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(first, "__esModule", { value: true }); + first.First = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the first item from a string or array. + */ + class First extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [First](xref:adaptive-expressions.First) class. + */ + constructor() { + super(expressionType_1.ExpressionType.First, First.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let first; + if (typeof args[0] === 'string' && args[0].length > 0) { + first = args[0][0]; + } + if (Array.isArray(args[0]) && args[0].length > 0) { + first = functionUtils_internal_1.InternalFunctionUtils.accessIndex(args[0], 0).value; + } + return first; + }); + } + } + first.First = First; + + return first; +} + +var float = {}; + +var hasRequiredFloat; + +function requireFloat () { + if (hasRequiredFloat) return float; + hasRequiredFloat = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (float && float.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(float, "__esModule", { value: true }); + float.Float = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const big_integer_1 = __importDefault(requireBigInteger()); + /** + * Convert the string version of a floating-point number to a floating-point number. + */ + class Float extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Float](xref:adaptive-expressions.Float) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Float, Float.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const firstChild = args[0]; + let error; + let value; + if (big_integer_1.default.isInstance(firstChild)) { + return { value: firstChild.toJSNumber(), error }; + } + if (typeof firstChild === 'string') { + value = parseFloat(firstChild); + if (!functionUtils_1.FunctionUtils.isNumber(value)) { + error = `parameter ${args[0]} is not a valid number string.`; + } + } + else if (functionUtils_1.FunctionUtils.isNumber(firstChild)) { + value = firstChild; + } + return { value, error }; + }); + } + } + float.Float = Float; + + return float; +} + +var floor = {}; + +var hasRequiredFloor; + +function requireFloor () { + if (hasRequiredFloor) return floor; + hasRequiredFloor = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(floor, "__esModule", { value: true }); + floor.Floor = void 0; + const expressionType_1 = requireExpressionType(); + const numberTransformEvaluator_1 = requireNumberTransformEvaluator(); + /** + * Returns the largest integer less than or equal to the specified number. + */ + class Floor extends numberTransformEvaluator_1.NumberTransformEvaluator { + /** + * Initializes a new instance of the [Floor](xref:adaptive-expressions.Floor) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Floor, Floor.func); + } + /** + * @private + */ + static func(args) { + return Math.floor(args[0]); + } + } + floor.Floor = Floor; + + return floor; +} + +var foreach = {}; + +var hasRequiredForeach; + +function requireForeach () { + if (hasRequiredForeach) return foreach; + hasRequiredForeach = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(foreach, "__esModule", { value: true }); + foreach.Foreach = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Operate on each element and return the new collection. + */ + class Foreach extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Foreach](xref:adaptive-expressions.Foreach) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Foreach, functionUtils_internal_1.InternalFunctionUtils.foreach, returnType_1.ReturnType.Array, functionUtils_internal_1.InternalFunctionUtils.ValidateLambdaExpression); + } + } + foreach.Foreach = Foreach; + + return foreach; +} + +var formatDateTime = {}; + +var hasRequiredFormatDateTime; + +function requireFormatDateTime () { + if (hasRequiredFormatDateTime) return formatDateTime; + hasRequiredFormatDateTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (formatDateTime && formatDateTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(formatDateTime, "__esModule", { value: true }); + formatDateTime.FormatDateTime = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return a timestamp in the specified format. + * Format reference: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings + */ + class FormatDateTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [FormatDateTime](xref:adaptive-expressions.FormatDateTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.FormatDateTime, FormatDateTime.evaluator(), returnType_1.ReturnType.String, FormatDateTime.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let error; + let arg = args[0]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + if (typeof arg === 'string') { + error = functionUtils_internal_1.InternalFunctionUtils.verifyTimestamp(arg.toString()); + } + else { + arg = arg.toISOString(); + } + let value; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + let dateString; + if (arg.endsWith('Z')) { + dateString = new Date(arg).toISOString(); + } + else { + try { + dateString = new Date(`${arg}Z`).toISOString(); + } + catch (_a) { + dateString = new Date(arg).toISOString(); + } + } + value = (0, dayjs_1.default)(dateString).locale(locale).utc().format(format); + } + return { value, error }; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String); + } + } + formatDateTime.FormatDateTime = FormatDateTime; + + return formatDateTime; +} + +var formatEpoch = {}; + +var hasRequiredFormatEpoch; + +function requireFormatEpoch () { + if (hasRequiredFormatEpoch) return formatEpoch; + hasRequiredFormatEpoch = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (formatEpoch && formatEpoch.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(formatEpoch, "__esModule", { value: true }); + formatEpoch.FormatEpoch = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return a timestamp in the specified format from UNIX time (also know as Epoch time, POSIX time, UNIX Epoch time). + */ + class FormatEpoch extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [FormatEpoch](xref:adaptive-expressions.FormatEpoch) class. + */ + constructor() { + super(expressionType_1.ExpressionType.FormatEpoch, FormatEpoch.evaluator(), returnType_1.ReturnType.String, FormatEpoch.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let error; + let arg = args[0]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + if (!functionUtils_1.FunctionUtils.isNumber(arg)) { + error = `formatEpoch first argument ${arg} must be a number`; + } + else { + // Convert to ms + arg = arg * 1000; + } + let value; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + const dateString = new Date(arg).toISOString(); + value = (0, dayjs_1.default)(dateString).locale(locale).utc().format(format); + } + return { value, error }; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.Number); + } + } + formatEpoch.FormatEpoch = FormatEpoch; + + return formatEpoch; +} + +var formatNumber = {}; + +var d3Format; +var hasRequiredD3Format; + +function requireD3Format () { + if (hasRequiredD3Format) return d3Format; + hasRequiredD3Format = 1; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + + // node_modules/d3-format/src/index.js + var index_exports = {}; + __export(index_exports, { + FormatSpecifier: () => FormatSpecifier, + format: () => format, + formatDefaultLocale: () => defaultLocale, + formatLocale: () => locale_default, + formatPrefix: () => formatPrefix, + formatSpecifier: () => formatSpecifier, + precisionFixed: () => precisionFixed_default, + precisionPrefix: () => precisionPrefix_default, + precisionRound: () => precisionRound_default + }); + d3Format = __toCommonJS(index_exports); + + // node_modules/d3-format/src/formatDecimal.js + function formatDecimal_default(x) { + return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10); + } + function formatDecimalParts(x, p) { + if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; + var i, coefficient = x.slice(0, i); + return [ + coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, + +x.slice(i + 1) + ]; + } + + // node_modules/d3-format/src/exponent.js + function exponent_default(x) { + return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN; + } + + // node_modules/d3-format/src/formatGroup.js + function formatGroup_default(grouping, thousands) { + return function(value, width) { + var i = value.length, t = [], j = 0, g = grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = grouping[j = (j + 1) % grouping.length]; + } + return t.reverse().join(thousands); + }; + } + + // node_modules/d3-format/src/formatNumerals.js + function formatNumerals_default(numerals) { + return function(value) { + return value.replace(/[0-9]/g, function(i) { + return numerals[+i]; + }); + }; + } + + // node_modules/d3-format/src/formatSpecifier.js + var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i; + function formatSpecifier(specifier) { + if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); + var match; + return new FormatSpecifier({ + fill: match[1], + align: match[2], + sign: match[3], + symbol: match[4], + zero: match[5], + width: match[6], + comma: match[7], + precision: match[8] && match[8].slice(1), + trim: match[9], + type: match[10] + }); + } + formatSpecifier.prototype = FormatSpecifier.prototype; + function FormatSpecifier(specifier) { + this.fill = specifier.fill === void 0 ? " " : specifier.fill + ""; + this.align = specifier.align === void 0 ? ">" : specifier.align + ""; + this.sign = specifier.sign === void 0 ? "-" : specifier.sign + ""; + this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + ""; + this.zero = !!specifier.zero; + this.width = specifier.width === void 0 ? void 0 : +specifier.width; + this.comma = !!specifier.comma; + this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision; + this.trim = !!specifier.trim; + this.type = specifier.type === void 0 ? "" : specifier.type + ""; + } + FormatSpecifier.prototype.toString = function() { + return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type; + }; + + // node_modules/d3-format/src/formatTrim.js + function formatTrim_default(s) { + out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { + switch (s[i]) { + case ".": + i0 = i1 = i; + break; + case "0": + if (i0 === 0) i0 = i; + i1 = i; + break; + default: + if (!+s[i]) break out; + if (i0 > 0) i0 = 0; + break; + } + } + return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; + } + + // node_modules/d3-format/src/formatPrefixAuto.js + var prefixExponent; + function formatPrefixAuto_default(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return x + ""; + var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length; + return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; + } + + // node_modules/d3-format/src/formatRounded.js + function formatRounded_default(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return x + ""; + var coefficient = d[0], exponent = d[1]; + return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0"); + } + + // node_modules/d3-format/src/formatTypes.js + var formatTypes_default = { + "%": (x, p) => (x * 100).toFixed(p), + "b": (x) => Math.round(x).toString(2), + "c": (x) => x + "", + "d": formatDecimal_default, + "e": (x, p) => x.toExponential(p), + "f": (x, p) => x.toFixed(p), + "g": (x, p) => x.toPrecision(p), + "o": (x) => Math.round(x).toString(8), + "p": (x, p) => formatRounded_default(x * 100, p), + "r": formatRounded_default, + "s": formatPrefixAuto_default, + "X": (x) => Math.round(x).toString(16).toUpperCase(), + "x": (x) => Math.round(x).toString(16) + }; + + // node_modules/d3-format/src/identity.js + function identity_default(x) { + return x; + } + + // node_modules/d3-format/src/locale.js + var map = Array.prototype.map; + var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"]; + function locale_default(locale2) { + var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity_default : formatGroup_default(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity_default : formatNumerals_default(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "\u2212" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + ""; + function newFormat(specifier) { + specifier = formatSpecifier(specifier); + var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type; + if (type === "n") comma = true, type = "g"; + else if (!formatTypes_default[type]) precision === void 0 && (precision = 12), trim = true, type = "g"; + if (zero || fill === "0" && align === "=") zero = true, fill = "0", align = "="; + var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : ""; + var formatType = formatTypes_default[type], maybeSuffix = /[defgprs%]/.test(type); + precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); + function format2(value) { + var valuePrefix = prefix, valueSuffix = suffix, i, n, c; + if (type === "c") { + valueSuffix = formatType(value) + valueSuffix; + value = ""; + } else { + value = +value; + var valueNegative = value < 0 || 1 / value < 0; + value = isNaN(value) ? nan : formatType(Math.abs(value), precision); + if (trim) value = formatTrim_default(value); + if (valueNegative && +value === 0 && sign !== "+") valueNegative = false; + valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix; + valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : ""); + if (maybeSuffix) { + i = -1, n = value.length; + while (++i < n) { + if (c = value.charCodeAt(i), 48 > c || c > 57) { + valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; + value = value.slice(0, i); + break; + } + } + } + } + if (comma && !zero) value = group(value, Infinity); + var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : ""; + if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; + switch (align) { + case "<": + value = valuePrefix + value + valueSuffix + padding; + break; + case "=": + value = valuePrefix + padding + value + valueSuffix; + break; + case "^": + value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); + break; + default: + value = padding + valuePrefix + value + valueSuffix; + break; + } + return numerals(value); + } + format2.toString = function() { + return specifier + ""; + }; + return format2; + } + function formatPrefix2(specifier, value) { + var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; + return function(value2) { + return f(k * value2) + prefix; + }; + } + return { + format: newFormat, + formatPrefix: formatPrefix2 + }; + } + + // node_modules/d3-format/src/defaultLocale.js + var locale; + var format; + var formatPrefix; + defaultLocale({ + thousands: ",", + grouping: [3], + currency: ["$", ""] + }); + function defaultLocale(definition) { + locale = locale_default(definition); + format = locale.format; + formatPrefix = locale.formatPrefix; + return locale; + } + + // node_modules/d3-format/src/precisionFixed.js + function precisionFixed_default(step) { + return Math.max(0, -exponent_default(Math.abs(step))); + } + + // node_modules/d3-format/src/precisionPrefix.js + function precisionPrefix_default(step, value) { + return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3 - exponent_default(Math.abs(step))); + } + + // node_modules/d3-format/src/precisionRound.js + function precisionRound_default(step, max) { + step = Math.abs(step), max = Math.abs(max) - step; + return Math.max(0, exponent_default(max) - exponent_default(step)) + 1; + } + + return d3Format; +} + +var localeInfo = {}; + +var hasRequiredLocaleInfo; + +function requireLocaleInfo () { + if (hasRequiredLocaleInfo) return localeInfo; + hasRequiredLocaleInfo = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(localeInfo, "__esModule", { value: true }); + localeInfo.localeInfo = void 0; + /** + * locale info of decimal, thousands, grouping and currency. + */ + localeInfo.localeInfo = { + 'ar-MA': { + currency: ['\u062f.\u0645. ', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'en-IN': { + currency: ['\u20b9', ''], + decimal: '.', + thousands: ',', + grouping: [3, 2, 2, 2, 2, 2, 2, 2, 2, 2], + }, + 'ar-BH': { + currency: ['', ' \u062f.\u0628.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-PS': { + currency: ['\u20aa ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'en-IE': { + currency: ['\u20ac', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'it-IT': { + currency: ['\u20ac', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-EG': { + currency: ['', ' \u062c.\u0645.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-IQ': { + currency: ['', ' \u062f.\u0639.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-EH': { + currency: ['\u062f.\u0645. ', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'ar-AE': { + currency: ['', ' \u062f.\u0625.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-MR': { + currency: ['', ' \u0623.\u0645.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'uk-UA': { + currency: ['', '\u00a0\u20b4.'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'ca-ES': { + currency: ['', '\u00a0\u20ac'], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'sv-SE': { + currency: ['', ' kr'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'ja-JP': { + currency: ['', '\u5186'], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'es-ES': { + currency: ['', '\u00a0\u20ac'], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'fi-FI': { + currency: ['', '\u00a0\u20ac'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'ar-DZ': { + currency: ['\u062f.\u062c. ', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'en-GB': { + currency: ['\u00a3', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'cs-CZ': { + currency: ['', '\u00a0K\u010d'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'ar-TD': { + currency: ['\u200fFCFA ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'de-CH': { + currency: ['', '\u00a0CHF'], + decimal: ',', + thousands: "'", + grouping: [3], + }, + 'nl-NL': { + currency: ['\u20ac\u00a0', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'es-BO': { + currency: ['Bs\u00a0', ''], + decimal: ',', + percent: '\u202f%', + thousands: '.', + grouping: [3], + }, + 'ar-SY': { + currency: ['', ' \u0644.\u0633.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-JO': { + currency: ['', ' \u062f.\u0623.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'en-CA': { + currency: ['$', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'ar-ER': { + currency: ['Nfk ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-LB': { + currency: ['', ' \u0644.\u0644.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'fr-CA': { + currency: ['', '$'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'ar-TN': { + currency: ['\u062f.\u062a. ', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-YE': { + currency: ['', ' \u0631.\u0649.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ru-RU': { + currency: ['', '\u00a0\u0440\u0443\u0431.'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'en-US': { + currency: ['$', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'ar-SS': { + currency: ['\u00a3 ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-SO': { + currency: ['\u200fS ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'hu-HU': { + currency: ['', '\u00a0Ft'], + decimal: ',', + thousands: '\u00a0', + grouping: [3], + }, + 'pt-BR': { + currency: ['R$', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-DJ': { + currency: ['\u200fFdj ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-SD': { + currency: ['', ' \u062c.\u0633.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-001': { + currency: ['', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-LY': { + currency: ['\u062f.\u0644. ', ''], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-SA': { + currency: ['', ' \u0631.\u0633.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'ar-KW': { + currency: ['', ' \u062f.\u0643.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'pl-PL': { + currency: ['', 'z\u0142'], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-QA': { + currency: ['', ' \u0631.\u0642.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'mk-MK': { + currency: ['', '\u00a0\u0434\u0435\u043d.'], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ko-KR': { + currency: ['\u20a9', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'es-MX': { + currency: ['$', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'ar-IL': { + currency: ['\u20aa ', ''], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'zh-CN': { + currency: ['\u00a5', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + 'de-DE': { + currency: ['', '\u00a0\u20ac'], + decimal: ',', + thousands: '.', + grouping: [3], + }, + 'ar-OM': { + currency: ['', ' \u0631.\u0639.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'fr-FR': { + currency: ['', '\u00a0\u20ac'], + decimal: ',', + percent: '\u202f%', + thousands: '\u00a0', + grouping: [3], + }, + 'ar-KM': { + currency: ['', ' \u0641.\u062c.\u0642.'], + decimal: '\u066b', + thousands: '\u066c', + numerals: ['\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'], + grouping: [3], + }, + 'he-IL': { + currency: ['\u20aa', ''], + decimal: '.', + thousands: ',', + grouping: [3], + }, + }; + + return localeInfo; +} + +var hasRequiredFormatNumber; + +function requireFormatNumber () { + if (hasRequiredFormatNumber) return formatNumber; + hasRequiredFormatNumber = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(formatNumber, "__esModule", { value: true }); + formatNumber.FormatNumber = void 0; + const d3_format_1 = requireD3Format(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const localeInfo_1 = requireLocaleInfo(); + /** + * Format number into required decimal numbers. + */ + class FormatNumber extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [FormatNumber](xref:adaptive-expressions.FormatNumber) class. + */ + constructor() { + super(expressionType_1.ExpressionType.FormatNumber, FormatNumber.evaluator(), returnType_1.ReturnType.String, FormatNumber.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let value = null; + let error; + const number = args[0]; + const precision = args[1]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = functionUtils_1.FunctionUtils.determineLocale(args, 3, locale); + if (!functionUtils_1.FunctionUtils.isNumber(number)) { + error = `formatNumber first argument ${number} must be a number`; + } + else if (!functionUtils_1.FunctionUtils.isNumber(precision)) { + error = `formatNumber second argument ${precision} must be a number`; + } + else if (locale && typeof locale !== 'string') { + error = `formatNubmer third argument ${locale} is not a valid locale`; + } + else { + const fixedNotation = `,.${precision}f`; + const roundedNumber = this.roundToPrecision(number, precision); + const formatLocale = localeInfo_1.localeInfo[locale]; + if (formatLocale !== undefined) { + value = (0, d3_format_1.formatLocale)(formatLocale).format(fixedNotation)(roundedNumber); + } + else { + value = (0, d3_format_1.format)(fixedNotation)(roundedNumber); + } + } + return { value, error }; + }); + } + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, [returnType_1.ReturnType.String], returnType_1.ReturnType.Number, returnType_1.ReturnType.Number); + } + } + formatNumber.FormatNumber = FormatNumber; + FormatNumber.roundToPrecision = (num, digits) => Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits); + + return formatNumber; +} + +var formatTicks = {}; + +var hasRequiredFormatTicks; + +function requireFormatTicks () { + if (hasRequiredFormatTicks) return formatTicks; + hasRequiredFormatTicks = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (formatTicks && formatTicks.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(formatTicks, "__esModule", { value: true }); + formatTicks.FormatTicks = void 0; + const big_integer_1 = __importDefault(requireBigInteger()); + const dayjs_1 = __importDefault(requireDayjs_min()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return a timestamp in the specified format from ticks. + */ + class FormatTicks extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [FormatTicks](xref:adaptive-expressions.FormatTicks) class. + */ + constructor() { + super(expressionType_1.ExpressionType.FormatTicks, FormatTicks.evaluator(), returnType_1.ReturnType.String, FormatTicks.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let error; + let arg = args[0]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + if (functionUtils_1.FunctionUtils.isNumber(arg)) { + arg = (0, big_integer_1.default)(arg); + } + if (typeof arg === 'string') { + arg = (0, big_integer_1.default)(arg); + } + if (!big_integer_1.default.isInstance(arg)) { + error = `formatTicks first argument ${arg} is not a number, numeric string or bigInt`; + } + else { + // Convert to ms + arg = arg + .subtract(functionUtils_internal_1.InternalFunctionUtils.UnixMilliSecondToTicksConstant) + .divide(functionUtils_internal_1.InternalFunctionUtils.MillisecondToTickConstant) + .toJSNumber(); + } + let value; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + if (functionUtils_1.FunctionUtils.isNumber(arg)) { + const dateString = new Date(arg).toISOString(); + value = (0, dayjs_1.default)(dateString).locale(locale).utc().format(format); + } + } + return { value, error }; + }); + } + /** + * @param expression + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.Number); + } + } + formatTicks.FormatTicks = FormatTicks; + + return formatTicks; +} + +var getFutureTime = {}; + +var hasRequiredGetFutureTime; + +function requireGetFutureTime () { + if (hasRequiredGetFutureTime) return getFutureTime; + hasRequiredGetFutureTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getFutureTime && getFutureTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getFutureTime, "__esModule", { value: true }); + getFutureTime.GetFutureTime = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the current timestamp plus the specified time units. + */ + class GetFutureTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetFutureTime](xref:adaptive-expressions.GetFutureTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetFutureTime, GetFutureTime.evaluator, returnType_1.ReturnType.String, GetFutureTime.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (Number.isInteger(args[0]) && typeof args[1] === 'string') { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 4, format, locale)); + const { duration, tsStr } = functionUtils_internal_1.InternalFunctionUtils.timeUnitTransformer(args[0], args[1]); + if (tsStr === undefined) { + error = `${args[2]} is not a valid time unit.`; + } + else { + value = (0, dayjs_1.default)().locale(locale).utc().add(duration, tsStr).format(format); + } + } + else { + error = `${expression} should contain a time interval integer, a string unit of time and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.Number, returnType_1.ReturnType.String); + } + } + getFutureTime.GetFutureTime = GetFutureTime; + + return getFutureTime; +} + +var getNextViableDate = {}; + +var hasRequiredGetNextViableDate; + +function requireGetNextViableDate () { + if (hasRequiredGetNextViableDate) return getNextViableDate; + hasRequiredGetNextViableDate = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getNextViableDate && getNextViableDate.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getNextViableDate, "__esModule", { value: true }); + getNextViableDate.GetNextViableDate = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const returnType_1 = requireReturnType(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + /** + * Return the next viable date of a timex expression based on the current date and user's timezone. + */ + class GetNextViableDate extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetNextViableDate](xref:adaptive-expressions.GetNextViableDate) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetNextViableDate, GetNextViableDate.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + const currentTime = (0, dayjs_1.default)(new Date().toISOString()); + let validYear = 0; + let validMonth = 0; + let validDay = 0; + let convertedDateTime; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + if (parsed.year || !parsed.month || !parsed.dayOfMonth) { + error = `${args[0]} must be a timex string which only contains month and day-of-month, for example: 'XXXX-10-31'.`; + } + } + if (!error) { + if (args.length === 2 && typeof args[1] === 'string') { + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(args[1]); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${args[1]} is not a valid timezone`; + } + if (!error) { + convertedDateTime = currentTime.utc().tz(timeZone); + } + } + else { + convertedDateTime = currentTime.utc(); + } + } + if (!error) { + const year = convertedDateTime.year(); + const month = convertedDateTime.month() + 1; + const dayOfMonth = convertedDateTime.date(); + if (parsed.month > month || (parsed.month === month && parsed.dayOfMonth >= dayOfMonth)) { + validYear = year; + } + else { + validYear = year + 1; + } + validMonth = parsed.month; + validDay = parsed.dayOfMonth; + if (validMonth === 2 && validDay === 29) { + while (!GetNextViableDate.leapYear(validYear)) { + validYear += 1; + } + } + } + const value = recognizers_text_data_types_timex_expression_1.TimexProperty.fromDate(new Date(validYear, validMonth - 1, validDay)).timex; + return { value, error }; + } + /** + * @private + */ + static leapYear(year) { + return (year % 4 === 0 && year % 100 != 0) || year % 400 === 0; + } + } + getNextViableDate.GetNextViableDate = GetNextViableDate; + + return getNextViableDate; +} + +var getNextViableTime = {}; + +var hasRequiredGetNextViableTime; + +function requireGetNextViableTime () { + if (hasRequiredGetNextViableTime) return getNextViableTime; + hasRequiredGetNextViableTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getNextViableTime && getNextViableTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getNextViableTime, "__esModule", { value: true }); + getNextViableTime.GetNextViableTime = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const returnType_1 = requireReturnType(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + /** + * Return the next viable time of a timex expression based on the current time and user's timezone. + */ + class GetNextViableTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetNextViableTime](xref:adaptive-expressions.GetNextViableTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetNextViableTime, GetNextViableTime.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + const currentTime = (0, dayjs_1.default)(new Date().toISOString()); + let validHour = 0; + let validMinute = 0; + let validSecond = 0; + let convertedDateTime; + const formatRegex = /TXX:[0-5][0-9]:[0-5][0-9]/g; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (!formatRegex.test(args[0])) { + error = `${args[0]} must be a timex string which only contains minutes and seconds, for example: 'TXX:15:28'`; + } + } + if (!error) { + if (args.length === 2 && typeof args[1] === 'string') { + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(args[1]); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${args[1]} is not a valid timezone`; + } + if (!error) { + convertedDateTime = currentTime.utc().tz(timeZone); + } + } + else { + convertedDateTime = currentTime.utc(); + } + } + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0].replace('XX', '00'))); + } + if (!error) { + const hour = convertedDateTime.hour(); + const minute = convertedDateTime.minute(); + const second = convertedDateTime.second(); + if (parsed.minute > minute || (parsed.minute === minute && parsed.second >= second)) { + validHour = hour; + } + else { + validHour = hour + 1; + } + if (validHour >= 24) { + validHour -= 24; + } + validMinute = parsed.minute; + validSecond = parsed.second; + } + const value = recognizers_text_data_types_timex_expression_1.TimexProperty.fromTime(new recognizers_text_data_types_timex_expression_1.Time(validHour, validMinute, validSecond)).timex; + return { value, error }; + } + } + getNextViableTime.GetNextViableTime = GetNextViableTime; + + return getNextViableTime; +} + +var getPastTime = {}; + +var hasRequiredGetPastTime; + +function requireGetPastTime () { + if (hasRequiredGetPastTime) return getPastTime; + hasRequiredGetPastTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getPastTime && getPastTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getPastTime, "__esModule", { value: true }); + getPastTime.GetPastTime = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the current timestamp minus the specified time units. + */ + class GetPastTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetPastTime](xref:adaptive-expressions.GetPastTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetPastTime, GetPastTime.evaluator, returnType_1.ReturnType.String, GetPastTime.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (Number.isInteger(args[0]) && typeof args[1] === 'string') { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 4, format, locale)); + const { duration, tsStr } = functionUtils_internal_1.InternalFunctionUtils.timeUnitTransformer(args[0], args[1]); + if (tsStr === undefined) { + error = `${args[2]} is not a valid time unit.`; + } + else { + value = (0, dayjs_1.default)().locale(locale).utc().subtract(duration, tsStr).format(format); + } + } + else { + error = `${expression} should contain a time interval integer, a string unit of time and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.Number, returnType_1.ReturnType.String); + } + } + getPastTime.GetPastTime = GetPastTime; + + return getPastTime; +} + +var getPreviousViableDate = {}; + +var hasRequiredGetPreviousViableDate; + +function requireGetPreviousViableDate () { + if (hasRequiredGetPreviousViableDate) return getPreviousViableDate; + hasRequiredGetPreviousViableDate = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getPreviousViableDate && getPreviousViableDate.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getPreviousViableDate, "__esModule", { value: true }); + getPreviousViableDate.GetPreviousViableDate = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const returnType_1 = requireReturnType(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + /** + * Return the previous viable date of a timex expression based on the current date and user's timezone. + */ + class GetPreviousViableDate extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetPreviousViableDate](xref:adaptive-expressions.GetPreviousViableDate) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetPreviousViableDate, GetPreviousViableDate.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + const currentTime = (0, dayjs_1.default)(new Date().toISOString()); + let validYear = 0; + let validMonth = 0; + let validDay = 0; + let convertedDateTime; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + if (parsed.year || !parsed.month || !parsed.dayOfMonth) { + error = `${args[0]} must be a timex string which only contains month and day-of-month, for example: 'XXXX-10-31'.`; + } + } + if (!error) { + if (args.length === 2 && typeof args[1] === 'string') { + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(args[1]); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${args[1]} is not a valid timezone`; + } + if (!error) { + convertedDateTime = currentTime.utc().tz(timeZone); + } + } + else { + convertedDateTime = currentTime.utc(); + } + } + if (!error) { + const year = convertedDateTime.year(); + const month = convertedDateTime.month() + 1; + const dayOfMonth = convertedDateTime.date(); + if (parsed.month < month || (parsed.month === month && parsed.dayOfMonth < dayOfMonth)) { + validYear = year; + } + else { + validYear = year - 1; + } + validMonth = parsed.month; + validDay = parsed.dayOfMonth; + if (validMonth === 2 && validDay === 29) { + while (!GetPreviousViableDate.leapYear(validYear)) { + validYear -= 1; + } + } + } + const value = recognizers_text_data_types_timex_expression_1.TimexProperty.fromDate(new Date(validYear, validMonth - 1, validDay)).timex; + return { value, error }; + } + /** + * @private + */ + static leapYear(year) { + return (year % 4 === 0 && year % 100 != 0) || year % 400 === 0; + } + } + getPreviousViableDate.GetPreviousViableDate = GetPreviousViableDate; + + return getPreviousViableDate; +} + +var getPreviousViableTime = {}; + +var hasRequiredGetPreviousViableTime; + +function requireGetPreviousViableTime () { + if (hasRequiredGetPreviousViableTime) return getPreviousViableTime; + hasRequiredGetPreviousViableTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getPreviousViableTime && getPreviousViableTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getPreviousViableTime, "__esModule", { value: true }); + getPreviousViableTime.GetPreviousViableTime = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const returnType_1 = requireReturnType(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const timeZoneConverter_1 = requireTimeZoneConverter(); + const dayjs_1 = __importDefault(requireDayjs_min()); + const timezone_1 = __importDefault(requireTimezone()); + dayjs_1.default.extend(timezone_1.default); + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + /** + * Return the previous viable time of a timex expression based on the current time and user's timezone. + */ + class GetPreviousViableTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetPreviousViableTime](xref:adaptive-expressions.GetPreviousViableTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetPreviousViableTime, GetPreviousViableTime.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + const currentTime = (0, dayjs_1.default)(new Date().toISOString()); + let validHour = 0; + let validMinute = 0; + let validSecond = 0; + let convertedDateTime; + const formatRegex = /TXX:[0-5][0-9]:[0-5][0-9]/g; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (!formatRegex.test(args[0])) { + error = `${args[0]} must be a timex string which only contains minutes and seconds, for example: 'TXX:15:28'`; + } + } + if (!error) { + if (args.length === 2 && typeof args[1] === 'string') { + const timeZone = timeZoneConverter_1.TimeZoneConverter.windowsToIana(args[1]); + if (!timeZoneConverter_1.TimeZoneConverter.verifyTimeZoneStr(timeZone)) { + error = `${args[1]} is not a valid timezone`; + } + if (!error) { + convertedDateTime = currentTime.utc().tz(timeZone); + } + } + else { + convertedDateTime = currentTime.utc(); + } + } + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0].replace('XX', '00'))); + } + if (!error) { + const hour = convertedDateTime.hour(); + const minute = convertedDateTime.minute(); + const second = convertedDateTime.second(); + if (parsed.minute < minute || (parsed.minute === minute && parsed.second < second)) { + validHour = hour; + } + else { + validHour = hour - 1; + } + if (validHour < 0) { + validHour += 24; + } + validMinute = parsed.minute; + validSecond = parsed.second; + } + const value = recognizers_text_data_types_timex_expression_1.TimexProperty.fromTime(new recognizers_text_data_types_timex_expression_1.Time(validHour, validMinute, validSecond)).timex; + return { value, error }; + } + } + getPreviousViableTime.GetPreviousViableTime = GetPreviousViableTime; + + return getPreviousViableTime; +} + +var getProperty = {}; + +var hasRequiredGetProperty; + +function requireGetProperty () { + if (hasRequiredGetProperty) return getProperty; + hasRequiredGetProperty = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(getProperty, "__esModule", { value: true }); + getProperty.GetProperty = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const simpleObjectMemory_1 = requireSimpleObjectMemory(); + const returnType_1 = requireReturnType(); + /** + * Retrieve the value of the specified property from the JSON object. + */ + class GetProperty extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetProperty](xref:adaptive-expressions.GetProperty) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetProperty, GetProperty.evaluator, returnType_1.ReturnType.Object, GetProperty.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let property; + const children = expression.children; + const { value: firstItem, error: childrenError } = children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (children.length === 1) { + // get root value from memory + if (typeof firstItem === 'string') { + value = functionUtils_internal_1.InternalFunctionUtils.wrapGetValue(state, firstItem, options); + } + else { + error = `"Single parameter ${children[0]} is not a string."`; + } + } + else { + // get the peoperty value from the instance + ({ value: property, error } = children[1].tryEvaluate(state, options)); + if (!error) { + value = functionUtils_internal_1.InternalFunctionUtils.wrapGetValue(new simpleObjectMemory_1.SimpleObjectMemory(firstItem), property.toString(), options); + } + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String], returnType_1.ReturnType.Object); + } + } + getProperty.GetProperty = GetProperty; + + return getProperty; +} + +var getTimeOfDay = {}; + +var hasRequiredGetTimeOfDay; + +function requireGetTimeOfDay () { + if (hasRequiredGetTimeOfDay) return getTimeOfDay; + hasRequiredGetTimeOfDay = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (getTimeOfDay && getTimeOfDay.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(getTimeOfDay, "__esModule", { value: true }); + getTimeOfDay.GetTimeOfDay = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + const convertFromUTC_1 = requireConvertFromUTC(); + /** + * Returns time of day for a given timestamp. + */ + class GetTimeOfDay extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [GetTimeOfDay](xref:adaptive-expressions.GetTimeOfDay) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GetTimeOfDay, GetTimeOfDay.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let value; + let error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + let thisTime; + if (error) { + error = functionUtils_internal_1.InternalFunctionUtils.verifyTimestamp(args[0]); + if (error) { + return { value, error }; + } + else { + if ((0, dayjs_1.default)(args[0]).format(convertFromUTC_1.ConvertFromUTC.NoneUtcDefaultDateTimeFormat) === args[0]) { + thisTime = new Date(args[0]).getHours() * 100 + new Date(args[0]).getMinutes(); + error = undefined; + } + else { + return { value, error }; + } + } + } + else { + // utc iso format + thisTime = new Date(args[0]).getUTCHours() * 100 + new Date(args[0]).getUTCMinutes(); + } + if (thisTime === 0) { + value = 'midnight'; + } + else if (thisTime > 0 && thisTime < 1200) { + value = 'morning'; + } + else if (thisTime === 1200) { + value = 'noon'; + } + else if (thisTime > 1200 && thisTime < 1800) { + value = 'afternoon'; + } + else if (thisTime >= 1800 && thisTime <= 2200) { + value = 'evening'; + } + else if (thisTime > 2200 && thisTime <= 2359) { + value = 'night'; + } + return { value, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + getTimeOfDay.GetTimeOfDay = GetTimeOfDay; + + return getTimeOfDay; +} + +var greaterThan = {}; + +var hasRequiredGreaterThan; + +function requireGreaterThan () { + if (hasRequiredGreaterThan) return greaterThan; + hasRequiredGreaterThan = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(greaterThan, "__esModule", { value: true }); + greaterThan.GreaterThan = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether the first value is greater than the second value. + * Return true if the first value is more, or return false if less. + */ + class GreaterThan extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [GreaterThan](xref:adaptive-expressions.GreaterThan) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GreaterThan, GreaterThan.func, functionUtils_1.FunctionUtils.validateBinary, functionUtils_1.FunctionUtils.verifyNotNull); + } + /** + * @private + */ + static func(args) { + if ((functionUtils_1.FunctionUtils.isNumber(args[0]) && functionUtils_1.FunctionUtils.isNumber(args[1])) || + (typeof args[0] === 'string' && typeof args[1] === 'string') || + (args[0] instanceof Date && args[1] instanceof Date)) { + return args[0] > args[1]; + } + else { + throw new Error(`${args[0]} and ${args[1]} must be comparable.`); + } + } + } + greaterThan.GreaterThan = GreaterThan; + + return greaterThan; +} + +var greaterThanOrEqual = {}; + +var hasRequiredGreaterThanOrEqual; + +function requireGreaterThanOrEqual () { + if (hasRequiredGreaterThanOrEqual) return greaterThanOrEqual; + hasRequiredGreaterThanOrEqual = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(greaterThanOrEqual, "__esModule", { value: true }); + greaterThanOrEqual.GreaterThanOrEqual = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether the first value is greater than or equal to the second value. Return true when the first value is greater or equal, + * or return false if the first value is less. + */ + class GreaterThanOrEqual extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [GreaterThanOrEqual](xref:adaptive-expressions.GreaterThanOrEqual) class. + */ + constructor() { + super(expressionType_1.ExpressionType.GreaterThanOrEqual, GreaterThanOrEqual.func, functionUtils_1.FunctionUtils.validateBinary, functionUtils_1.FunctionUtils.verifyNotNull); + } + /** + * @private + */ + static func(args) { + if ((functionUtils_1.FunctionUtils.isNumber(args[0]) && functionUtils_1.FunctionUtils.isNumber(args[1])) || + (typeof args[0] === 'string' && typeof args[1] === 'string') || + (args[0] instanceof Date && args[1] instanceof Date)) { + return args[0] >= args[1]; + } + else { + throw new Error(`${args[0]} and ${args[1]} must be comparable.`); + } + } + } + greaterThanOrEqual.GreaterThanOrEqual = GreaterThanOrEqual; + + return greaterThanOrEqual; +} + +var _if = {}; + +var hasRequired_if; + +function require_if () { + if (hasRequired_if) return _if; + hasRequired_if = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(_if, "__esModule", { value: true }); + _if.If = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const options_1 = requireOptions(); + const returnType_1 = requireReturnType(); + /** + * Check whether an expression is true or false. Based on the result, return a specified value. + */ + class If extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [If](xref:adaptive-expressions.If) class. + */ + constructor() { + super(expressionType_1.ExpressionType.If, If.evaluator, returnType_1.ReturnType.Object, If.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + let error; + const newOptions = new options_1.Options(options); + newOptions.nullSubstitution = undefined; + ({ value: result, error } = expression.children[0].tryEvaluate(state, newOptions)); + if (!error && functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(result)) { + ({ value: result, error } = expression.children[1].tryEvaluate(state, options)); + } + else { + ({ value: result, error } = expression.children[2].tryEvaluate(state, options)); + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expr, 3, 3); + } + } + _if.If = If; + + return _if; +} + +var ignore = {}; + +var hasRequiredIgnore; + +function requireIgnore () { + if (hasRequiredIgnore) return ignore; + hasRequiredIgnore = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(ignore, "__esModule", { value: true }); + ignore.Ignore = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Mark a clause so that MostSpecificSelector will ignore it. + * MostSpecificSelector considers A & B to be more specific than A, but some clauses are unique and incomparable. + * + */ + class Ignore extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Ignore](xref:adaptive-expressions.Ignore) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Ignore, Ignore.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnaryBoolean); + this.negation = this; + } + /** + * @private + */ + static evaluator(expression, state, options) { + return expression.children[0].tryEvaluate(state, options); + } + } + ignore.Ignore = Ignore; + + return ignore; +} + +var indexOf = {}; + +var hasRequiredIndexOf; + +function requireIndexOf () { + if (hasRequiredIndexOf) return indexOf; + hasRequiredIndexOf = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(indexOf, "__esModule", { value: true }); + indexOf.IndexOf = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Returns the index of the first occurrence of a value in an array. + * The zero-based index position of value if that value is found, or -1 if it is not. + */ + class IndexOf extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IndexOf](xref:adaptive-expressions.IndexOf) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IndexOf, IndexOf.evaluator, returnType_1.ReturnType.Number, IndexOf.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value = -1; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (args[0] == null || typeof args[0] === 'string') { + if (args[1] === undefined || typeof args[1] === 'string') { + value = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).indexOf(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1])); + } + else { + error = `Can only look for indexof string in ${expression}`; + } + } + else if (Array.isArray(args[0])) { + value = args[0].indexOf(args[1]); + } + else { + error = `${expression} works only on string or list.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.String | returnType_1.ReturnType.Array, returnType_1.ReturnType.Object); + } + } + indexOf.IndexOf = IndexOf; + + return indexOf; +} + +var indicesAndValues = {}; + +var hasRequiredIndicesAndValues; + +function requireIndicesAndValues () { + if (hasRequiredIndicesAndValues) return indicesAndValues; + hasRequiredIndicesAndValues = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(indicesAndValues, "__esModule", { value: true }); + indicesAndValues.IndicesAndValues = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Turn an array or object into an array of objects with index and value properties. + * For arrays, the index is the position in the array. + * For objects, it is the key for the value. + */ + class IndicesAndValues extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IndicesAndValues](xref:adaptive-expressions.IndicesAndValues) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IndicesAndValues, IndicesAndValues.evaluator, returnType_1.ReturnType.Array, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = undefined; + let error = undefined; + let value = undefined; + ({ value, error } = expression.children[0].tryEvaluate(state, options)); + if (error === undefined) { + if (Array.isArray(value)) { + const tempList = []; + for (let i = 0; i < value.length; i++) { + tempList.push({ index: i, value: value[i] }); + } + result = tempList; + } + else if (typeof value === 'object') { + const tempList = []; + for (const [index, val] of Object.entries(value)) { + tempList.push({ index: index, value: val }); + } + result = tempList; + } + else { + error = `${expression.children[0]} is not array or object.`; + } + } + return { value: result, error }; + } + } + indicesAndValues.IndicesAndValues = IndicesAndValues; + + return indicesAndValues; +} + +var int = {}; + +var hasRequiredInt; + +function requireInt () { + if (hasRequiredInt) return int; + hasRequiredInt = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (int && int.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(int, "__esModule", { value: true }); + int.Int = void 0; + const big_integer_1 = __importDefault(requireBigInteger()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the integer version of a string. + */ + class Int extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Int](xref:adaptive-expressions.Int) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Int, Int.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error; + let value; + const firstChild = args[0]; + if (big_integer_1.default.isInstance(firstChild)) { + return { value: firstChild.toJSNumber(), error }; + } + if (typeof firstChild === 'string') { + value = parseInt(firstChild, 10); + if (!functionUtils_1.FunctionUtils.isNumber(value)) { + error = `parameter ${args[0]} is not a valid number string.`; + } + } + else if (functionUtils_1.FunctionUtils.isNumber(firstChild)) { + value = parseInt(firstChild.toString(), 10); + } + return { value, error }; + }); + } + } + int.Int = Int; + + return int; +} + +var intersection = {}; + +var hasRequiredIntersection; + +function requireIntersection () { + if (hasRequiredIntersection) return intersection; + hasRequiredIntersection = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(intersection, "__esModule", { value: true }); + intersection.Intersection = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return a collection that has only the common items across the specified collections. + * To appear in the result, an item must appear in all the collections passed to this function. + * If one or more items have the same name, + * the last item with that name appears in the result. + */ + class Intersection extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Intersection](xref:adaptive-expressions.Intersection) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Intersection, Intersection.evaluator(), returnType_1.ReturnType.Array, Intersection.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let result = args[0]; + for (const arg of args) { + result = result.filter((e) => arg.indexOf(e) > -1); + } + return Array.from(new Set(result)); + }, functionUtils_1.FunctionUtils.verifyList); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.Array); + } + } + intersection.Intersection = Intersection; + + return intersection; +} + +var isArray = {}; + +var hasRequiredIsArray; + +function requireIsArray () { + if (hasRequiredIsArray) return isArray; + hasRequiredIsArray = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isArray, "__esModule", { value: true }); + isArray.IsArray = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is an array. + */ + class IsArray extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsArray](xref:adaptive-expressions.IsArray) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsArray, IsArray.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => Array.isArray(args[0])); + } + } + isArray.IsArray = IsArray; + + return isArray; +} + +var isBoolean = {}; + +var hasRequiredIsBoolean; + +function requireIsBoolean () { + if (hasRequiredIsBoolean) return isBoolean; + hasRequiredIsBoolean = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isBoolean, "__esModule", { value: true }); + isBoolean.IsBoolean = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is a Boolean. + */ + class IsBoolean extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsBoolean](xref:adaptive-expressions.IsBoolean) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsBoolean, IsBoolean.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => typeof args[0] === 'boolean'); + } + } + isBoolean.IsBoolean = IsBoolean; + + return isBoolean; +} + +var isDate = {}; + +var hasRequiredIsDate; + +function requireIsDate () { + if (hasRequiredIsDate) return isDate; + hasRequiredIsDate = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isDate, "__esModule", { value: true }); + isDate.IsDate = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given `TimexProperty` or timex string refers to a valid date. + * Valid dates contain the month and dayOfMonth, or contain the dayOfWeek. + */ + class IsDate extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsDate](xref:adaptive-expressions.IsDate) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsDate, IsDate.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = (parsed.month !== undefined && parsed.dayOfMonth !== undefined) || parsed.dayOfWeek !== undefined; + } + return { value, error }; + } + } + isDate.IsDate = IsDate; + + return isDate; +} + +var isDateRange = {}; + +var hasRequiredIsDateRange; + +function requireIsDateRange () { + if (hasRequiredIsDateRange) return isDateRange; + hasRequiredIsDateRange = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isDateRange, "__esModule", { value: true }); + isDateRange.IsDateRange = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to a valid date range. + */ + class IsDateRange extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsDateRange](xref:adaptive-expressions.IsDateRange) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsDateRange, IsDateRange.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = + (parsed.year !== undefined && parsed.dayOfMonth === undefined) || + (parsed.year !== undefined && parsed.month !== undefined && parsed.dayOfMonth === undefined) || + (parsed.month !== undefined && parsed.dayOfMonth === undefined) || + parsed.season !== undefined || + parsed.weekOfYear !== undefined || + parsed.weekOfMonth !== undefined; + } + return { value, error }; + } + } + isDateRange.IsDateRange = IsDateRange; + + return isDateRange; +} + +var isDateTime = {}; + +var hasRequiredIsDateTime; + +function requireIsDateTime () { + if (hasRequiredIsDateTime) return isDateTime; + hasRequiredIsDateTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isDateTime, "__esModule", { value: true }); + isDateTime.IsDateTime = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is a UTC ISO format (YYYY-MM-DDTHH:mm:ss.fffZ) timestamp string. + */ + class IsDateTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsDateTime](xref:adaptive-expressions.IsDateTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsDateTime, IsDateTime.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => typeof args[0] === 'string' && functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]) === undefined); + } + } + isDateTime.IsDateTime = IsDateTime; + + return isDateTime; +} + +var isDefinite = {}; + +var hasRequiredIsDefinite; + +function requireIsDefinite () { + if (hasRequiredIsDefinite) return isDefinite; + hasRequiredIsDefinite = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isDefinite, "__esModule", { value: true }); + isDefinite.IsDefinite = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to a valid date. Valid dates contain the year, month and dayOfMonth. + */ + class IsDefinite extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsDefinite](xref:adaptive-expressions.IsDefinite) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsDefinite, IsDefinite.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (!error) { + value = + parsed != undefined && + parsed.year !== undefined && + parsed.month !== undefined && + parsed.dayOfMonth !== undefined; + } + return { value, error }; + } + } + isDefinite.IsDefinite = IsDefinite; + + return isDefinite; +} + +var isDuration = {}; + +var hasRequiredIsDuration; + +function requireIsDuration () { + if (hasRequiredIsDuration) return isDuration; + hasRequiredIsDuration = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isDuration, "__esModule", { value: true }); + isDuration.IsDuration = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to a valid duration. + */ + class IsDuration extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsDuration](xref:adaptive-expressions.IsDuration) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsDuration, IsDuration.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = + parsed.years !== undefined || + parsed.months !== undefined || + parsed.weeks !== undefined || + parsed.days !== undefined || + parsed.hours !== undefined || + parsed.minutes !== undefined || + parsed.seconds !== undefined; + } + return { value, error }; + } + } + isDuration.IsDuration = IsDuration; + + return isDuration; +} + +var isFloat = {}; + +var hasRequiredIsFloat; + +function requireIsFloat () { + if (hasRequiredIsFloat) return isFloat; + hasRequiredIsFloat = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isFloat, "__esModule", { value: true }); + isFloat.IsFloat = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is a floating-point number. + * Due to the alignment between C# and JavaScript, a number with an non-zero residue of its modulo 1 will be treated as a floating-point number. + */ + class IsFloat extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsFloat](xref:adaptive-expressions.IsFloat) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsFloat, IsFloat.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_1.FunctionUtils.isNumber(args[0]) && !Number.isInteger(args[0])); + } + } + isFloat.IsFloat = IsFloat; + + return isFloat; +} + +var isInteger = {}; + +var hasRequiredIsInteger; + +function requireIsInteger () { + if (hasRequiredIsInteger) return isInteger; + hasRequiredIsInteger = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isInteger, "__esModule", { value: true }); + isInteger.IsInteger = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is an integer number. Due to the alignment between C# and JavaScript, a number with a zero residue of its modulo 1 will be treated as an integer number. + */ + class IsInteger extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsInteger](xref:adaptive-expressions.IsInteger) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsInteger, IsInteger.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_1.FunctionUtils.isNumber(args[0]) && Number.isInteger(args[0])); + } + } + isInteger.IsInteger = IsInteger; + + return isInteger; +} + +var isMatch = {}; + +var commonRegex = {}; + +var iterator; +var hasRequiredIterator; + +function requireIterator () { + if (hasRequiredIterator) return iterator; + hasRequiredIterator = 1; + iterator = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value; + } + }; + }; + return iterator; +} + +var yallist; +var hasRequiredYallist; + +function requireYallist () { + if (hasRequiredYallist) return yallist; + hasRequiredYallist = 1; + yallist = Yallist; + + Yallist.Node = Node; + Yallist.create = Yallist; + + function Yallist (list) { + var self = this; + if (!(self instanceof Yallist)) { + self = new Yallist(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self + } + + Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + + return next + }; + + Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + if (head) { + head.prev = node; + } + + this.head = node; + if (!this.tail) { + this.tail = node; + } + this.length++; + }; + + Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + if (tail) { + tail.next = node; + } + + this.tail = node; + if (!this.head) { + this.head = node; + } + this.length++; + }; + + Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + return this.length + }; + + Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + return this.length + }; + + Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value; + this.tail = this.tail.prev; + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + this.length--; + return res + }; + + Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value; + this.head = this.head.next; + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + this.length--; + return res + }; + + Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + if (i === n && walker !== null) { + return walker.value + } + }; + + Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + return res + }; + + Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + return res + }; + + Yallist.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc + }; + + Yallist.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc + }; + + Yallist.prototype.toArray = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + return arr + }; + + Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + return arr + }; + + Yallist.prototype.slice = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + return ret + }; + + Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length; + if (to < 0) { + to += this.length; + } + from = from || 0; + if (from < 0) { + from += this.length; + } + var ret = new Yallist(); + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0; + } + if (to > this.length) { + to = this.length; + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + return ret + }; + + Yallist.prototype.splice = function (start, deleteCount /*, ...nodes */) { + if (start > this.length) { + start = this.length - 1; + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 2; i < arguments.length; i++) { + walker = insert(this, walker, arguments[i]); + } + return ret; + }; + + Yallist.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + this.head = tail; + this.tail = head; + return this + }; + + function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + + return inserted + } + + function push (self, item) { + self.tail = new Node(item, self.tail, null, self); + if (!self.head) { + self.head = self.tail; + } + self.length++; + } + + function unshift (self, item) { + self.head = new Node(item, null, self.head, self); + if (!self.tail) { + self.tail = self.head; + } + self.length++; + } + + function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + // add if support for Symbol.iterator is present + requireIterator()(Yallist); + } catch (er) {} + return yallist; +} + +var lruCache; +var hasRequiredLruCache; + +function requireLruCache () { + if (hasRequiredLruCache) return lruCache; + hasRequiredLruCache = 1; + + // A linked list to keep track of recently-used-ness + const Yallist = requireYallist(); + + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + // lruList is a yallist where the head is the youngest + // item, and the tail is the oldest. the list contains the Hit + // objects as the entries. + // Each Hit object has a reference to its Yallist.Node. This + // never changes. + // + // cache is a Map (or PseudoMap) that matches the keys to + // the Yallist.Node object. + class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options }; + + if (!options) + options = {}; + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + this[MAX] = options.max || Infinity; + + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity; + trim(this); + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA; + trim(this); + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + trim(this); + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach (fn, thisp) { + thisp = thisp || this; + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); // hash of items by key + this[LRU_LIST] = new Yallist(); // list of items in order of use recency + this[LENGTH] = 0; // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false + } + + const node = this[CACHE].get(key); + const item = node.value; + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true + } + + const hit = new Entry(key, value, len, now, maxAge); + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value); + + return false + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value; + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail; + if (!node) + return null + + del(this, node); + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)); + } + + load (arr) { + // reset the cache + this.reset(); + + const now = Date.now(); + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + else { + const maxAge = expiresAt - now; + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)); + } + } + + const get = (self, key, doUse) => { + const node = self[CACHE].get(key); + if (node) { + const hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + return hit.value + } + }; + + const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value); + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) + hit = undefined; + } + if (hit) + fn.call(thisp, hit.value, hit.key, self); + }; + + lruCache = LRUCache; + return lruCache; +} + +var generated = {}; + +var CommonRegexLexer = {}; + +var hasRequiredCommonRegexLexer; + +function requireCommonRegexLexer () { + if (hasRequiredCommonRegexLexer) return CommonRegexLexer; + hasRequiredCommonRegexLexer = 1; + // Generated from src/CommonRegex.g4 by ANTLR 4.7.3-SNAPSHOT + var __createBinding = (CommonRegexLexer && CommonRegexLexer.__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 = (CommonRegexLexer && CommonRegexLexer.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (CommonRegexLexer && CommonRegexLexer.__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(CommonRegexLexer, "__esModule", { value: true }); + CommonRegexLexer.CommonRegexLexer = void 0; + const ATNDeserializer_1 = requireATNDeserializer(); + const Lexer_1 = requireLexer(); + const LexerATNSimulator_1 = requireLexerATNSimulator(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const Utils = __importStar(requireUtils()); + let CommonRegexLexer$1 = class CommonRegexLexer extends Lexer_1.Lexer { + // tslint:enable:no-trailing-whitespace + constructor(input) { + super(input); + this._interp = new LexerATNSimulator_1.LexerATNSimulator(CommonRegexLexer._ATN, this); + } + // @Override + // @NotNull + get vocabulary() { + return CommonRegexLexer.VOCABULARY; + } + // @Override + get grammarFileName() { return "CommonRegex.g4"; } + // @Override + get ruleNames() { return CommonRegexLexer.ruleNames; } + // @Override + get serializedATN() { return CommonRegexLexer._serializedATN; } + // @Override + get channelNames() { return CommonRegexLexer.channelNames; } + // @Override + get modeNames() { return CommonRegexLexer.modeNames; } + static get _ATN() { + if (!CommonRegexLexer.__ATN) { + CommonRegexLexer.__ATN = new ATNDeserializer_1.ATNDeserializer().deserialize(Utils.toCharArray(CommonRegexLexer._serializedATN)); + } + return CommonRegexLexer.__ATN; + } + }; + CommonRegexLexer.CommonRegexLexer = CommonRegexLexer$1; + CommonRegexLexer$1.Quoted = 1; + CommonRegexLexer$1.BlockQuoted = 2; + CommonRegexLexer$1.BellChar = 3; + CommonRegexLexer$1.ControlChar = 4; + CommonRegexLexer$1.EscapeChar = 5; + CommonRegexLexer$1.FormFeed = 6; + CommonRegexLexer$1.NewLine = 7; + CommonRegexLexer$1.CarriageReturn = 8; + CommonRegexLexer$1.Tab = 9; + CommonRegexLexer$1.Backslash = 10; + CommonRegexLexer$1.HexChar = 11; + CommonRegexLexer$1.Dot = 12; + CommonRegexLexer$1.DecimalDigit = 13; + CommonRegexLexer$1.NotDecimalDigit = 14; + CommonRegexLexer$1.CharWithProperty = 15; + CommonRegexLexer$1.CharWithoutProperty = 16; + CommonRegexLexer$1.WhiteSpace = 17; + CommonRegexLexer$1.NotWhiteSpace = 18; + CommonRegexLexer$1.WordChar = 19; + CommonRegexLexer$1.NotWordChar = 20; + CommonRegexLexer$1.CharacterClassStart = 21; + CommonRegexLexer$1.CharacterClassEnd = 22; + CommonRegexLexer$1.Caret = 23; + CommonRegexLexer$1.Hyphen = 24; + CommonRegexLexer$1.QuestionMark = 25; + CommonRegexLexer$1.Plus = 26; + CommonRegexLexer$1.Star = 27; + CommonRegexLexer$1.OpenBrace = 28; + CommonRegexLexer$1.CloseBrace = 29; + CommonRegexLexer$1.Comma = 30; + CommonRegexLexer$1.EndOfSubject = 31; + CommonRegexLexer$1.Pipe = 32; + CommonRegexLexer$1.OpenParen = 33; + CommonRegexLexer$1.CloseParen = 34; + CommonRegexLexer$1.LessThan = 35; + CommonRegexLexer$1.GreaterThan = 36; + CommonRegexLexer$1.SingleQuote = 37; + CommonRegexLexer$1.Underscore = 38; + CommonRegexLexer$1.Colon = 39; + CommonRegexLexer$1.Hash = 40; + CommonRegexLexer$1.Equals = 41; + CommonRegexLexer$1.Exclamation = 42; + CommonRegexLexer$1.Ampersand = 43; + CommonRegexLexer$1.ALC = 44; + CommonRegexLexer$1.BLC = 45; + CommonRegexLexer$1.CLC = 46; + CommonRegexLexer$1.DLC = 47; + CommonRegexLexer$1.ELC = 48; + CommonRegexLexer$1.FLC = 49; + CommonRegexLexer$1.GLC = 50; + CommonRegexLexer$1.HLC = 51; + CommonRegexLexer$1.ILC = 52; + CommonRegexLexer$1.JLC = 53; + CommonRegexLexer$1.KLC = 54; + CommonRegexLexer$1.LLC = 55; + CommonRegexLexer$1.MLC = 56; + CommonRegexLexer$1.NLC = 57; + CommonRegexLexer$1.OLC = 58; + CommonRegexLexer$1.PLC = 59; + CommonRegexLexer$1.QLC = 60; + CommonRegexLexer$1.RLC = 61; + CommonRegexLexer$1.SLC = 62; + CommonRegexLexer$1.TLC = 63; + CommonRegexLexer$1.ULC = 64; + CommonRegexLexer$1.VLC = 65; + CommonRegexLexer$1.WLC = 66; + CommonRegexLexer$1.XLC = 67; + CommonRegexLexer$1.YLC = 68; + CommonRegexLexer$1.ZLC = 69; + CommonRegexLexer$1.AUC = 70; + CommonRegexLexer$1.BUC = 71; + CommonRegexLexer$1.CUC = 72; + CommonRegexLexer$1.DUC = 73; + CommonRegexLexer$1.EUC = 74; + CommonRegexLexer$1.FUC = 75; + CommonRegexLexer$1.GUC = 76; + CommonRegexLexer$1.HUC = 77; + CommonRegexLexer$1.IUC = 78; + CommonRegexLexer$1.JUC = 79; + CommonRegexLexer$1.KUC = 80; + CommonRegexLexer$1.LUC = 81; + CommonRegexLexer$1.MUC = 82; + CommonRegexLexer$1.NUC = 83; + CommonRegexLexer$1.OUC = 84; + CommonRegexLexer$1.PUC = 85; + CommonRegexLexer$1.QUC = 86; + CommonRegexLexer$1.RUC = 87; + CommonRegexLexer$1.SUC = 88; + CommonRegexLexer$1.TUC = 89; + CommonRegexLexer$1.UUC = 90; + CommonRegexLexer$1.VUC = 91; + CommonRegexLexer$1.WUC = 92; + CommonRegexLexer$1.XUC = 93; + CommonRegexLexer$1.YUC = 94; + CommonRegexLexer$1.ZUC = 95; + CommonRegexLexer$1.D1 = 96; + CommonRegexLexer$1.D2 = 97; + CommonRegexLexer$1.D3 = 98; + CommonRegexLexer$1.D4 = 99; + CommonRegexLexer$1.D5 = 100; + CommonRegexLexer$1.D6 = 101; + CommonRegexLexer$1.D7 = 102; + CommonRegexLexer$1.D8 = 103; + CommonRegexLexer$1.D9 = 104; + CommonRegexLexer$1.D0 = 105; + CommonRegexLexer$1.OtherChar = 106; + // tslint:disable:no-trailing-whitespace + CommonRegexLexer$1.channelNames = [ + "DEFAULT_TOKEN_CHANNEL", "HIDDEN", + ]; + // tslint:disable:no-trailing-whitespace + CommonRegexLexer$1.modeNames = [ + "DEFAULT_MODE", + ]; + CommonRegexLexer$1.ruleNames = [ + "Quoted", "BlockQuoted", "BellChar", "ControlChar", "EscapeChar", "FormFeed", + "NewLine", "CarriageReturn", "Tab", "Backslash", "HexChar", "Dot", "DecimalDigit", + "NotDecimalDigit", "CharWithProperty", "CharWithoutProperty", "WhiteSpace", + "NotWhiteSpace", "WordChar", "NotWordChar", "CharacterClassStart", "CharacterClassEnd", + "Caret", "Hyphen", "QuestionMark", "Plus", "Star", "OpenBrace", "CloseBrace", + "Comma", "EndOfSubject", "Pipe", "OpenParen", "CloseParen", "LessThan", + "GreaterThan", "SingleQuote", "Underscore", "Colon", "Hash", "Equals", + "Exclamation", "Ampersand", "ALC", "BLC", "CLC", "DLC", "ELC", "FLC", + "GLC", "HLC", "ILC", "JLC", "KLC", "LLC", "MLC", "NLC", "OLC", "PLC", + "QLC", "RLC", "SLC", "TLC", "ULC", "VLC", "WLC", "XLC", "YLC", "ZLC", + "AUC", "BUC", "CUC", "DUC", "EUC", "FUC", "GUC", "HUC", "IUC", "JUC", + "KUC", "LUC", "MUC", "NUC", "OUC", "PUC", "QUC", "RUC", "SUC", "TUC", + "UUC", "VUC", "WUC", "XUC", "YUC", "ZUC", "D1", "D2", "D3", "D4", "D5", + "D6", "D7", "D8", "D9", "D0", "OtherChar", "UnderscoreAlphaNumerics", + "AlphaNumerics", "AlphaNumeric", "NonAlphaNumeric", "HexDigit", "ASCII", + ]; + CommonRegexLexer$1._LITERAL_NAMES = [ + undefined, undefined, undefined, "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", + "'\\'", "'\\'", "'\\'", undefined, "'.'", "'\\'", "'\\'", undefined, undefined, + "'\\'", "'\\'", "'\\'", "'\\'", "'['", "']'", "'^'", "'-'", "'?'", "'+'", + "'*'", "'{'", "'}'", "','", "'$'", "'|'", "'('", "')'", "'<'", "'>'", + "'''", "'_'", "':'", "'#'", "'='", "'!'", "'&'", "'a'", "'b'", "'c'", + "'d'", "'e'", "'f'", "'g'", "'h'", "'i'", "'j'", "'k'", "'l'", "'m'", + "'n'", "'o'", "'p'", "'q'", "'r'", "'s'", "'t'", "'u'", "'v'", "'w'", + "'x'", "'y'", "'z'", "'A'", "'B'", "'C'", "'D'", "'E'", "'F'", "'G'", + "'H'", "'I'", "'J'", "'K'", "'L'", "'M'", "'N'", "'O'", "'P'", "'Q'", + "'R'", "'S'", "'T'", "'U'", "'V'", "'W'", "'X'", "'Y'", "'Z'", "'1'", + "'2'", "'3'", "'4'", "'5'", "'6'", "'7'", "'8'", "'9'", "'0'", + ]; + CommonRegexLexer$1._SYMBOLIC_NAMES = [ + undefined, "Quoted", "BlockQuoted", "BellChar", "ControlChar", "EscapeChar", + "FormFeed", "NewLine", "CarriageReturn", "Tab", "Backslash", "HexChar", + "Dot", "DecimalDigit", "NotDecimalDigit", "CharWithProperty", "CharWithoutProperty", + "WhiteSpace", "NotWhiteSpace", "WordChar", "NotWordChar", "CharacterClassStart", + "CharacterClassEnd", "Caret", "Hyphen", "QuestionMark", "Plus", "Star", + "OpenBrace", "CloseBrace", "Comma", "EndOfSubject", "Pipe", "OpenParen", + "CloseParen", "LessThan", "GreaterThan", "SingleQuote", "Underscore", + "Colon", "Hash", "Equals", "Exclamation", "Ampersand", "ALC", "BLC", "CLC", + "DLC", "ELC", "FLC", "GLC", "HLC", "ILC", "JLC", "KLC", "LLC", "MLC", + "NLC", "OLC", "PLC", "QLC", "RLC", "SLC", "TLC", "ULC", "VLC", "WLC", + "XLC", "YLC", "ZLC", "AUC", "BUC", "CUC", "DUC", "EUC", "FUC", "GUC", + "HUC", "IUC", "JUC", "KUC", "LUC", "MUC", "NUC", "OUC", "PUC", "QUC", + "RUC", "SUC", "TUC", "UUC", "VUC", "WUC", "XUC", "YUC", "ZUC", "D1", "D2", + "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D0", "OtherChar", + ]; + CommonRegexLexer$1.VOCABULARY = new VocabularyImpl_1.VocabularyImpl(CommonRegexLexer$1._LITERAL_NAMES, CommonRegexLexer$1._SYMBOLIC_NAMES, []); + CommonRegexLexer$1._serializedATN = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02l\u01FC\b\x01" + + "\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06" + + "\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r" + + "\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t" + + "\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t" + + "\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t" + + "\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04 \t \x04!\t!\x04\"\t" + + "\"\x04#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(\t(\x04)\t)\x04*\t*\x04" + + "+\t+\x04,\t,\x04-\t-\x04.\t.\x04/\t/\x040\t0\x041\t1\x042\t2\x043\t3\x04" + + "4\t4\x045\t5\x046\t6\x047\t7\x048\t8\x049\t9\x04:\t:\x04;\t;\x04<\t<\x04" + + "=\t=\x04>\t>\x04?\t?\x04@\t@\x04A\tA\x04B\tB\x04C\tC\x04D\tD\x04E\tE\x04" + + "F\tF\x04G\tG\x04H\tH\x04I\tI\x04J\tJ\x04K\tK\x04L\tL\x04M\tM\x04N\tN\x04" + + "O\tO\x04P\tP\x04Q\tQ\x04R\tR\x04S\tS\x04T\tT\x04U\tU\x04V\tV\x04W\tW\x04" + + "X\tX\x04Y\tY\x04Z\tZ\x04[\t[\x04\\\t\\\x04]\t]\x04^\t^\x04_\t_\x04`\t" + + "`\x04a\ta\x04b\tb\x04c\tc\x04d\td\x04e\te\x04f\tf\x04g\tg\x04h\th\x04" + + "i\ti\x04j\tj\x04k\tk\x04l\tl\x04m\tm\x04n\tn\x04o\to\x04p\tp\x04q\tq\x03" + + "\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x07\x03\xEB\n\x03" + + "\f\x03\x0E\x03\xEE\v\x03\x03\x03\x03\x03\x03\x03\x03\x04\x03\x04\x03\x04" + + "\x03\x05\x03\x05\x03\x05\x03\x06\x03\x06\x03\x06\x03\x07\x03\x07\x03\x07" + + "\x03\b\x03\b\x03\b\x03\t\x03\t\x03\t\x03\n\x03\n\x03\n\x03\v\x03\v\x03" + + "\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x03\f\x06\f\u0114\n" + + "\f\r\f\x0E\f\u0115\x03\f\x03\f\x05\f\u011A\n\f\x03\r\x03\r\x03\x0E\x03" + + "\x0E\x03\x0E\x03\x0F\x03\x0F\x03\x0F\x03\x10\x03\x10\x03\x10\x03\x10\x03" + + "\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03" + + "\x11\x03\x12\x03\x12\x03\x12\x03\x13\x03\x13\x03\x13\x03\x14\x03\x14\x03" + + "\x14\x03\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03\x17\x03\x17\x03\x18\x03" + + "\x18\x03\x19\x03\x19\x03\x1A\x03\x1A\x03\x1B\x03\x1B\x03\x1C\x03\x1C\x03" + + "\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1F\x03\x1F\x03 \x03 \x03!\x03!\x03\"" + + "\x03\"\x03#\x03#\x03$\x03$\x03%\x03%\x03&\x03&\x03\'\x03\'\x03(\x03(\x03" + + ")\x03)\x03*\x03*\x03+\x03+\x03,\x03,\x03-\x03-\x03.\x03.\x03/\x03/\x03" + + "0\x030\x031\x031\x032\x032\x033\x033\x034\x034\x035\x035\x036\x036\x03" + + "7\x037\x038\x038\x039\x039\x03:\x03:\x03;\x03;\x03<\x03<\x03=\x03=\x03" + + ">\x03>\x03?\x03?\x03@\x03@\x03A\x03A\x03B\x03B\x03C\x03C\x03D\x03D\x03" + + "E\x03E\x03F\x03F\x03G\x03G\x03H\x03H\x03I\x03I\x03J\x03J\x03K\x03K\x03" + + "L\x03L\x03M\x03M\x03N\x03N\x03O\x03O\x03P\x03P\x03Q\x03Q\x03R\x03R\x03" + + "S\x03S\x03T\x03T\x03U\x03U\x03V\x03V\x03W\x03W\x03X\x03X\x03Y\x03Y\x03" + + "Z\x03Z\x03[\x03[\x03\\\x03\\\x03]\x03]\x03^\x03^\x03_\x03_\x03`\x03`\x03" + + "a\x03a\x03b\x03b\x03c\x03c\x03d\x03d\x03e\x03e\x03f\x03f\x03g\x03g\x03" + + "h\x03h\x03i\x03i\x03j\x03j\x03k\x03k\x03l\x03l\x06l\u01EC\nl\rl\x0El\u01ED" + + "\x03m\x06m\u01F1\nm\rm\x0Em\u01F2\x03n\x03n\x03o\x03o\x03p\x03p\x03q\x03" + + "q\x03\xEC\x02\x02r\x03\x02\x03\x05\x02\x04\x07\x02\x05\t\x02\x06\v\x02" + + "\x07\r\x02\b\x0F\x02\t\x11\x02\n\x13\x02\v\x15\x02\f\x17\x02\r\x19\x02" + + "\x0E\x1B\x02\x0F\x1D\x02\x10\x1F\x02\x11!\x02\x12#\x02\x13%\x02\x14\'" + + "\x02\x15)\x02\x16+\x02\x17-\x02\x18/\x02\x191\x02\x1A3\x02\x1B5\x02\x1C" + + "7\x02\x1D9\x02\x1E;\x02\x1F=\x02 ?\x02!A\x02\"C\x02#E\x02$G\x02%I\x02" + + "&K\x02\'M\x02(O\x02)Q\x02*S\x02+U\x02,W\x02-Y\x02.[\x02/]\x020_\x021a" + + "\x022c\x023e\x024g\x025i\x026k\x027m\x028o\x029q\x02:s\x02;u\x02{\x02?}\x02@\x7F\x02A\x81\x02B\x83\x02C\x85\x02D\x87\x02E\x89\x02" + + "F\x8B\x02G\x8D\x02H\x8F\x02I\x91\x02J\x93\x02K\x95\x02L\x97\x02M\x99\x02" + + "N\x9B\x02O\x9D\x02P\x9F\x02Q\xA1\x02R\xA3\x02S\xA5\x02T\xA7\x02U\xA9\x02" + + "V\xAB\x02W\xAD\x02X\xAF\x02Y\xB1\x02Z\xB3\x02[\xB5\x02\\\xB7\x02]\xB9" + + "\x02^\xBB\x02_\xBD\x02`\xBF\x02a\xC1\x02b\xC3\x02c\xC5\x02d\xC7\x02e\xC9" + + "\x02f\xCB\x02g\xCD\x02h\xCF\x02i\xD1\x02j\xD3\x02k\xD5\x02l\xD7\x02\x02" + + "\xD9\x02\x02\xDB\x02\x02\xDD\x02\x02\xDF\x02\x02\xE1\x02\x02\x03\x02\x05" + + "\x05\x022;C\\c|\x05\x022;CHch\x03\x02\x02\x81\x02\u01FB\x02\x03\x03\x02" + + "\x02\x02\x02\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02\x02\x02\t\x03\x02" + + "\x02\x02\x02\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02\x02\x0F\x03\x02\x02" + + "\x02\x02\x11\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02\x02\x15\x03\x02\x02" + + "\x02\x02\x17\x03\x02\x02\x02\x02\x19\x03\x02\x02\x02\x02\x1B\x03\x02\x02" + + "\x02\x02\x1D\x03\x02\x02\x02\x02\x1F\x03\x02\x02\x02\x02!\x03\x02\x02" + + "\x02\x02#\x03\x02\x02\x02\x02%\x03\x02\x02\x02\x02\'\x03\x02\x02\x02\x02" + + ")\x03\x02\x02\x02\x02+\x03\x02\x02\x02\x02-\x03\x02\x02\x02\x02/\x03\x02" + + "\x02\x02\x021\x03\x02\x02\x02\x023\x03\x02\x02\x02\x025\x03\x02\x02\x02" + + "\x027\x03\x02\x02\x02\x029\x03\x02\x02\x02\x02;\x03\x02\x02\x02\x02=\x03" + + "\x02\x02\x02\x02?\x03\x02\x02\x02\x02A\x03\x02\x02\x02\x02C\x03\x02\x02" + + "\x02\x02E\x03\x02\x02\x02\x02G\x03\x02\x02\x02\x02I\x03\x02\x02\x02\x02" + + "K\x03\x02\x02\x02\x02M\x03\x02\x02\x02\x02O\x03\x02\x02\x02\x02Q\x03\x02" + + "\x02\x02\x02S\x03\x02\x02\x02\x02U\x03\x02\x02\x02\x02W\x03\x02\x02\x02" + + "\x02Y\x03\x02\x02\x02\x02[\x03\x02\x02\x02\x02]\x03\x02\x02\x02\x02_\x03" + + "\x02\x02\x02\x02a\x03\x02\x02\x02\x02c\x03\x02\x02\x02\x02e\x03\x02\x02" + + "\x02\x02g\x03\x02\x02\x02\x02i\x03\x02\x02\x02\x02k\x03\x02\x02\x02\x02" + + "m\x03\x02\x02\x02\x02o\x03\x02\x02\x02\x02q\x03\x02\x02\x02\x02s\x03\x02" + + "\x02\x02\x02u\x03\x02\x02\x02\x02w\x03\x02\x02\x02\x02y\x03\x02\x02\x02" + + "\x02{\x03\x02\x02\x02\x02}\x03\x02\x02\x02\x02\x7F\x03\x02\x02\x02\x02" + + "\x81\x03\x02\x02\x02\x02\x83\x03\x02\x02\x02\x02\x85\x03\x02\x02\x02\x02" + + "\x87\x03\x02\x02\x02\x02\x89\x03\x02\x02\x02\x02\x8B\x03\x02\x02\x02\x02" + + "\x8D\x03\x02\x02\x02\x02\x8F\x03\x02\x02\x02\x02\x91\x03\x02\x02\x02\x02" + + "\x93\x03\x02\x02\x02\x02\x95\x03\x02\x02\x02\x02\x97\x03\x02\x02\x02\x02" + + "\x99\x03\x02\x02\x02\x02\x9B\x03\x02\x02\x02\x02\x9D\x03\x02\x02\x02\x02" + + "\x9F\x03\x02\x02\x02\x02\xA1\x03\x02\x02\x02\x02\xA3\x03\x02\x02\x02\x02" + + "\xA5\x03\x02\x02\x02\x02\xA7\x03\x02\x02\x02\x02\xA9\x03\x02\x02\x02\x02" + + "\xAB\x03\x02\x02\x02\x02\xAD\x03\x02\x02\x02\x02\xAF\x03\x02\x02\x02\x02" + + "\xB1\x03\x02\x02\x02\x02\xB3\x03\x02\x02\x02\x02\xB5\x03\x02\x02\x02\x02" + + "\xB7\x03\x02\x02\x02\x02\xB9\x03\x02\x02\x02\x02\xBB\x03\x02\x02\x02\x02" + + "\xBD\x03\x02\x02\x02\x02\xBF\x03\x02\x02\x02\x02\xC1\x03\x02\x02\x02\x02" + + "\xC3\x03\x02\x02\x02\x02\xC5\x03\x02\x02\x02\x02\xC7\x03\x02\x02\x02\x02" + + "\xC9\x03\x02\x02\x02\x02\xCB\x03\x02\x02\x02\x02\xCD\x03\x02\x02\x02\x02" + + "\xCF\x03\x02\x02\x02\x02\xD1\x03\x02\x02\x02\x02\xD3\x03\x02\x02\x02\x02" + + "\xD5\x03\x02\x02\x02\x03\xE3\x03\x02\x02\x02\x05\xE6\x03\x02\x02\x02\x07" + + "\xF2\x03\x02\x02\x02\t\xF5\x03\x02\x02\x02\v\xF8\x03\x02\x02\x02\r\xFB" + + "\x03\x02\x02\x02\x0F\xFE\x03\x02\x02\x02\x11\u0101\x03\x02\x02\x02\x13" + + "\u0104\x03\x02\x02\x02\x15\u0107\x03\x02\x02\x02\x17\u0109\x03\x02\x02" + + "\x02\x19\u011B\x03\x02\x02\x02\x1B\u011D\x03\x02\x02\x02\x1D\u0120\x03" + + "\x02\x02\x02\x1F\u0123\x03\x02\x02\x02!\u012A\x03\x02\x02\x02#\u0131\x03" + + "\x02\x02\x02%\u0134\x03\x02\x02\x02\'\u0137\x03\x02\x02\x02)\u013A\x03" + + "\x02\x02\x02+\u013D\x03\x02\x02\x02-\u013F\x03\x02\x02\x02/\u0141\x03" + + "\x02\x02\x021\u0143\x03\x02\x02\x023\u0145\x03\x02\x02\x025\u0147\x03" + + "\x02\x02\x027\u0149\x03\x02\x02\x029\u014B\x03\x02\x02\x02;\u014D\x03" + + "\x02\x02\x02=\u014F\x03\x02\x02\x02?\u0151\x03\x02\x02\x02A\u0153\x03" + + "\x02\x02\x02C\u0155\x03\x02\x02\x02E\u0157\x03\x02\x02\x02G\u0159\x03" + + "\x02\x02\x02I\u015B\x03\x02\x02\x02K\u015D\x03\x02\x02\x02M\u015F\x03" + + "\x02\x02\x02O\u0161\x03\x02\x02\x02Q\u0163\x03\x02\x02\x02S\u0165\x03" + + "\x02\x02\x02U\u0167\x03\x02\x02\x02W\u0169\x03\x02\x02\x02Y\u016B\x03" + + "\x02\x02\x02[\u016D\x03\x02\x02\x02]\u016F\x03\x02\x02\x02_\u0171\x03" + + "\x02\x02\x02a\u0173\x03\x02\x02\x02c\u0175\x03\x02\x02\x02e\u0177\x03" + + "\x02\x02\x02g\u0179\x03\x02\x02\x02i\u017B\x03\x02\x02\x02k\u017D\x03" + + "\x02\x02\x02m\u017F\x03\x02\x02\x02o\u0181\x03\x02\x02\x02q\u0183\x03" + + "\x02\x02\x02s\u0185\x03\x02\x02\x02u\u0187\x03\x02\x02\x02w\u0189\x03" + + "\x02\x02\x02y\u018B\x03\x02\x02\x02{\u018D\x03\x02\x02\x02}\u018F\x03" + + "\x02\x02\x02\x7F\u0191\x03\x02\x02\x02\x81\u0193\x03\x02\x02\x02\x83\u0195" + + "\x03\x02\x02\x02\x85\u0197\x03\x02\x02\x02\x87\u0199\x03\x02\x02\x02\x89" + + "\u019B\x03\x02\x02\x02\x8B\u019D\x03\x02\x02\x02\x8D\u019F\x03\x02\x02" + + "\x02\x8F\u01A1\x03\x02\x02\x02\x91\u01A3\x03\x02\x02\x02\x93\u01A5\x03" + + "\x02\x02\x02\x95\u01A7\x03\x02\x02\x02\x97\u01A9\x03\x02\x02\x02\x99\u01AB" + + "\x03\x02\x02\x02\x9B\u01AD\x03\x02\x02\x02\x9D\u01AF\x03\x02\x02\x02\x9F" + + "\u01B1\x03\x02\x02\x02\xA1\u01B3\x03\x02\x02\x02\xA3\u01B5\x03\x02\x02" + + "\x02\xA5\u01B7\x03\x02\x02\x02\xA7\u01B9\x03\x02\x02\x02\xA9\u01BB\x03" + + "\x02\x02\x02\xAB\u01BD\x03\x02\x02\x02\xAD\u01BF\x03\x02\x02\x02\xAF\u01C1" + + "\x03\x02\x02\x02\xB1\u01C3\x03\x02\x02\x02\xB3\u01C5\x03\x02\x02\x02\xB5" + + "\u01C7\x03\x02\x02\x02\xB7\u01C9\x03\x02\x02\x02\xB9\u01CB\x03\x02\x02" + + "\x02\xBB\u01CD\x03\x02\x02\x02\xBD\u01CF\x03\x02\x02\x02\xBF\u01D1\x03" + + "\x02\x02\x02\xC1\u01D3\x03\x02\x02\x02\xC3\u01D5\x03\x02\x02\x02\xC5\u01D7" + + "\x03\x02\x02\x02\xC7\u01D9\x03\x02\x02\x02\xC9\u01DB\x03\x02\x02\x02\xCB" + + "\u01DD\x03\x02\x02\x02\xCD\u01DF\x03\x02\x02\x02\xCF\u01E1\x03\x02\x02" + + "\x02\xD1\u01E3\x03\x02\x02\x02\xD3\u01E5\x03\x02\x02\x02\xD5\u01E7\x03" + + "\x02\x02\x02\xD7\u01EB\x03\x02\x02\x02\xD9\u01F0\x03\x02\x02\x02\xDB\u01F4" + + "\x03\x02\x02\x02\xDD\u01F6\x03\x02\x02\x02\xDF\u01F8\x03\x02\x02\x02\xE1" + + "\u01FA\x03\x02\x02\x02\xE3\xE4\x07^\x02\x02\xE4\xE5\x05\xDDo\x02\xE5\x04" + + "\x03\x02\x02\x02\xE6\xE7\x07^\x02\x02\xE7\xE8\x07S\x02\x02\xE8\xEC\x03" + + "\x02\x02\x02\xE9\xEB\v\x02\x02\x02\xEA\xE9\x03\x02\x02\x02\xEB\xEE\x03" + + "\x02\x02\x02\xEC\xED\x03\x02\x02\x02\xEC\xEA\x03\x02\x02\x02\xED\xEF\x03" + + "\x02\x02\x02\xEE\xEC\x03\x02\x02\x02\xEF\xF0\x07^\x02\x02\xF0\xF1\x07" + + "G\x02\x02\xF1\x06\x03\x02\x02\x02\xF2\xF3\x07^\x02\x02\xF3\xF4\x07c\x02" + + "\x02\xF4\b\x03\x02\x02\x02\xF5\xF6\x07^\x02\x02\xF6\xF7\x07e\x02\x02\xF7" + + "\n\x03\x02\x02\x02\xF8\xF9\x07^\x02\x02\xF9\xFA\x07g\x02\x02\xFA\f\x03" + + "\x02\x02\x02\xFB\xFC\x07^\x02\x02\xFC\xFD\x07h\x02\x02\xFD\x0E\x03\x02" + + "\x02\x02\xFE\xFF\x07^\x02\x02\xFF\u0100\x07p\x02\x02\u0100\x10\x03\x02" + + "\x02\x02\u0101\u0102\x07^\x02\x02\u0102\u0103\x07t\x02\x02\u0103\x12\x03" + + "\x02\x02\x02\u0104\u0105\x07^\x02\x02\u0105\u0106\x07v\x02\x02\u0106\x14" + + "\x03\x02\x02\x02\u0107\u0108\x07^\x02\x02\u0108\x16\x03\x02\x02\x02\u0109" + + "\u010A\x07^\x02\x02\u010A\u010B\x07z\x02\x02\u010B\u0119\x03\x02\x02\x02" + + "\u010C\u010D\x05\xDFp\x02\u010D\u010E\x05\xDFp\x02\u010E\u011A\x03\x02" + + "\x02\x02\u010F\u0110\x07}\x02\x02\u0110\u0111\x05\xDFp\x02\u0111\u0113" + + "\x05\xDFp\x02\u0112\u0114\x05\xDFp\x02\u0113\u0112\x03\x02\x02\x02\u0114" + + "\u0115\x03\x02\x02\x02\u0115\u0113\x03\x02\x02\x02\u0115\u0116\x03\x02" + + "\x02\x02\u0116\u0117\x03\x02\x02\x02\u0117\u0118\x07\x7F\x02\x02\u0118" + + "\u011A\x03\x02\x02\x02\u0119\u010C\x03\x02\x02\x02\u0119\u010F\x03\x02" + + "\x02\x02\u011A\x18\x03\x02\x02\x02\u011B\u011C\x070\x02\x02\u011C\x1A" + + "\x03\x02\x02\x02\u011D\u011E\x07^\x02\x02\u011E\u011F\x07f\x02\x02\u011F" + + "\x1C\x03\x02\x02\x02\u0120\u0121\x07^\x02\x02\u0121\u0122\x07F\x02\x02" + + "\u0122\x1E\x03\x02\x02\x02\u0123\u0124\x07^\x02\x02\u0124\u0125\x07r\x02" + + "\x02\u0125\u0126\x07}\x02\x02\u0126\u0127\x03\x02\x02\x02\u0127\u0128" + + "\x05\xD7l\x02\u0128\u0129\x07\x7F\x02\x02\u0129 \x03\x02\x02\x02\u012A" + + "\u012B\x07^\x02\x02\u012B\u012C\x07R\x02\x02\u012C\u012D\x07}\x02\x02" + + "\u012D\u012E\x03\x02\x02\x02\u012E\u012F\x05\xD7l\x02\u012F\u0130\x07" + + "\x7F\x02\x02\u0130\"\x03\x02\x02\x02\u0131\u0132\x07^\x02\x02\u0132\u0133" + + "\x07u\x02\x02\u0133$\x03\x02\x02\x02\u0134\u0135\x07^\x02\x02\u0135\u0136" + + "\x07U\x02\x02\u0136&\x03\x02\x02\x02\u0137\u0138\x07^\x02\x02\u0138\u0139" + + "\x07y\x02\x02\u0139(\x03\x02\x02\x02\u013A\u013B\x07^\x02\x02\u013B\u013C" + + "\x07Y\x02\x02\u013C*\x03\x02\x02\x02\u013D\u013E\x07]\x02\x02\u013E,\x03" + + "\x02\x02\x02\u013F\u0140\x07_\x02\x02\u0140.\x03\x02\x02\x02\u0141\u0142" + + "\x07`\x02\x02\u01420\x03\x02\x02\x02\u0143\u0144\x07/\x02\x02\u01442\x03" + + "\x02\x02\x02\u0145\u0146\x07A\x02\x02\u01464\x03\x02\x02\x02\u0147\u0148" + + "\x07-\x02\x02\u01486\x03\x02\x02\x02\u0149\u014A\x07,\x02\x02\u014A8\x03" + + "\x02\x02\x02\u014B\u014C\x07}\x02\x02\u014C:\x03\x02\x02\x02\u014D\u014E" + + "\x07\x7F\x02\x02\u014E<\x03\x02\x02\x02\u014F\u0150\x07.\x02\x02\u0150" + + ">\x03\x02\x02\x02\u0151\u0152\x07&\x02\x02\u0152@\x03\x02\x02\x02\u0153" + + "\u0154\x07~\x02\x02\u0154B\x03\x02\x02\x02\u0155\u0156\x07*\x02\x02\u0156" + + "D\x03\x02\x02\x02\u0157\u0158\x07+\x02\x02\u0158F\x03\x02\x02\x02\u0159" + + "\u015A\x07>\x02\x02\u015AH\x03\x02\x02\x02\u015B\u015C\x07@\x02\x02\u015C" + + "J\x03\x02\x02\x02\u015D\u015E\x07)\x02\x02\u015EL\x03\x02\x02\x02\u015F" + + "\u0160\x07a\x02\x02\u0160N\x03\x02\x02\x02\u0161\u0162\x07<\x02\x02\u0162" + + "P\x03\x02\x02\x02\u0163\u0164\x07%\x02\x02\u0164R\x03\x02\x02\x02\u0165" + + "\u0166\x07?\x02\x02\u0166T\x03\x02\x02\x02\u0167\u0168\x07#\x02\x02\u0168" + + "V\x03\x02\x02\x02\u0169\u016A\x07(\x02\x02\u016AX\x03\x02\x02\x02\u016B" + + "\u016C\x07c\x02\x02\u016CZ\x03\x02\x02\x02\u016D\u016E\x07d\x02\x02\u016E" + + "\\\x03\x02\x02\x02\u016F\u0170\x07e\x02\x02\u0170^\x03\x02\x02\x02\u0171" + + "\u0172\x07f\x02\x02\u0172`\x03\x02\x02\x02\u0173\u0174\x07g\x02\x02\u0174" + + "b\x03\x02\x02\x02\u0175\u0176\x07h\x02\x02\u0176d\x03\x02\x02\x02\u0177" + + "\u0178\x07i\x02\x02\u0178f\x03\x02\x02\x02\u0179\u017A\x07j\x02\x02\u017A" + + "h\x03\x02\x02\x02\u017B\u017C\x07k\x02\x02\u017Cj\x03\x02\x02\x02\u017D" + + "\u017E\x07l\x02\x02\u017El\x03\x02\x02\x02\u017F\u0180\x07m\x02\x02\u0180" + + "n\x03\x02\x02\x02\u0181\u0182\x07n\x02\x02\u0182p\x03\x02\x02\x02\u0183" + + "\u0184\x07o\x02\x02\u0184r\x03\x02\x02\x02\u0185\u0186\x07p\x02\x02\u0186" + + "t\x03\x02\x02\x02\u0187\u0188\x07q\x02\x02\u0188v\x03\x02\x02\x02\u0189" + + "\u018A\x07r\x02\x02\u018Ax\x03\x02\x02\x02\u018B\u018C\x07s\x02\x02\u018C" + + "z\x03\x02\x02\x02\u018D\u018E\x07t\x02\x02\u018E|\x03\x02\x02\x02\u018F" + + "\u0190\x07u\x02\x02\u0190~\x03\x02\x02\x02\u0191\u0192\x07v\x02\x02\u0192" + + "\x80\x03\x02\x02\x02\u0193\u0194\x07w\x02\x02\u0194\x82\x03\x02\x02\x02" + + "\u0195\u0196\x07x\x02\x02\u0196\x84\x03\x02\x02\x02\u0197\u0198\x07y\x02" + + "\x02\u0198\x86\x03\x02\x02\x02\u0199\u019A\x07z\x02\x02\u019A\x88\x03" + + "\x02\x02\x02\u019B\u019C\x07{\x02\x02\u019C\x8A\x03\x02\x02\x02\u019D" + + "\u019E\x07|\x02\x02\u019E\x8C\x03\x02\x02\x02\u019F\u01A0\x07C\x02\x02" + + "\u01A0\x8E\x03\x02\x02\x02\u01A1\u01A2\x07D\x02\x02\u01A2\x90\x03\x02" + + "\x02\x02\u01A3\u01A4\x07E\x02\x02\u01A4\x92\x03\x02\x02\x02\u01A5\u01A6" + + "\x07F\x02\x02\u01A6\x94\x03\x02\x02\x02\u01A7\u01A8\x07G\x02\x02\u01A8" + + "\x96\x03\x02\x02\x02\u01A9\u01AA\x07H\x02\x02\u01AA\x98\x03\x02\x02\x02" + + "\u01AB\u01AC\x07I\x02\x02\u01AC\x9A\x03\x02\x02\x02\u01AD\u01AE\x07J\x02" + + "\x02\u01AE\x9C\x03\x02\x02\x02\u01AF\u01B0\x07K\x02\x02\u01B0\x9E\x03" + + "\x02\x02\x02\u01B1\u01B2\x07L\x02\x02\u01B2\xA0\x03\x02\x02\x02\u01B3" + + "\u01B4\x07M\x02\x02\u01B4\xA2\x03\x02\x02\x02\u01B5\u01B6\x07N\x02\x02" + + "\u01B6\xA4\x03\x02\x02\x02\u01B7\u01B8\x07O\x02\x02\u01B8\xA6\x03\x02" + + "\x02\x02\u01B9\u01BA\x07P\x02\x02\u01BA\xA8\x03\x02\x02\x02\u01BB\u01BC" + + "\x07Q\x02\x02\u01BC\xAA\x03\x02\x02\x02\u01BD\u01BE\x07R\x02\x02\u01BE" + + "\xAC\x03\x02\x02\x02\u01BF\u01C0\x07S\x02\x02\u01C0\xAE\x03\x02\x02\x02" + + "\u01C1\u01C2\x07T\x02\x02\u01C2\xB0\x03\x02\x02\x02\u01C3\u01C4\x07U\x02" + + "\x02\u01C4\xB2\x03\x02\x02\x02\u01C5\u01C6\x07V\x02\x02\u01C6\xB4\x03" + + "\x02\x02\x02\u01C7\u01C8\x07W\x02\x02\u01C8\xB6\x03\x02\x02\x02\u01C9" + + "\u01CA\x07X\x02\x02\u01CA\xB8\x03\x02\x02\x02\u01CB\u01CC\x07Y\x02\x02" + + "\u01CC\xBA\x03\x02\x02\x02\u01CD\u01CE\x07Z\x02\x02\u01CE\xBC\x03\x02" + + "\x02\x02\u01CF\u01D0\x07[\x02\x02\u01D0\xBE\x03\x02\x02\x02\u01D1\u01D2" + + "\x07\\\x02\x02\u01D2\xC0\x03\x02\x02\x02\u01D3\u01D4\x073\x02\x02\u01D4" + + "\xC2\x03\x02\x02\x02\u01D5\u01D6\x074\x02\x02\u01D6\xC4\x03\x02\x02\x02" + + "\u01D7\u01D8\x075\x02\x02\u01D8\xC6\x03\x02\x02\x02\u01D9\u01DA\x076\x02" + + "\x02\u01DA\xC8\x03\x02\x02\x02\u01DB\u01DC\x077\x02\x02\u01DC\xCA\x03" + + "\x02\x02\x02\u01DD\u01DE\x078\x02\x02\u01DE\xCC\x03\x02\x02\x02\u01DF" + + "\u01E0\x079\x02\x02\u01E0\xCE\x03\x02\x02\x02\u01E1\u01E2\x07:\x02\x02" + + "\u01E2\xD0\x03\x02\x02\x02\u01E3\u01E4\x07;\x02\x02\u01E4\xD2\x03\x02" + + "\x02\x02\u01E5\u01E6\x072\x02\x02\u01E6\xD4\x03\x02\x02\x02\u01E7\u01E8" + + "\v\x02\x02\x02\u01E8\xD6\x03\x02\x02\x02\u01E9\u01EC\x07a\x02\x02\u01EA" + + "\u01EC\x05\xDBn\x02\u01EB\u01E9\x03\x02\x02\x02\u01EB\u01EA\x03\x02\x02" + + "\x02\u01EC\u01ED\x03\x02\x02\x02\u01ED\u01EB\x03\x02\x02\x02\u01ED\u01EE" + + "\x03\x02\x02\x02\u01EE\xD8\x03\x02\x02\x02\u01EF\u01F1\x05\xDBn\x02\u01F0" + + "\u01EF\x03\x02\x02\x02\u01F1\u01F2\x03\x02\x02\x02\u01F2\u01F0\x03\x02" + + "\x02\x02\u01F2\u01F3\x03\x02\x02\x02\u01F3\xDA\x03\x02\x02\x02\u01F4\u01F5" + + "\t\x02\x02\x02\u01F5\xDC\x03\x02\x02\x02\u01F6\u01F7\n\x02\x02\x02\u01F7" + + "\xDE\x03\x02\x02\x02\u01F8\u01F9\t\x03\x02\x02\u01F9\xE0\x03\x02\x02\x02" + + "\u01FA\u01FB\t\x04\x02\x02\u01FB\xE2\x03\x02\x02\x02\t\x02\xEC\u0115\u0119" + + "\u01EB\u01ED\u01F2\x02"; + + return CommonRegexLexer; +} + +var CommonRegexListener = {}; + +var hasRequiredCommonRegexListener; + +function requireCommonRegexListener () { + if (hasRequiredCommonRegexListener) return CommonRegexListener; + hasRequiredCommonRegexListener = 1; + // Generated from src/CommonRegex.g4 by ANTLR 4.7.3-SNAPSHOT + Object.defineProperty(CommonRegexListener, "__esModule", { value: true }); + + return CommonRegexListener; +} + +var CommonRegexParser = {}; + +var hasRequiredCommonRegexParser; + +function requireCommonRegexParser () { + if (hasRequiredCommonRegexParser) return CommonRegexParser; + hasRequiredCommonRegexParser = 1; + // Generated from src/CommonRegex.g4 by ANTLR 4.7.3-SNAPSHOT + var __createBinding = (CommonRegexParser && CommonRegexParser.__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 = (CommonRegexParser && CommonRegexParser.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (CommonRegexParser && CommonRegexParser.__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(CommonRegexParser, "__esModule", { value: true }); + CommonRegexParser.LetterContext = CommonRegexParser.Non_close_parenContext = CommonRegexParser.Non_close_parensContext = CommonRegexParser.Alpha_numsContext = CommonRegexParser.NameContext = CommonRegexParser.DigitContext = CommonRegexParser.DigitsContext = CommonRegexParser.Octal_digitContext = CommonRegexParser.Octal_charContext = CommonRegexParser.NumberContext = CommonRegexParser.Shared_literalContext = CommonRegexParser.Cc_literalContext = CommonRegexParser.LiteralContext = CommonRegexParser.Shared_atomContext = CommonRegexParser.Cc_atomContext = CommonRegexParser.AtomContext = CommonRegexParser.Option_flagContext = CommonRegexParser.OptionContext = CommonRegexParser.Non_captureContext = CommonRegexParser.CaptureContext = CommonRegexParser.Character_classContext = CommonRegexParser.Quantifier_typeContext = CommonRegexParser.QuantifierContext = CommonRegexParser.ElementContext = CommonRegexParser.ExprContext = CommonRegexParser.AlternationContext = CommonRegexParser.ParseContext = CommonRegexParser.CommonRegexParser = void 0; + const ATNDeserializer_1 = requireATNDeserializer(); + const NoViableAltException_1 = requireNoViableAltException(); + const Parser_1 = requireParser$1(); + const ParserRuleContext_1 = requireParserRuleContext(); + const ParserATNSimulator_1 = requireParserATNSimulator(); + const RecognitionException_1 = requireRecognitionException(); + const Token_1 = requireToken(); + const VocabularyImpl_1 = requireVocabularyImpl(); + const Utils = __importStar(requireUtils()); + let CommonRegexParser$1 = class CommonRegexParser extends Parser_1.Parser { + constructor(input) { + super(input); + this._interp = new ParserATNSimulator_1.ParserATNSimulator(CommonRegexParser._ATN, this); + } + // @Override + // @NotNull + get vocabulary() { + return CommonRegexParser.VOCABULARY; + } + // tslint:enable:no-trailing-whitespace + // @Override + get grammarFileName() { return "CommonRegex.g4"; } + // @Override + get ruleNames() { return CommonRegexParser.ruleNames; } + // @Override + get serializedATN() { return CommonRegexParser._serializedATN; } + // @RuleVersion(0) + parse() { + let _localctx = new ParseContext(this._ctx, this.state); + this.enterRule(_localctx, 0, CommonRegexParser.RULE_parse); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 54; + this.alternation(); + this.state = 55; + this.match(CommonRegexParser.EOF); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + alternation() { + let _localctx = new AlternationContext(this._ctx, this.state); + this.enterRule(_localctx, 2, CommonRegexParser.RULE_alternation); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 57; + this.expr(); + this.state = 62; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (_la === CommonRegexParser.Pipe) { + { + { + this.state = 58; + this.match(CommonRegexParser.Pipe); + this.state = 59; + this.expr(); + } + } + this.state = 64; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + expr() { + let _localctx = new ExprContext(this._ctx, this.state); + this.enterRule(_localctx, 4, CommonRegexParser.RULE_expr); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 68; + this._errHandler.sync(this); + _la = this._input.LA(1); + while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CommonRegexParser.Quoted) | (1 << CommonRegexParser.BlockQuoted) | (1 << CommonRegexParser.BellChar) | (1 << CommonRegexParser.ControlChar) | (1 << CommonRegexParser.EscapeChar) | (1 << CommonRegexParser.FormFeed) | (1 << CommonRegexParser.NewLine) | (1 << CommonRegexParser.CarriageReturn) | (1 << CommonRegexParser.Tab) | (1 << CommonRegexParser.Backslash) | (1 << CommonRegexParser.HexChar) | (1 << CommonRegexParser.Dot) | (1 << CommonRegexParser.DecimalDigit) | (1 << CommonRegexParser.NotDecimalDigit) | (1 << CommonRegexParser.CharWithProperty) | (1 << CommonRegexParser.CharWithoutProperty) | (1 << CommonRegexParser.WhiteSpace) | (1 << CommonRegexParser.NotWhiteSpace) | (1 << CommonRegexParser.WordChar) | (1 << CommonRegexParser.NotWordChar) | (1 << CommonRegexParser.CharacterClassStart) | (1 << CommonRegexParser.CharacterClassEnd) | (1 << CommonRegexParser.Caret) | (1 << CommonRegexParser.Hyphen) | (1 << CommonRegexParser.OpenBrace) | (1 << CommonRegexParser.CloseBrace) | (1 << CommonRegexParser.Comma) | (1 << CommonRegexParser.EndOfSubject))) !== 0) || ((((_la - 33)) & ~0x1F) === 0 && ((1 << (_la - 33)) & ((1 << (CommonRegexParser.OpenParen - 33)) | (1 << (CommonRegexParser.LessThan - 33)) | (1 << (CommonRegexParser.GreaterThan - 33)) | (1 << (CommonRegexParser.SingleQuote - 33)) | (1 << (CommonRegexParser.Underscore - 33)) | (1 << (CommonRegexParser.Colon - 33)) | (1 << (CommonRegexParser.Hash - 33)) | (1 << (CommonRegexParser.Equals - 33)) | (1 << (CommonRegexParser.Exclamation - 33)) | (1 << (CommonRegexParser.Ampersand - 33)) | (1 << (CommonRegexParser.ALC - 33)) | (1 << (CommonRegexParser.BLC - 33)) | (1 << (CommonRegexParser.CLC - 33)) | (1 << (CommonRegexParser.DLC - 33)) | (1 << (CommonRegexParser.ELC - 33)) | (1 << (CommonRegexParser.FLC - 33)) | (1 << (CommonRegexParser.GLC - 33)) | (1 << (CommonRegexParser.HLC - 33)) | (1 << (CommonRegexParser.ILC - 33)) | (1 << (CommonRegexParser.JLC - 33)) | (1 << (CommonRegexParser.KLC - 33)) | (1 << (CommonRegexParser.LLC - 33)) | (1 << (CommonRegexParser.MLC - 33)) | (1 << (CommonRegexParser.NLC - 33)) | (1 << (CommonRegexParser.OLC - 33)) | (1 << (CommonRegexParser.PLC - 33)) | (1 << (CommonRegexParser.QLC - 33)) | (1 << (CommonRegexParser.RLC - 33)) | (1 << (CommonRegexParser.SLC - 33)) | (1 << (CommonRegexParser.TLC - 33)) | (1 << (CommonRegexParser.ULC - 33)))) !== 0) || ((((_la - 65)) & ~0x1F) === 0 && ((1 << (_la - 65)) & ((1 << (CommonRegexParser.VLC - 65)) | (1 << (CommonRegexParser.WLC - 65)) | (1 << (CommonRegexParser.XLC - 65)) | (1 << (CommonRegexParser.YLC - 65)) | (1 << (CommonRegexParser.ZLC - 65)) | (1 << (CommonRegexParser.AUC - 65)) | (1 << (CommonRegexParser.BUC - 65)) | (1 << (CommonRegexParser.CUC - 65)) | (1 << (CommonRegexParser.DUC - 65)) | (1 << (CommonRegexParser.EUC - 65)) | (1 << (CommonRegexParser.FUC - 65)) | (1 << (CommonRegexParser.GUC - 65)) | (1 << (CommonRegexParser.HUC - 65)) | (1 << (CommonRegexParser.IUC - 65)) | (1 << (CommonRegexParser.JUC - 65)) | (1 << (CommonRegexParser.KUC - 65)) | (1 << (CommonRegexParser.LUC - 65)) | (1 << (CommonRegexParser.MUC - 65)) | (1 << (CommonRegexParser.NUC - 65)) | (1 << (CommonRegexParser.OUC - 65)) | (1 << (CommonRegexParser.PUC - 65)) | (1 << (CommonRegexParser.QUC - 65)) | (1 << (CommonRegexParser.RUC - 65)) | (1 << (CommonRegexParser.SUC - 65)) | (1 << (CommonRegexParser.TUC - 65)) | (1 << (CommonRegexParser.UUC - 65)) | (1 << (CommonRegexParser.VUC - 65)) | (1 << (CommonRegexParser.WUC - 65)) | (1 << (CommonRegexParser.XUC - 65)) | (1 << (CommonRegexParser.YUC - 65)) | (1 << (CommonRegexParser.ZUC - 65)) | (1 << (CommonRegexParser.D1 - 65)))) !== 0) || ((((_la - 97)) & ~0x1F) === 0 && ((1 << (_la - 97)) & ((1 << (CommonRegexParser.D2 - 97)) | (1 << (CommonRegexParser.D3 - 97)) | (1 << (CommonRegexParser.D4 - 97)) | (1 << (CommonRegexParser.D5 - 97)) | (1 << (CommonRegexParser.D6 - 97)) | (1 << (CommonRegexParser.D7 - 97)) | (1 << (CommonRegexParser.D8 - 97)) | (1 << (CommonRegexParser.D9 - 97)) | (1 << (CommonRegexParser.D0 - 97)) | (1 << (CommonRegexParser.OtherChar - 97)))) !== 0)) { + { + { + this.state = 65; + this.element(); + } + } + this.state = 70; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + element() { + let _localctx = new ElementContext(this._ctx, this.state); + this.enterRule(_localctx, 6, CommonRegexParser.RULE_element); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 71; + this.atom(); + this.state = 73; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 2, this._ctx)) { + case 1: + { + this.state = 72; + this.quantifier(); + } + break; + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + quantifier() { + let _localctx = new QuantifierContext(this._ctx, this.state); + this.enterRule(_localctx, 8, CommonRegexParser.RULE_quantifier); + try { + this.state = 99; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 3, this._ctx)) { + case 1: + this.enterOuterAlt(_localctx, 1); + { + this.state = 75; + this.match(CommonRegexParser.QuestionMark); + this.state = 76; + this.quantifier_type(); + } + break; + case 2: + this.enterOuterAlt(_localctx, 2); + { + this.state = 77; + this.match(CommonRegexParser.Plus); + this.state = 78; + this.quantifier_type(); + } + break; + case 3: + this.enterOuterAlt(_localctx, 3); + { + this.state = 79; + this.match(CommonRegexParser.Star); + this.state = 80; + this.quantifier_type(); + } + break; + case 4: + this.enterOuterAlt(_localctx, 4); + { + this.state = 81; + this.match(CommonRegexParser.OpenBrace); + this.state = 82; + this.number(); + this.state = 83; + this.match(CommonRegexParser.CloseBrace); + this.state = 84; + this.quantifier_type(); + } + break; + case 5: + this.enterOuterAlt(_localctx, 5); + { + this.state = 86; + this.match(CommonRegexParser.OpenBrace); + this.state = 87; + this.number(); + this.state = 88; + this.match(CommonRegexParser.Comma); + this.state = 89; + this.match(CommonRegexParser.CloseBrace); + this.state = 90; + this.quantifier_type(); + } + break; + case 6: + this.enterOuterAlt(_localctx, 6); + { + this.state = 92; + this.match(CommonRegexParser.OpenBrace); + this.state = 93; + this.number(); + this.state = 94; + this.match(CommonRegexParser.Comma); + this.state = 95; + this.number(); + this.state = 96; + this.match(CommonRegexParser.CloseBrace); + this.state = 97; + this.quantifier_type(); + } + break; + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + quantifier_type() { + let _localctx = new Quantifier_typeContext(this._ctx, this.state); + this.enterRule(_localctx, 10, CommonRegexParser.RULE_quantifier_type); + try { + this.state = 104; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.Plus: + this.enterOuterAlt(_localctx, 1); + { + this.state = 101; + this.match(CommonRegexParser.Plus); + } + break; + case CommonRegexParser.QuestionMark: + this.enterOuterAlt(_localctx, 2); + { + this.state = 102; + this.match(CommonRegexParser.QuestionMark); + } + break; + case CommonRegexParser.EOF: + case CommonRegexParser.Quoted: + case CommonRegexParser.BlockQuoted: + case CommonRegexParser.BellChar: + case CommonRegexParser.ControlChar: + case CommonRegexParser.EscapeChar: + case CommonRegexParser.FormFeed: + case CommonRegexParser.NewLine: + case CommonRegexParser.CarriageReturn: + case CommonRegexParser.Tab: + case CommonRegexParser.Backslash: + case CommonRegexParser.HexChar: + case CommonRegexParser.Dot: + case CommonRegexParser.DecimalDigit: + case CommonRegexParser.NotDecimalDigit: + case CommonRegexParser.CharWithProperty: + case CommonRegexParser.CharWithoutProperty: + case CommonRegexParser.WhiteSpace: + case CommonRegexParser.NotWhiteSpace: + case CommonRegexParser.WordChar: + case CommonRegexParser.NotWordChar: + case CommonRegexParser.CharacterClassStart: + case CommonRegexParser.CharacterClassEnd: + case CommonRegexParser.Caret: + case CommonRegexParser.Hyphen: + case CommonRegexParser.OpenBrace: + case CommonRegexParser.CloseBrace: + case CommonRegexParser.Comma: + case CommonRegexParser.EndOfSubject: + case CommonRegexParser.Pipe: + case CommonRegexParser.OpenParen: + case CommonRegexParser.CloseParen: + case CommonRegexParser.LessThan: + case CommonRegexParser.GreaterThan: + case CommonRegexParser.SingleQuote: + case CommonRegexParser.Underscore: + case CommonRegexParser.Colon: + case CommonRegexParser.Hash: + case CommonRegexParser.Equals: + case CommonRegexParser.Exclamation: + case CommonRegexParser.Ampersand: + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + case CommonRegexParser.D1: + case CommonRegexParser.D2: + case CommonRegexParser.D3: + case CommonRegexParser.D4: + case CommonRegexParser.D5: + case CommonRegexParser.D6: + case CommonRegexParser.D7: + case CommonRegexParser.D8: + case CommonRegexParser.D9: + case CommonRegexParser.D0: + case CommonRegexParser.OtherChar: + this.enterOuterAlt(_localctx, 3); + // tslint:disable-next-line:no-empty + { + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + character_class() { + let _localctx = new Character_classContext(this._ctx, this.state); + this.enterRule(_localctx, 12, CommonRegexParser.RULE_character_class); + let _la; + try { + this.state = 123; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 7, this._ctx)) { + case 1: + this.enterOuterAlt(_localctx, 1); + { + this.state = 106; + this.match(CommonRegexParser.CharacterClassStart); + this.state = 107; + this.match(CommonRegexParser.Caret); + this.state = 109; + this._errHandler.sync(this); + _la = this._input.LA(1); + do { + { + { + this.state = 108; + this.cc_atom(); + } + } + this.state = 111; + this._errHandler.sync(this); + _la = this._input.LA(1); + } while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CommonRegexParser.Quoted) | (1 << CommonRegexParser.BlockQuoted) | (1 << CommonRegexParser.BellChar) | (1 << CommonRegexParser.ControlChar) | (1 << CommonRegexParser.EscapeChar) | (1 << CommonRegexParser.FormFeed) | (1 << CommonRegexParser.NewLine) | (1 << CommonRegexParser.CarriageReturn) | (1 << CommonRegexParser.Tab) | (1 << CommonRegexParser.Backslash) | (1 << CommonRegexParser.HexChar) | (1 << CommonRegexParser.Dot) | (1 << CommonRegexParser.DecimalDigit) | (1 << CommonRegexParser.NotDecimalDigit) | (1 << CommonRegexParser.CharWithProperty) | (1 << CommonRegexParser.CharWithoutProperty) | (1 << CommonRegexParser.WhiteSpace) | (1 << CommonRegexParser.NotWhiteSpace) | (1 << CommonRegexParser.WordChar) | (1 << CommonRegexParser.NotWordChar) | (1 << CommonRegexParser.CharacterClassStart) | (1 << CommonRegexParser.Caret) | (1 << CommonRegexParser.Hyphen) | (1 << CommonRegexParser.QuestionMark) | (1 << CommonRegexParser.Plus) | (1 << CommonRegexParser.Star) | (1 << CommonRegexParser.OpenBrace) | (1 << CommonRegexParser.CloseBrace) | (1 << CommonRegexParser.Comma) | (1 << CommonRegexParser.EndOfSubject))) !== 0) || ((((_la - 32)) & ~0x1F) === 0 && ((1 << (_la - 32)) & ((1 << (CommonRegexParser.Pipe - 32)) | (1 << (CommonRegexParser.OpenParen - 32)) | (1 << (CommonRegexParser.CloseParen - 32)) | (1 << (CommonRegexParser.LessThan - 32)) | (1 << (CommonRegexParser.GreaterThan - 32)) | (1 << (CommonRegexParser.SingleQuote - 32)) | (1 << (CommonRegexParser.Underscore - 32)) | (1 << (CommonRegexParser.Colon - 32)) | (1 << (CommonRegexParser.Hash - 32)) | (1 << (CommonRegexParser.Equals - 32)) | (1 << (CommonRegexParser.Exclamation - 32)) | (1 << (CommonRegexParser.Ampersand - 32)) | (1 << (CommonRegexParser.ALC - 32)) | (1 << (CommonRegexParser.BLC - 32)) | (1 << (CommonRegexParser.CLC - 32)) | (1 << (CommonRegexParser.DLC - 32)) | (1 << (CommonRegexParser.ELC - 32)) | (1 << (CommonRegexParser.FLC - 32)) | (1 << (CommonRegexParser.GLC - 32)) | (1 << (CommonRegexParser.HLC - 32)) | (1 << (CommonRegexParser.ILC - 32)) | (1 << (CommonRegexParser.JLC - 32)) | (1 << (CommonRegexParser.KLC - 32)) | (1 << (CommonRegexParser.LLC - 32)) | (1 << (CommonRegexParser.MLC - 32)) | (1 << (CommonRegexParser.NLC - 32)) | (1 << (CommonRegexParser.OLC - 32)) | (1 << (CommonRegexParser.PLC - 32)) | (1 << (CommonRegexParser.QLC - 32)) | (1 << (CommonRegexParser.RLC - 32)) | (1 << (CommonRegexParser.SLC - 32)) | (1 << (CommonRegexParser.TLC - 32)))) !== 0) || ((((_la - 64)) & ~0x1F) === 0 && ((1 << (_la - 64)) & ((1 << (CommonRegexParser.ULC - 64)) | (1 << (CommonRegexParser.VLC - 64)) | (1 << (CommonRegexParser.WLC - 64)) | (1 << (CommonRegexParser.XLC - 64)) | (1 << (CommonRegexParser.YLC - 64)) | (1 << (CommonRegexParser.ZLC - 64)) | (1 << (CommonRegexParser.AUC - 64)) | (1 << (CommonRegexParser.BUC - 64)) | (1 << (CommonRegexParser.CUC - 64)) | (1 << (CommonRegexParser.DUC - 64)) | (1 << (CommonRegexParser.EUC - 64)) | (1 << (CommonRegexParser.FUC - 64)) | (1 << (CommonRegexParser.GUC - 64)) | (1 << (CommonRegexParser.HUC - 64)) | (1 << (CommonRegexParser.IUC - 64)) | (1 << (CommonRegexParser.JUC - 64)) | (1 << (CommonRegexParser.KUC - 64)) | (1 << (CommonRegexParser.LUC - 64)) | (1 << (CommonRegexParser.MUC - 64)) | (1 << (CommonRegexParser.NUC - 64)) | (1 << (CommonRegexParser.OUC - 64)) | (1 << (CommonRegexParser.PUC - 64)) | (1 << (CommonRegexParser.QUC - 64)) | (1 << (CommonRegexParser.RUC - 64)) | (1 << (CommonRegexParser.SUC - 64)) | (1 << (CommonRegexParser.TUC - 64)) | (1 << (CommonRegexParser.UUC - 64)) | (1 << (CommonRegexParser.VUC - 64)) | (1 << (CommonRegexParser.WUC - 64)) | (1 << (CommonRegexParser.XUC - 64)) | (1 << (CommonRegexParser.YUC - 64)) | (1 << (CommonRegexParser.ZUC - 64)))) !== 0) || ((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D8 - 96)) | (1 << (CommonRegexParser.D9 - 96)) | (1 << (CommonRegexParser.D0 - 96)) | (1 << (CommonRegexParser.OtherChar - 96)))) !== 0)); + this.state = 113; + this.match(CommonRegexParser.CharacterClassEnd); + } + break; + case 2: + this.enterOuterAlt(_localctx, 2); + { + this.state = 115; + this.match(CommonRegexParser.CharacterClassStart); + this.state = 117; + this._errHandler.sync(this); + _la = this._input.LA(1); + do { + { + { + this.state = 116; + this.cc_atom(); + } + } + this.state = 119; + this._errHandler.sync(this); + _la = this._input.LA(1); + } while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CommonRegexParser.Quoted) | (1 << CommonRegexParser.BlockQuoted) | (1 << CommonRegexParser.BellChar) | (1 << CommonRegexParser.ControlChar) | (1 << CommonRegexParser.EscapeChar) | (1 << CommonRegexParser.FormFeed) | (1 << CommonRegexParser.NewLine) | (1 << CommonRegexParser.CarriageReturn) | (1 << CommonRegexParser.Tab) | (1 << CommonRegexParser.Backslash) | (1 << CommonRegexParser.HexChar) | (1 << CommonRegexParser.Dot) | (1 << CommonRegexParser.DecimalDigit) | (1 << CommonRegexParser.NotDecimalDigit) | (1 << CommonRegexParser.CharWithProperty) | (1 << CommonRegexParser.CharWithoutProperty) | (1 << CommonRegexParser.WhiteSpace) | (1 << CommonRegexParser.NotWhiteSpace) | (1 << CommonRegexParser.WordChar) | (1 << CommonRegexParser.NotWordChar) | (1 << CommonRegexParser.CharacterClassStart) | (1 << CommonRegexParser.Caret) | (1 << CommonRegexParser.Hyphen) | (1 << CommonRegexParser.QuestionMark) | (1 << CommonRegexParser.Plus) | (1 << CommonRegexParser.Star) | (1 << CommonRegexParser.OpenBrace) | (1 << CommonRegexParser.CloseBrace) | (1 << CommonRegexParser.Comma) | (1 << CommonRegexParser.EndOfSubject))) !== 0) || ((((_la - 32)) & ~0x1F) === 0 && ((1 << (_la - 32)) & ((1 << (CommonRegexParser.Pipe - 32)) | (1 << (CommonRegexParser.OpenParen - 32)) | (1 << (CommonRegexParser.CloseParen - 32)) | (1 << (CommonRegexParser.LessThan - 32)) | (1 << (CommonRegexParser.GreaterThan - 32)) | (1 << (CommonRegexParser.SingleQuote - 32)) | (1 << (CommonRegexParser.Underscore - 32)) | (1 << (CommonRegexParser.Colon - 32)) | (1 << (CommonRegexParser.Hash - 32)) | (1 << (CommonRegexParser.Equals - 32)) | (1 << (CommonRegexParser.Exclamation - 32)) | (1 << (CommonRegexParser.Ampersand - 32)) | (1 << (CommonRegexParser.ALC - 32)) | (1 << (CommonRegexParser.BLC - 32)) | (1 << (CommonRegexParser.CLC - 32)) | (1 << (CommonRegexParser.DLC - 32)) | (1 << (CommonRegexParser.ELC - 32)) | (1 << (CommonRegexParser.FLC - 32)) | (1 << (CommonRegexParser.GLC - 32)) | (1 << (CommonRegexParser.HLC - 32)) | (1 << (CommonRegexParser.ILC - 32)) | (1 << (CommonRegexParser.JLC - 32)) | (1 << (CommonRegexParser.KLC - 32)) | (1 << (CommonRegexParser.LLC - 32)) | (1 << (CommonRegexParser.MLC - 32)) | (1 << (CommonRegexParser.NLC - 32)) | (1 << (CommonRegexParser.OLC - 32)) | (1 << (CommonRegexParser.PLC - 32)) | (1 << (CommonRegexParser.QLC - 32)) | (1 << (CommonRegexParser.RLC - 32)) | (1 << (CommonRegexParser.SLC - 32)) | (1 << (CommonRegexParser.TLC - 32)))) !== 0) || ((((_la - 64)) & ~0x1F) === 0 && ((1 << (_la - 64)) & ((1 << (CommonRegexParser.ULC - 64)) | (1 << (CommonRegexParser.VLC - 64)) | (1 << (CommonRegexParser.WLC - 64)) | (1 << (CommonRegexParser.XLC - 64)) | (1 << (CommonRegexParser.YLC - 64)) | (1 << (CommonRegexParser.ZLC - 64)) | (1 << (CommonRegexParser.AUC - 64)) | (1 << (CommonRegexParser.BUC - 64)) | (1 << (CommonRegexParser.CUC - 64)) | (1 << (CommonRegexParser.DUC - 64)) | (1 << (CommonRegexParser.EUC - 64)) | (1 << (CommonRegexParser.FUC - 64)) | (1 << (CommonRegexParser.GUC - 64)) | (1 << (CommonRegexParser.HUC - 64)) | (1 << (CommonRegexParser.IUC - 64)) | (1 << (CommonRegexParser.JUC - 64)) | (1 << (CommonRegexParser.KUC - 64)) | (1 << (CommonRegexParser.LUC - 64)) | (1 << (CommonRegexParser.MUC - 64)) | (1 << (CommonRegexParser.NUC - 64)) | (1 << (CommonRegexParser.OUC - 64)) | (1 << (CommonRegexParser.PUC - 64)) | (1 << (CommonRegexParser.QUC - 64)) | (1 << (CommonRegexParser.RUC - 64)) | (1 << (CommonRegexParser.SUC - 64)) | (1 << (CommonRegexParser.TUC - 64)) | (1 << (CommonRegexParser.UUC - 64)) | (1 << (CommonRegexParser.VUC - 64)) | (1 << (CommonRegexParser.WUC - 64)) | (1 << (CommonRegexParser.XUC - 64)) | (1 << (CommonRegexParser.YUC - 64)) | (1 << (CommonRegexParser.ZUC - 64)))) !== 0) || ((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D8 - 96)) | (1 << (CommonRegexParser.D9 - 96)) | (1 << (CommonRegexParser.D0 - 96)) | (1 << (CommonRegexParser.OtherChar - 96)))) !== 0)); + this.state = 121; + this.match(CommonRegexParser.CharacterClassEnd); + } + break; + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + capture() { + let _localctx = new CaptureContext(this._ctx, this.state); + this.enterRule(_localctx, 14, CommonRegexParser.RULE_capture); + try { + this.state = 137; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 8, this._ctx)) { + case 1: + this.enterOuterAlt(_localctx, 1); + { + this.state = 125; + this.match(CommonRegexParser.OpenParen); + this.state = 126; + this.match(CommonRegexParser.QuestionMark); + this.state = 127; + this.match(CommonRegexParser.LessThan); + this.state = 128; + this.name(); + this.state = 129; + this.match(CommonRegexParser.GreaterThan); + this.state = 130; + this.alternation(); + this.state = 131; + this.match(CommonRegexParser.CloseParen); + } + break; + case 2: + this.enterOuterAlt(_localctx, 2); + { + this.state = 133; + this.match(CommonRegexParser.OpenParen); + this.state = 134; + this.alternation(); + this.state = 135; + this.match(CommonRegexParser.CloseParen); + } + break; + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + non_capture() { + let _localctx = new Non_captureContext(this._ctx, this.state); + this.enterRule(_localctx, 16, CommonRegexParser.RULE_non_capture); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 139; + this.match(CommonRegexParser.OpenParen); + this.state = 140; + this.match(CommonRegexParser.QuestionMark); + this.state = 141; + this.match(CommonRegexParser.Colon); + this.state = 142; + this.alternation(); + this.state = 143; + this.match(CommonRegexParser.CloseParen); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + option() { + let _localctx = new OptionContext(this._ctx, this.state); + this.enterRule(_localctx, 18, CommonRegexParser.RULE_option); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 145; + this.match(CommonRegexParser.OpenParen); + this.state = 146; + this.match(CommonRegexParser.QuestionMark); + this.state = 148; + this._errHandler.sync(this); + _la = this._input.LA(1); + do { + { + { + this.state = 147; + this.option_flag(); + } + } + this.state = 150; + this._errHandler.sync(this); + _la = this._input.LA(1); + } while (((((_la - 52)) & ~0x1F) === 0 && ((1 << (_la - 52)) & ((1 << (CommonRegexParser.ILC - 52)) | (1 << (CommonRegexParser.MLC - 52)) | (1 << (CommonRegexParser.SLC - 52)))) !== 0)); + this.state = 152; + this.match(CommonRegexParser.CloseParen); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + option_flag() { + let _localctx = new Option_flagContext(this._ctx, this.state); + this.enterRule(_localctx, 20, CommonRegexParser.RULE_option_flag); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 154; + _la = this._input.LA(1); + if (!(((((_la - 52)) & ~0x1F) === 0 && ((1 << (_la - 52)) & ((1 << (CommonRegexParser.ILC - 52)) | (1 << (CommonRegexParser.MLC - 52)) | (1 << (CommonRegexParser.SLC - 52)))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + atom() { + let _localctx = new AtomContext(this._ctx, this.state); + this.enterRule(_localctx, 22, CommonRegexParser.RULE_atom); + try { + this.state = 165; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 10, this._ctx)) { + case 1: + this.enterOuterAlt(_localctx, 1); + { + this.state = 156; + this.shared_atom(); + } + break; + case 2: + this.enterOuterAlt(_localctx, 2); + { + this.state = 157; + this.literal(); + } + break; + case 3: + this.enterOuterAlt(_localctx, 3); + { + this.state = 158; + this.character_class(); + } + break; + case 4: + this.enterOuterAlt(_localctx, 4); + { + this.state = 159; + this.capture(); + } + break; + case 5: + this.enterOuterAlt(_localctx, 5); + { + this.state = 160; + this.non_capture(); + } + break; + case 6: + this.enterOuterAlt(_localctx, 6); + { + this.state = 161; + this.option(); + } + break; + case 7: + this.enterOuterAlt(_localctx, 7); + { + this.state = 162; + this.match(CommonRegexParser.Dot); + } + break; + case 8: + this.enterOuterAlt(_localctx, 8); + { + this.state = 163; + this.match(CommonRegexParser.Caret); + } + break; + case 9: + this.enterOuterAlt(_localctx, 9); + { + this.state = 164; + this.match(CommonRegexParser.EndOfSubject); + } + break; + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + cc_atom() { + let _localctx = new Cc_atomContext(this._ctx, this.state); + this.enterRule(_localctx, 24, CommonRegexParser.RULE_cc_atom); + try { + this.state = 173; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 11, this._ctx)) { + case 1: + this.enterOuterAlt(_localctx, 1); + { + this.state = 167; + this.cc_literal(); + this.state = 168; + this.match(CommonRegexParser.Hyphen); + this.state = 169; + this.cc_literal(); + } + break; + case 2: + this.enterOuterAlt(_localctx, 2); + { + this.state = 171; + this.shared_atom(); + } + break; + case 3: + this.enterOuterAlt(_localctx, 3); + { + this.state = 172; + this.cc_literal(); + } + break; + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + shared_atom() { + let _localctx = new Shared_atomContext(this._ctx, this.state); + this.enterRule(_localctx, 26, CommonRegexParser.RULE_shared_atom); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 175; + _la = this._input.LA(1); + if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CommonRegexParser.ControlChar) | (1 << CommonRegexParser.DecimalDigit) | (1 << CommonRegexParser.NotDecimalDigit) | (1 << CommonRegexParser.CharWithProperty) | (1 << CommonRegexParser.CharWithoutProperty) | (1 << CommonRegexParser.WhiteSpace) | (1 << CommonRegexParser.NotWhiteSpace) | (1 << CommonRegexParser.WordChar) | (1 << CommonRegexParser.NotWordChar))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + literal() { + let _localctx = new LiteralContext(this._ctx, this.state); + this.enterRule(_localctx, 28, CommonRegexParser.RULE_literal); + try { + this.state = 179; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.Quoted: + case CommonRegexParser.BlockQuoted: + case CommonRegexParser.BellChar: + case CommonRegexParser.EscapeChar: + case CommonRegexParser.FormFeed: + case CommonRegexParser.NewLine: + case CommonRegexParser.CarriageReturn: + case CommonRegexParser.Tab: + case CommonRegexParser.Backslash: + case CommonRegexParser.HexChar: + case CommonRegexParser.Hyphen: + case CommonRegexParser.OpenBrace: + case CommonRegexParser.CloseBrace: + case CommonRegexParser.Comma: + case CommonRegexParser.LessThan: + case CommonRegexParser.GreaterThan: + case CommonRegexParser.SingleQuote: + case CommonRegexParser.Underscore: + case CommonRegexParser.Colon: + case CommonRegexParser.Hash: + case CommonRegexParser.Equals: + case CommonRegexParser.Exclamation: + case CommonRegexParser.Ampersand: + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + case CommonRegexParser.D1: + case CommonRegexParser.D2: + case CommonRegexParser.D3: + case CommonRegexParser.D4: + case CommonRegexParser.D5: + case CommonRegexParser.D6: + case CommonRegexParser.D7: + case CommonRegexParser.D8: + case CommonRegexParser.D9: + case CommonRegexParser.D0: + case CommonRegexParser.OtherChar: + this.enterOuterAlt(_localctx, 1); + { + this.state = 177; + this.shared_literal(); + } + break; + case CommonRegexParser.CharacterClassEnd: + this.enterOuterAlt(_localctx, 2); + { + this.state = 178; + this.match(CommonRegexParser.CharacterClassEnd); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + cc_literal() { + let _localctx = new Cc_literalContext(this._ctx, this.state); + this.enterRule(_localctx, 30, CommonRegexParser.RULE_cc_literal); + try { + this.state = 192; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.Quoted: + case CommonRegexParser.BlockQuoted: + case CommonRegexParser.BellChar: + case CommonRegexParser.EscapeChar: + case CommonRegexParser.FormFeed: + case CommonRegexParser.NewLine: + case CommonRegexParser.CarriageReturn: + case CommonRegexParser.Tab: + case CommonRegexParser.Backslash: + case CommonRegexParser.HexChar: + case CommonRegexParser.Hyphen: + case CommonRegexParser.OpenBrace: + case CommonRegexParser.CloseBrace: + case CommonRegexParser.Comma: + case CommonRegexParser.LessThan: + case CommonRegexParser.GreaterThan: + case CommonRegexParser.SingleQuote: + case CommonRegexParser.Underscore: + case CommonRegexParser.Colon: + case CommonRegexParser.Hash: + case CommonRegexParser.Equals: + case CommonRegexParser.Exclamation: + case CommonRegexParser.Ampersand: + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + case CommonRegexParser.D1: + case CommonRegexParser.D2: + case CommonRegexParser.D3: + case CommonRegexParser.D4: + case CommonRegexParser.D5: + case CommonRegexParser.D6: + case CommonRegexParser.D7: + case CommonRegexParser.D8: + case CommonRegexParser.D9: + case CommonRegexParser.D0: + case CommonRegexParser.OtherChar: + this.enterOuterAlt(_localctx, 1); + { + this.state = 181; + this.shared_literal(); + } + break; + case CommonRegexParser.Dot: + this.enterOuterAlt(_localctx, 2); + { + this.state = 182; + this.match(CommonRegexParser.Dot); + } + break; + case CommonRegexParser.CharacterClassStart: + this.enterOuterAlt(_localctx, 3); + { + this.state = 183; + this.match(CommonRegexParser.CharacterClassStart); + } + break; + case CommonRegexParser.Caret: + this.enterOuterAlt(_localctx, 4); + { + this.state = 184; + this.match(CommonRegexParser.Caret); + } + break; + case CommonRegexParser.QuestionMark: + this.enterOuterAlt(_localctx, 5); + { + this.state = 185; + this.match(CommonRegexParser.QuestionMark); + } + break; + case CommonRegexParser.Plus: + this.enterOuterAlt(_localctx, 6); + { + this.state = 186; + this.match(CommonRegexParser.Plus); + } + break; + case CommonRegexParser.Star: + this.enterOuterAlt(_localctx, 7); + { + this.state = 187; + this.match(CommonRegexParser.Star); + } + break; + case CommonRegexParser.EndOfSubject: + this.enterOuterAlt(_localctx, 8); + { + this.state = 188; + this.match(CommonRegexParser.EndOfSubject); + } + break; + case CommonRegexParser.Pipe: + this.enterOuterAlt(_localctx, 9); + { + this.state = 189; + this.match(CommonRegexParser.Pipe); + } + break; + case CommonRegexParser.OpenParen: + this.enterOuterAlt(_localctx, 10); + { + this.state = 190; + this.match(CommonRegexParser.OpenParen); + } + break; + case CommonRegexParser.CloseParen: + this.enterOuterAlt(_localctx, 11); + { + this.state = 191; + this.match(CommonRegexParser.CloseParen); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + shared_literal() { + let _localctx = new Shared_literalContext(this._ctx, this.state); + this.enterRule(_localctx, 32, CommonRegexParser.RULE_shared_literal); + try { + this.state = 220; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.Backslash: + this.enterOuterAlt(_localctx, 1); + { + this.state = 194; + this.octal_char(); + } + break; + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + this.enterOuterAlt(_localctx, 2); + { + this.state = 195; + this.letter(); + } + break; + case CommonRegexParser.D1: + case CommonRegexParser.D2: + case CommonRegexParser.D3: + case CommonRegexParser.D4: + case CommonRegexParser.D5: + case CommonRegexParser.D6: + case CommonRegexParser.D7: + case CommonRegexParser.D8: + case CommonRegexParser.D9: + case CommonRegexParser.D0: + this.enterOuterAlt(_localctx, 3); + { + this.state = 196; + this.digit(); + } + break; + case CommonRegexParser.BellChar: + this.enterOuterAlt(_localctx, 4); + { + this.state = 197; + this.match(CommonRegexParser.BellChar); + } + break; + case CommonRegexParser.EscapeChar: + this.enterOuterAlt(_localctx, 5); + { + this.state = 198; + this.match(CommonRegexParser.EscapeChar); + } + break; + case CommonRegexParser.FormFeed: + this.enterOuterAlt(_localctx, 6); + { + this.state = 199; + this.match(CommonRegexParser.FormFeed); + } + break; + case CommonRegexParser.NewLine: + this.enterOuterAlt(_localctx, 7); + { + this.state = 200; + this.match(CommonRegexParser.NewLine); + } + break; + case CommonRegexParser.CarriageReturn: + this.enterOuterAlt(_localctx, 8); + { + this.state = 201; + this.match(CommonRegexParser.CarriageReturn); + } + break; + case CommonRegexParser.Tab: + this.enterOuterAlt(_localctx, 9); + { + this.state = 202; + this.match(CommonRegexParser.Tab); + } + break; + case CommonRegexParser.HexChar: + this.enterOuterAlt(_localctx, 10); + { + this.state = 203; + this.match(CommonRegexParser.HexChar); + } + break; + case CommonRegexParser.Quoted: + this.enterOuterAlt(_localctx, 11); + { + this.state = 204; + this.match(CommonRegexParser.Quoted); + } + break; + case CommonRegexParser.BlockQuoted: + this.enterOuterAlt(_localctx, 12); + { + this.state = 205; + this.match(CommonRegexParser.BlockQuoted); + } + break; + case CommonRegexParser.OpenBrace: + this.enterOuterAlt(_localctx, 13); + { + this.state = 206; + this.match(CommonRegexParser.OpenBrace); + } + break; + case CommonRegexParser.CloseBrace: + this.enterOuterAlt(_localctx, 14); + { + this.state = 207; + this.match(CommonRegexParser.CloseBrace); + } + break; + case CommonRegexParser.Comma: + this.enterOuterAlt(_localctx, 15); + { + this.state = 208; + this.match(CommonRegexParser.Comma); + } + break; + case CommonRegexParser.Hyphen: + this.enterOuterAlt(_localctx, 16); + { + this.state = 209; + this.match(CommonRegexParser.Hyphen); + } + break; + case CommonRegexParser.LessThan: + this.enterOuterAlt(_localctx, 17); + { + this.state = 210; + this.match(CommonRegexParser.LessThan); + } + break; + case CommonRegexParser.GreaterThan: + this.enterOuterAlt(_localctx, 18); + { + this.state = 211; + this.match(CommonRegexParser.GreaterThan); + } + break; + case CommonRegexParser.SingleQuote: + this.enterOuterAlt(_localctx, 19); + { + this.state = 212; + this.match(CommonRegexParser.SingleQuote); + } + break; + case CommonRegexParser.Underscore: + this.enterOuterAlt(_localctx, 20); + { + this.state = 213; + this.match(CommonRegexParser.Underscore); + } + break; + case CommonRegexParser.Colon: + this.enterOuterAlt(_localctx, 21); + { + this.state = 214; + this.match(CommonRegexParser.Colon); + } + break; + case CommonRegexParser.Hash: + this.enterOuterAlt(_localctx, 22); + { + this.state = 215; + this.match(CommonRegexParser.Hash); + } + break; + case CommonRegexParser.Equals: + this.enterOuterAlt(_localctx, 23); + { + this.state = 216; + this.match(CommonRegexParser.Equals); + } + break; + case CommonRegexParser.Exclamation: + this.enterOuterAlt(_localctx, 24); + { + this.state = 217; + this.match(CommonRegexParser.Exclamation); + } + break; + case CommonRegexParser.Ampersand: + this.enterOuterAlt(_localctx, 25); + { + this.state = 218; + this.match(CommonRegexParser.Ampersand); + } + break; + case CommonRegexParser.OtherChar: + this.enterOuterAlt(_localctx, 26); + { + this.state = 219; + this.match(CommonRegexParser.OtherChar); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + number() { + let _localctx = new NumberContext(this._ctx, this.state); + this.enterRule(_localctx, 34, CommonRegexParser.RULE_number); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 222; + this.digits(); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + octal_char() { + let _localctx = new Octal_charContext(this._ctx, this.state); + this.enterRule(_localctx, 36, CommonRegexParser.RULE_octal_char); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 233; + this._errHandler.sync(this); + switch (this.interpreter.adaptivePredict(this._input, 15, this._ctx)) { + case 1: + { + this.state = 224; + this.match(CommonRegexParser.Backslash); + this.state = 225; + _la = this._input.LA(1); + if (!(((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D0 - 96)))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + this.state = 226; + this.octal_digit(); + this.state = 227; + this.octal_digit(); + } + break; + case 2: + { + this.state = 229; + this.match(CommonRegexParser.Backslash); + this.state = 230; + this.octal_digit(); + this.state = 231; + this.octal_digit(); + } + break; + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + octal_digit() { + let _localctx = new Octal_digitContext(this._ctx, this.state); + this.enterRule(_localctx, 38, CommonRegexParser.RULE_octal_digit); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 235; + _la = this._input.LA(1); + if (!(((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D0 - 96)))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + digits() { + let _localctx = new DigitsContext(this._ctx, this.state); + this.enterRule(_localctx, 40, CommonRegexParser.RULE_digits); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 238; + this._errHandler.sync(this); + _la = this._input.LA(1); + do { + { + { + this.state = 237; + this.digit(); + } + } + this.state = 240; + this._errHandler.sync(this); + _la = this._input.LA(1); + } while (((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D8 - 96)) | (1 << (CommonRegexParser.D9 - 96)) | (1 << (CommonRegexParser.D0 - 96)))) !== 0)); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + digit() { + let _localctx = new DigitContext(this._ctx, this.state); + this.enterRule(_localctx, 42, CommonRegexParser.RULE_digit); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 242; + _la = this._input.LA(1); + if (!(((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D8 - 96)) | (1 << (CommonRegexParser.D9 - 96)) | (1 << (CommonRegexParser.D0 - 96)))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + name() { + let _localctx = new NameContext(this._ctx, this.state); + this.enterRule(_localctx, 44, CommonRegexParser.RULE_name); + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 244; + this.alpha_nums(); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + alpha_nums() { + let _localctx = new Alpha_numsContext(this._ctx, this.state); + this.enterRule(_localctx, 46, CommonRegexParser.RULE_alpha_nums); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 248; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + { + this.state = 246; + this.letter(); + } + break; + case CommonRegexParser.Underscore: + { + this.state = 247; + this.match(CommonRegexParser.Underscore); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + this.state = 255; + this._errHandler.sync(this); + _la = this._input.LA(1); + while (((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CommonRegexParser.Underscore - 38)) | (1 << (CommonRegexParser.ALC - 38)) | (1 << (CommonRegexParser.BLC - 38)) | (1 << (CommonRegexParser.CLC - 38)) | (1 << (CommonRegexParser.DLC - 38)) | (1 << (CommonRegexParser.ELC - 38)) | (1 << (CommonRegexParser.FLC - 38)) | (1 << (CommonRegexParser.GLC - 38)) | (1 << (CommonRegexParser.HLC - 38)) | (1 << (CommonRegexParser.ILC - 38)) | (1 << (CommonRegexParser.JLC - 38)) | (1 << (CommonRegexParser.KLC - 38)) | (1 << (CommonRegexParser.LLC - 38)) | (1 << (CommonRegexParser.MLC - 38)) | (1 << (CommonRegexParser.NLC - 38)) | (1 << (CommonRegexParser.OLC - 38)) | (1 << (CommonRegexParser.PLC - 38)) | (1 << (CommonRegexParser.QLC - 38)) | (1 << (CommonRegexParser.RLC - 38)) | (1 << (CommonRegexParser.SLC - 38)) | (1 << (CommonRegexParser.TLC - 38)) | (1 << (CommonRegexParser.ULC - 38)) | (1 << (CommonRegexParser.VLC - 38)) | (1 << (CommonRegexParser.WLC - 38)) | (1 << (CommonRegexParser.XLC - 38)) | (1 << (CommonRegexParser.YLC - 38)) | (1 << (CommonRegexParser.ZLC - 38)))) !== 0) || ((((_la - 70)) & ~0x1F) === 0 && ((1 << (_la - 70)) & ((1 << (CommonRegexParser.AUC - 70)) | (1 << (CommonRegexParser.BUC - 70)) | (1 << (CommonRegexParser.CUC - 70)) | (1 << (CommonRegexParser.DUC - 70)) | (1 << (CommonRegexParser.EUC - 70)) | (1 << (CommonRegexParser.FUC - 70)) | (1 << (CommonRegexParser.GUC - 70)) | (1 << (CommonRegexParser.HUC - 70)) | (1 << (CommonRegexParser.IUC - 70)) | (1 << (CommonRegexParser.JUC - 70)) | (1 << (CommonRegexParser.KUC - 70)) | (1 << (CommonRegexParser.LUC - 70)) | (1 << (CommonRegexParser.MUC - 70)) | (1 << (CommonRegexParser.NUC - 70)) | (1 << (CommonRegexParser.OUC - 70)) | (1 << (CommonRegexParser.PUC - 70)) | (1 << (CommonRegexParser.QUC - 70)) | (1 << (CommonRegexParser.RUC - 70)) | (1 << (CommonRegexParser.SUC - 70)) | (1 << (CommonRegexParser.TUC - 70)) | (1 << (CommonRegexParser.UUC - 70)) | (1 << (CommonRegexParser.VUC - 70)) | (1 << (CommonRegexParser.WUC - 70)) | (1 << (CommonRegexParser.XUC - 70)) | (1 << (CommonRegexParser.YUC - 70)) | (1 << (CommonRegexParser.ZUC - 70)) | (1 << (CommonRegexParser.D1 - 70)) | (1 << (CommonRegexParser.D2 - 70)) | (1 << (CommonRegexParser.D3 - 70)) | (1 << (CommonRegexParser.D4 - 70)) | (1 << (CommonRegexParser.D5 - 70)) | (1 << (CommonRegexParser.D6 - 70)))) !== 0) || ((((_la - 102)) & ~0x1F) === 0 && ((1 << (_la - 102)) & ((1 << (CommonRegexParser.D7 - 102)) | (1 << (CommonRegexParser.D8 - 102)) | (1 << (CommonRegexParser.D9 - 102)) | (1 << (CommonRegexParser.D0 - 102)))) !== 0)) { + { + this.state = 253; + this._errHandler.sync(this); + switch (this._input.LA(1)) { + case CommonRegexParser.ALC: + case CommonRegexParser.BLC: + case CommonRegexParser.CLC: + case CommonRegexParser.DLC: + case CommonRegexParser.ELC: + case CommonRegexParser.FLC: + case CommonRegexParser.GLC: + case CommonRegexParser.HLC: + case CommonRegexParser.ILC: + case CommonRegexParser.JLC: + case CommonRegexParser.KLC: + case CommonRegexParser.LLC: + case CommonRegexParser.MLC: + case CommonRegexParser.NLC: + case CommonRegexParser.OLC: + case CommonRegexParser.PLC: + case CommonRegexParser.QLC: + case CommonRegexParser.RLC: + case CommonRegexParser.SLC: + case CommonRegexParser.TLC: + case CommonRegexParser.ULC: + case CommonRegexParser.VLC: + case CommonRegexParser.WLC: + case CommonRegexParser.XLC: + case CommonRegexParser.YLC: + case CommonRegexParser.ZLC: + case CommonRegexParser.AUC: + case CommonRegexParser.BUC: + case CommonRegexParser.CUC: + case CommonRegexParser.DUC: + case CommonRegexParser.EUC: + case CommonRegexParser.FUC: + case CommonRegexParser.GUC: + case CommonRegexParser.HUC: + case CommonRegexParser.IUC: + case CommonRegexParser.JUC: + case CommonRegexParser.KUC: + case CommonRegexParser.LUC: + case CommonRegexParser.MUC: + case CommonRegexParser.NUC: + case CommonRegexParser.OUC: + case CommonRegexParser.PUC: + case CommonRegexParser.QUC: + case CommonRegexParser.RUC: + case CommonRegexParser.SUC: + case CommonRegexParser.TUC: + case CommonRegexParser.UUC: + case CommonRegexParser.VUC: + case CommonRegexParser.WUC: + case CommonRegexParser.XUC: + case CommonRegexParser.YUC: + case CommonRegexParser.ZUC: + { + this.state = 250; + this.letter(); + } + break; + case CommonRegexParser.Underscore: + { + this.state = 251; + this.match(CommonRegexParser.Underscore); + } + break; + case CommonRegexParser.D1: + case CommonRegexParser.D2: + case CommonRegexParser.D3: + case CommonRegexParser.D4: + case CommonRegexParser.D5: + case CommonRegexParser.D6: + case CommonRegexParser.D7: + case CommonRegexParser.D8: + case CommonRegexParser.D9: + case CommonRegexParser.D0: + { + this.state = 252; + this.digit(); + } + break; + default: + throw new NoViableAltException_1.NoViableAltException(this); + } + } + this.state = 257; + this._errHandler.sync(this); + _la = this._input.LA(1); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + non_close_parens() { + let _localctx = new Non_close_parensContext(this._ctx, this.state); + this.enterRule(_localctx, 48, CommonRegexParser.RULE_non_close_parens); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 259; + this._errHandler.sync(this); + _la = this._input.LA(1); + do { + { + { + this.state = 258; + this.non_close_paren(); + } + } + this.state = 261; + this._errHandler.sync(this); + _la = this._input.LA(1); + } while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CommonRegexParser.Quoted) | (1 << CommonRegexParser.BlockQuoted) | (1 << CommonRegexParser.BellChar) | (1 << CommonRegexParser.ControlChar) | (1 << CommonRegexParser.EscapeChar) | (1 << CommonRegexParser.FormFeed) | (1 << CommonRegexParser.NewLine) | (1 << CommonRegexParser.CarriageReturn) | (1 << CommonRegexParser.Tab) | (1 << CommonRegexParser.Backslash) | (1 << CommonRegexParser.HexChar) | (1 << CommonRegexParser.Dot) | (1 << CommonRegexParser.DecimalDigit) | (1 << CommonRegexParser.NotDecimalDigit) | (1 << CommonRegexParser.CharWithProperty) | (1 << CommonRegexParser.CharWithoutProperty) | (1 << CommonRegexParser.WhiteSpace) | (1 << CommonRegexParser.NotWhiteSpace) | (1 << CommonRegexParser.WordChar) | (1 << CommonRegexParser.NotWordChar) | (1 << CommonRegexParser.CharacterClassStart) | (1 << CommonRegexParser.CharacterClassEnd) | (1 << CommonRegexParser.Caret) | (1 << CommonRegexParser.Hyphen) | (1 << CommonRegexParser.QuestionMark) | (1 << CommonRegexParser.Plus) | (1 << CommonRegexParser.Star) | (1 << CommonRegexParser.OpenBrace) | (1 << CommonRegexParser.CloseBrace) | (1 << CommonRegexParser.Comma) | (1 << CommonRegexParser.EndOfSubject))) !== 0) || ((((_la - 32)) & ~0x1F) === 0 && ((1 << (_la - 32)) & ((1 << (CommonRegexParser.Pipe - 32)) | (1 << (CommonRegexParser.OpenParen - 32)) | (1 << (CommonRegexParser.LessThan - 32)) | (1 << (CommonRegexParser.GreaterThan - 32)) | (1 << (CommonRegexParser.SingleQuote - 32)) | (1 << (CommonRegexParser.Underscore - 32)) | (1 << (CommonRegexParser.Colon - 32)) | (1 << (CommonRegexParser.Hash - 32)) | (1 << (CommonRegexParser.Equals - 32)) | (1 << (CommonRegexParser.Exclamation - 32)) | (1 << (CommonRegexParser.Ampersand - 32)) | (1 << (CommonRegexParser.ALC - 32)) | (1 << (CommonRegexParser.BLC - 32)) | (1 << (CommonRegexParser.CLC - 32)) | (1 << (CommonRegexParser.DLC - 32)) | (1 << (CommonRegexParser.ELC - 32)) | (1 << (CommonRegexParser.FLC - 32)) | (1 << (CommonRegexParser.GLC - 32)) | (1 << (CommonRegexParser.HLC - 32)) | (1 << (CommonRegexParser.ILC - 32)) | (1 << (CommonRegexParser.JLC - 32)) | (1 << (CommonRegexParser.KLC - 32)) | (1 << (CommonRegexParser.LLC - 32)) | (1 << (CommonRegexParser.MLC - 32)) | (1 << (CommonRegexParser.NLC - 32)) | (1 << (CommonRegexParser.OLC - 32)) | (1 << (CommonRegexParser.PLC - 32)) | (1 << (CommonRegexParser.QLC - 32)) | (1 << (CommonRegexParser.RLC - 32)) | (1 << (CommonRegexParser.SLC - 32)) | (1 << (CommonRegexParser.TLC - 32)))) !== 0) || ((((_la - 64)) & ~0x1F) === 0 && ((1 << (_la - 64)) & ((1 << (CommonRegexParser.ULC - 64)) | (1 << (CommonRegexParser.VLC - 64)) | (1 << (CommonRegexParser.WLC - 64)) | (1 << (CommonRegexParser.XLC - 64)) | (1 << (CommonRegexParser.YLC - 64)) | (1 << (CommonRegexParser.ZLC - 64)) | (1 << (CommonRegexParser.AUC - 64)) | (1 << (CommonRegexParser.BUC - 64)) | (1 << (CommonRegexParser.CUC - 64)) | (1 << (CommonRegexParser.DUC - 64)) | (1 << (CommonRegexParser.EUC - 64)) | (1 << (CommonRegexParser.FUC - 64)) | (1 << (CommonRegexParser.GUC - 64)) | (1 << (CommonRegexParser.HUC - 64)) | (1 << (CommonRegexParser.IUC - 64)) | (1 << (CommonRegexParser.JUC - 64)) | (1 << (CommonRegexParser.KUC - 64)) | (1 << (CommonRegexParser.LUC - 64)) | (1 << (CommonRegexParser.MUC - 64)) | (1 << (CommonRegexParser.NUC - 64)) | (1 << (CommonRegexParser.OUC - 64)) | (1 << (CommonRegexParser.PUC - 64)) | (1 << (CommonRegexParser.QUC - 64)) | (1 << (CommonRegexParser.RUC - 64)) | (1 << (CommonRegexParser.SUC - 64)) | (1 << (CommonRegexParser.TUC - 64)) | (1 << (CommonRegexParser.UUC - 64)) | (1 << (CommonRegexParser.VUC - 64)) | (1 << (CommonRegexParser.WUC - 64)) | (1 << (CommonRegexParser.XUC - 64)) | (1 << (CommonRegexParser.YUC - 64)) | (1 << (CommonRegexParser.ZUC - 64)))) !== 0) || ((((_la - 96)) & ~0x1F) === 0 && ((1 << (_la - 96)) & ((1 << (CommonRegexParser.D1 - 96)) | (1 << (CommonRegexParser.D2 - 96)) | (1 << (CommonRegexParser.D3 - 96)) | (1 << (CommonRegexParser.D4 - 96)) | (1 << (CommonRegexParser.D5 - 96)) | (1 << (CommonRegexParser.D6 - 96)) | (1 << (CommonRegexParser.D7 - 96)) | (1 << (CommonRegexParser.D8 - 96)) | (1 << (CommonRegexParser.D9 - 96)) | (1 << (CommonRegexParser.D0 - 96)) | (1 << (CommonRegexParser.OtherChar - 96)))) !== 0)); + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + non_close_paren() { + let _localctx = new Non_close_parenContext(this._ctx, this.state); + this.enterRule(_localctx, 50, CommonRegexParser.RULE_non_close_paren); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 263; + _la = this._input.LA(1); + if (_la <= 0 || (_la === CommonRegexParser.CloseParen)) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + // @RuleVersion(0) + letter() { + let _localctx = new LetterContext(this._ctx, this.state); + this.enterRule(_localctx, 52, CommonRegexParser.RULE_letter); + let _la; + try { + this.enterOuterAlt(_localctx, 1); + { + this.state = 265; + _la = this._input.LA(1); + if (!(((((_la - 44)) & ~0x1F) === 0 && ((1 << (_la - 44)) & ((1 << (CommonRegexParser.ALC - 44)) | (1 << (CommonRegexParser.BLC - 44)) | (1 << (CommonRegexParser.CLC - 44)) | (1 << (CommonRegexParser.DLC - 44)) | (1 << (CommonRegexParser.ELC - 44)) | (1 << (CommonRegexParser.FLC - 44)) | (1 << (CommonRegexParser.GLC - 44)) | (1 << (CommonRegexParser.HLC - 44)) | (1 << (CommonRegexParser.ILC - 44)) | (1 << (CommonRegexParser.JLC - 44)) | (1 << (CommonRegexParser.KLC - 44)) | (1 << (CommonRegexParser.LLC - 44)) | (1 << (CommonRegexParser.MLC - 44)) | (1 << (CommonRegexParser.NLC - 44)) | (1 << (CommonRegexParser.OLC - 44)) | (1 << (CommonRegexParser.PLC - 44)) | (1 << (CommonRegexParser.QLC - 44)) | (1 << (CommonRegexParser.RLC - 44)) | (1 << (CommonRegexParser.SLC - 44)) | (1 << (CommonRegexParser.TLC - 44)) | (1 << (CommonRegexParser.ULC - 44)) | (1 << (CommonRegexParser.VLC - 44)) | (1 << (CommonRegexParser.WLC - 44)) | (1 << (CommonRegexParser.XLC - 44)) | (1 << (CommonRegexParser.YLC - 44)) | (1 << (CommonRegexParser.ZLC - 44)) | (1 << (CommonRegexParser.AUC - 44)) | (1 << (CommonRegexParser.BUC - 44)) | (1 << (CommonRegexParser.CUC - 44)) | (1 << (CommonRegexParser.DUC - 44)) | (1 << (CommonRegexParser.EUC - 44)) | (1 << (CommonRegexParser.FUC - 44)))) !== 0) || ((((_la - 76)) & ~0x1F) === 0 && ((1 << (_la - 76)) & ((1 << (CommonRegexParser.GUC - 76)) | (1 << (CommonRegexParser.HUC - 76)) | (1 << (CommonRegexParser.IUC - 76)) | (1 << (CommonRegexParser.JUC - 76)) | (1 << (CommonRegexParser.KUC - 76)) | (1 << (CommonRegexParser.LUC - 76)) | (1 << (CommonRegexParser.MUC - 76)) | (1 << (CommonRegexParser.NUC - 76)) | (1 << (CommonRegexParser.OUC - 76)) | (1 << (CommonRegexParser.PUC - 76)) | (1 << (CommonRegexParser.QUC - 76)) | (1 << (CommonRegexParser.RUC - 76)) | (1 << (CommonRegexParser.SUC - 76)) | (1 << (CommonRegexParser.TUC - 76)) | (1 << (CommonRegexParser.UUC - 76)) | (1 << (CommonRegexParser.VUC - 76)) | (1 << (CommonRegexParser.WUC - 76)) | (1 << (CommonRegexParser.XUC - 76)) | (1 << (CommonRegexParser.YUC - 76)) | (1 << (CommonRegexParser.ZUC - 76)))) !== 0))) { + this._errHandler.recoverInline(this); + } + else { + if (this._input.LA(1) === Token_1.Token.EOF) { + this.matchedEOF = true; + } + this._errHandler.reportMatch(this); + this.consume(); + } + } + } + catch (re) { + if (re instanceof RecognitionException_1.RecognitionException) { + _localctx.exception = re; + this._errHandler.reportError(this, re); + this._errHandler.recover(this, re); + } + else { + throw re; + } + } + finally { + this.exitRule(); + } + return _localctx; + } + static get _ATN() { + if (!CommonRegexParser.__ATN) { + CommonRegexParser.__ATN = new ATNDeserializer_1.ATNDeserializer().deserialize(Utils.toCharArray(CommonRegexParser._serializedATN)); + } + return CommonRegexParser.__ATN; + } + }; + CommonRegexParser.CommonRegexParser = CommonRegexParser$1; + CommonRegexParser$1.Quoted = 1; + CommonRegexParser$1.BlockQuoted = 2; + CommonRegexParser$1.BellChar = 3; + CommonRegexParser$1.ControlChar = 4; + CommonRegexParser$1.EscapeChar = 5; + CommonRegexParser$1.FormFeed = 6; + CommonRegexParser$1.NewLine = 7; + CommonRegexParser$1.CarriageReturn = 8; + CommonRegexParser$1.Tab = 9; + CommonRegexParser$1.Backslash = 10; + CommonRegexParser$1.HexChar = 11; + CommonRegexParser$1.Dot = 12; + CommonRegexParser$1.DecimalDigit = 13; + CommonRegexParser$1.NotDecimalDigit = 14; + CommonRegexParser$1.CharWithProperty = 15; + CommonRegexParser$1.CharWithoutProperty = 16; + CommonRegexParser$1.WhiteSpace = 17; + CommonRegexParser$1.NotWhiteSpace = 18; + CommonRegexParser$1.WordChar = 19; + CommonRegexParser$1.NotWordChar = 20; + CommonRegexParser$1.CharacterClassStart = 21; + CommonRegexParser$1.CharacterClassEnd = 22; + CommonRegexParser$1.Caret = 23; + CommonRegexParser$1.Hyphen = 24; + CommonRegexParser$1.QuestionMark = 25; + CommonRegexParser$1.Plus = 26; + CommonRegexParser$1.Star = 27; + CommonRegexParser$1.OpenBrace = 28; + CommonRegexParser$1.CloseBrace = 29; + CommonRegexParser$1.Comma = 30; + CommonRegexParser$1.EndOfSubject = 31; + CommonRegexParser$1.Pipe = 32; + CommonRegexParser$1.OpenParen = 33; + CommonRegexParser$1.CloseParen = 34; + CommonRegexParser$1.LessThan = 35; + CommonRegexParser$1.GreaterThan = 36; + CommonRegexParser$1.SingleQuote = 37; + CommonRegexParser$1.Underscore = 38; + CommonRegexParser$1.Colon = 39; + CommonRegexParser$1.Hash = 40; + CommonRegexParser$1.Equals = 41; + CommonRegexParser$1.Exclamation = 42; + CommonRegexParser$1.Ampersand = 43; + CommonRegexParser$1.ALC = 44; + CommonRegexParser$1.BLC = 45; + CommonRegexParser$1.CLC = 46; + CommonRegexParser$1.DLC = 47; + CommonRegexParser$1.ELC = 48; + CommonRegexParser$1.FLC = 49; + CommonRegexParser$1.GLC = 50; + CommonRegexParser$1.HLC = 51; + CommonRegexParser$1.ILC = 52; + CommonRegexParser$1.JLC = 53; + CommonRegexParser$1.KLC = 54; + CommonRegexParser$1.LLC = 55; + CommonRegexParser$1.MLC = 56; + CommonRegexParser$1.NLC = 57; + CommonRegexParser$1.OLC = 58; + CommonRegexParser$1.PLC = 59; + CommonRegexParser$1.QLC = 60; + CommonRegexParser$1.RLC = 61; + CommonRegexParser$1.SLC = 62; + CommonRegexParser$1.TLC = 63; + CommonRegexParser$1.ULC = 64; + CommonRegexParser$1.VLC = 65; + CommonRegexParser$1.WLC = 66; + CommonRegexParser$1.XLC = 67; + CommonRegexParser$1.YLC = 68; + CommonRegexParser$1.ZLC = 69; + CommonRegexParser$1.AUC = 70; + CommonRegexParser$1.BUC = 71; + CommonRegexParser$1.CUC = 72; + CommonRegexParser$1.DUC = 73; + CommonRegexParser$1.EUC = 74; + CommonRegexParser$1.FUC = 75; + CommonRegexParser$1.GUC = 76; + CommonRegexParser$1.HUC = 77; + CommonRegexParser$1.IUC = 78; + CommonRegexParser$1.JUC = 79; + CommonRegexParser$1.KUC = 80; + CommonRegexParser$1.LUC = 81; + CommonRegexParser$1.MUC = 82; + CommonRegexParser$1.NUC = 83; + CommonRegexParser$1.OUC = 84; + CommonRegexParser$1.PUC = 85; + CommonRegexParser$1.QUC = 86; + CommonRegexParser$1.RUC = 87; + CommonRegexParser$1.SUC = 88; + CommonRegexParser$1.TUC = 89; + CommonRegexParser$1.UUC = 90; + CommonRegexParser$1.VUC = 91; + CommonRegexParser$1.WUC = 92; + CommonRegexParser$1.XUC = 93; + CommonRegexParser$1.YUC = 94; + CommonRegexParser$1.ZUC = 95; + CommonRegexParser$1.D1 = 96; + CommonRegexParser$1.D2 = 97; + CommonRegexParser$1.D3 = 98; + CommonRegexParser$1.D4 = 99; + CommonRegexParser$1.D5 = 100; + CommonRegexParser$1.D6 = 101; + CommonRegexParser$1.D7 = 102; + CommonRegexParser$1.D8 = 103; + CommonRegexParser$1.D9 = 104; + CommonRegexParser$1.D0 = 105; + CommonRegexParser$1.OtherChar = 106; + CommonRegexParser$1.RULE_parse = 0; + CommonRegexParser$1.RULE_alternation = 1; + CommonRegexParser$1.RULE_expr = 2; + CommonRegexParser$1.RULE_element = 3; + CommonRegexParser$1.RULE_quantifier = 4; + CommonRegexParser$1.RULE_quantifier_type = 5; + CommonRegexParser$1.RULE_character_class = 6; + CommonRegexParser$1.RULE_capture = 7; + CommonRegexParser$1.RULE_non_capture = 8; + CommonRegexParser$1.RULE_option = 9; + CommonRegexParser$1.RULE_option_flag = 10; + CommonRegexParser$1.RULE_atom = 11; + CommonRegexParser$1.RULE_cc_atom = 12; + CommonRegexParser$1.RULE_shared_atom = 13; + CommonRegexParser$1.RULE_literal = 14; + CommonRegexParser$1.RULE_cc_literal = 15; + CommonRegexParser$1.RULE_shared_literal = 16; + CommonRegexParser$1.RULE_number = 17; + CommonRegexParser$1.RULE_octal_char = 18; + CommonRegexParser$1.RULE_octal_digit = 19; + CommonRegexParser$1.RULE_digits = 20; + CommonRegexParser$1.RULE_digit = 21; + CommonRegexParser$1.RULE_name = 22; + CommonRegexParser$1.RULE_alpha_nums = 23; + CommonRegexParser$1.RULE_non_close_parens = 24; + CommonRegexParser$1.RULE_non_close_paren = 25; + CommonRegexParser$1.RULE_letter = 26; + // tslint:disable:no-trailing-whitespace + CommonRegexParser$1.ruleNames = [ + "parse", "alternation", "expr", "element", "quantifier", "quantifier_type", + "character_class", "capture", "non_capture", "option", "option_flag", + "atom", "cc_atom", "shared_atom", "literal", "cc_literal", "shared_literal", + "number", "octal_char", "octal_digit", "digits", "digit", "name", "alpha_nums", + "non_close_parens", "non_close_paren", "letter", + ]; + CommonRegexParser$1._LITERAL_NAMES = [ + undefined, undefined, undefined, "'\\'", "'\\'", "'\\'", "'\\'", "'\\'", + "'\\'", "'\\'", "'\\'", undefined, "'.'", "'\\'", "'\\'", undefined, undefined, + "'\\'", "'\\'", "'\\'", "'\\'", "'['", "']'", "'^'", "'-'", "'?'", "'+'", + "'*'", "'{'", "'}'", "','", "'$'", "'|'", "'('", "')'", "'<'", "'>'", + "'''", "'_'", "':'", "'#'", "'='", "'!'", "'&'", "'a'", "'b'", "'c'", + "'d'", "'e'", "'f'", "'g'", "'h'", "'i'", "'j'", "'k'", "'l'", "'m'", + "'n'", "'o'", "'p'", "'q'", "'r'", "'s'", "'t'", "'u'", "'v'", "'w'", + "'x'", "'y'", "'z'", "'A'", "'B'", "'C'", "'D'", "'E'", "'F'", "'G'", + "'H'", "'I'", "'J'", "'K'", "'L'", "'M'", "'N'", "'O'", "'P'", "'Q'", + "'R'", "'S'", "'T'", "'U'", "'V'", "'W'", "'X'", "'Y'", "'Z'", "'1'", + "'2'", "'3'", "'4'", "'5'", "'6'", "'7'", "'8'", "'9'", "'0'", + ]; + CommonRegexParser$1._SYMBOLIC_NAMES = [ + undefined, "Quoted", "BlockQuoted", "BellChar", "ControlChar", "EscapeChar", + "FormFeed", "NewLine", "CarriageReturn", "Tab", "Backslash", "HexChar", + "Dot", "DecimalDigit", "NotDecimalDigit", "CharWithProperty", "CharWithoutProperty", + "WhiteSpace", "NotWhiteSpace", "WordChar", "NotWordChar", "CharacterClassStart", + "CharacterClassEnd", "Caret", "Hyphen", "QuestionMark", "Plus", "Star", + "OpenBrace", "CloseBrace", "Comma", "EndOfSubject", "Pipe", "OpenParen", + "CloseParen", "LessThan", "GreaterThan", "SingleQuote", "Underscore", + "Colon", "Hash", "Equals", "Exclamation", "Ampersand", "ALC", "BLC", "CLC", + "DLC", "ELC", "FLC", "GLC", "HLC", "ILC", "JLC", "KLC", "LLC", "MLC", + "NLC", "OLC", "PLC", "QLC", "RLC", "SLC", "TLC", "ULC", "VLC", "WLC", + "XLC", "YLC", "ZLC", "AUC", "BUC", "CUC", "DUC", "EUC", "FUC", "GUC", + "HUC", "IUC", "JUC", "KUC", "LUC", "MUC", "NUC", "OUC", "PUC", "QUC", + "RUC", "SUC", "TUC", "UUC", "VUC", "WUC", "XUC", "YUC", "ZUC", "D1", "D2", + "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D0", "OtherChar", + ]; + CommonRegexParser$1.VOCABULARY = new VocabularyImpl_1.VocabularyImpl(CommonRegexParser$1._LITERAL_NAMES, CommonRegexParser$1._SYMBOLIC_NAMES, []); + CommonRegexParser$1._serializedATN = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03l\u010E\x04\x02" + + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + + "\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r\x04" + + "\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12\x04" + + "\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t\x17\x04" + + "\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t\x1C\x03" + + "\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x07\x03?\n\x03\f\x03\x0E" + + "\x03B\v\x03\x03\x04\x07\x04E\n\x04\f\x04\x0E\x04H\v\x04\x03\x05\x03\x05" + + "\x05\x05L\n\x05\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06" + + "\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06" + + "\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x03\x06\x05\x06" + + "f\n\x06\x03\x07\x03\x07\x03\x07\x05\x07k\n\x07\x03\b\x03\b\x03\b\x06\b" + + "p\n\b\r\b\x0E\bq\x03\b\x03\b\x03\b\x03\b\x06\bx\n\b\r\b\x0E\by\x03\b\x03" + + "\b\x05\b~\n\b\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03" + + "\t\x03\t\x03\t\x05\t\x8C\n\t\x03\n\x03\n\x03\n\x03\n\x03\n\x03\n\x03\v" + + "\x03\v\x03\v\x06\v\x97\n\v\r\v\x0E\v\x98\x03\v\x03\v\x03\f\x03\f\x03\r" + + "\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03\r\x05\r\xA8\n\r\x03\x0E" + + "\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x05\x0E\xB0\n\x0E\x03\x0F\x03" + + "\x0F\x03\x10\x03\x10\x05\x10\xB6\n\x10\x03\x11\x03\x11\x03\x11\x03\x11" + + "\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x05\x11\xC3\n" + + "\x11\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03" + + "\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03" + + "\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x05" + + "\x12\xDF\n\x12\x03\x13\x03\x13\x03\x14\x03\x14\x03\x14\x03\x14\x03\x14" + + "\x03\x14\x03\x14\x03\x14\x03\x14\x05\x14\xEC\n\x14\x03\x15\x03\x15\x03" + + "\x16\x06\x16\xF1\n\x16\r\x16\x0E\x16\xF2\x03\x17\x03\x17\x03\x18\x03\x18" + + "\x03\x19\x03\x19\x05\x19\xFB\n\x19\x03\x19\x03\x19\x03\x19\x07\x19\u0100" + + "\n\x19\f\x19\x0E\x19\u0103\v\x19\x03\x1A\x06\x1A\u0106\n\x1A\r\x1A\x0E" + + "\x1A\u0107\x03\x1B\x03\x1B\x03\x1C\x03\x1C\x03\x1C\x02\x02\x02\x1D\x02" + + "\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12\x02\x14\x02" + + "\x16\x02\x18\x02\x1A\x02\x1C\x02\x1E\x02 \x02\"\x02$\x02&\x02(\x02*\x02" + + ",\x02.\x020\x022\x024\x026\x02\x02\t\x05\x0266::@@\x04\x02\x06\x06\x0F" + + "\x16\x04\x02bdkk\x04\x02bhkk\x03\x02bk\x03\x02$$\x03\x02.a\x02\u0136\x02" + + "8\x03\x02\x02\x02\x04;\x03\x02\x02\x02\x06F\x03\x02\x02\x02\bI\x03\x02" + + "\x02\x02\ne\x03\x02\x02\x02\fj\x03\x02\x02\x02\x0E}\x03\x02\x02\x02\x10" + + "\x8B\x03\x02\x02\x02\x12\x8D\x03\x02\x02\x02\x14\x93\x03\x02\x02\x02\x16" + + "\x9C\x03\x02\x02\x02\x18\xA7\x03\x02\x02\x02\x1A\xAF\x03\x02\x02\x02\x1C" + + "\xB1\x03\x02\x02\x02\x1E\xB5\x03\x02\x02\x02 \xC2\x03\x02\x02\x02\"\xDE" + + "\x03\x02\x02\x02$\xE0\x03\x02\x02\x02&\xEB\x03\x02\x02\x02(\xED\x03\x02" + + "\x02\x02*\xF0\x03\x02\x02\x02,\xF4\x03\x02\x02\x02.\xF6\x03\x02\x02\x02" + + "0\xFA\x03\x02\x02\x022\u0105\x03\x02\x02\x024\u0109\x03\x02\x02\x026\u010B" + + "\x03\x02\x02\x0289\x05\x04\x03\x029:\x07\x02\x02\x03:\x03\x03\x02\x02" + + "\x02;@\x05\x06\x04\x02<=\x07\"\x02\x02=?\x05\x06\x04\x02><\x03\x02\x02" + + "\x02?B\x03\x02\x02\x02@>\x03\x02\x02\x02@A\x03\x02\x02\x02A\x05\x03\x02" + + "\x02\x02B@\x03\x02\x02\x02CE\x05\b\x05\x02DC\x03\x02\x02\x02EH\x03\x02" + + "\x02\x02FD\x03\x02\x02\x02FG\x03\x02\x02\x02G\x07\x03\x02\x02\x02HF\x03" + + "\x02\x02\x02IK\x05\x18\r\x02JL\x05\n\x06\x02KJ\x03\x02\x02\x02KL\x03\x02" + + "\x02\x02L\t\x03\x02\x02\x02MN\x07\x1B\x02\x02Nf\x05\f\x07\x02OP\x07\x1C" + + "\x02\x02Pf\x05\f\x07\x02QR\x07\x1D\x02\x02Rf\x05\f\x07\x02ST\x07\x1E\x02" + + "\x02TU\x05$\x13\x02UV\x07\x1F\x02\x02VW\x05\f\x07\x02Wf\x03\x02\x02\x02" + + "XY\x07\x1E\x02\x02YZ\x05$\x13\x02Z[\x07 \x02\x02[\\\x07\x1F\x02\x02\\" + + "]\x05\f\x07\x02]f\x03\x02\x02\x02^_\x07\x1E\x02\x02_`\x05$\x13\x02`a\x07" + + " \x02\x02ab\x05$\x13\x02bc\x07\x1F\x02\x02cd\x05\f\x07\x02df\x03\x02\x02" + + "\x02eM\x03\x02\x02\x02eO\x03\x02\x02\x02eQ\x03\x02\x02\x02eS\x03\x02\x02" + + "\x02eX\x03\x02\x02\x02e^\x03\x02\x02\x02f\v\x03\x02\x02\x02gk\x07\x1C" + + "\x02\x02hk\x07\x1B\x02\x02ik\x03\x02\x02\x02jg\x03\x02\x02\x02jh\x03\x02" + + "\x02\x02ji\x03\x02\x02\x02k\r\x03\x02\x02\x02lm\x07\x17\x02\x02mo\x07" + + "\x19\x02\x02np\x05\x1A\x0E\x02on\x03\x02\x02\x02pq\x03\x02\x02\x02qo\x03" + + "\x02\x02\x02qr\x03\x02\x02\x02rs\x03\x02\x02\x02st\x07\x18\x02\x02t~\x03" + + "\x02\x02\x02uw\x07\x17\x02\x02vx\x05\x1A\x0E\x02wv\x03\x02\x02\x02xy\x03" + + "\x02\x02\x02yw\x03\x02\x02\x02yz\x03\x02\x02\x02z{\x03\x02\x02\x02{|\x07" + + "\x18\x02\x02|~\x03\x02\x02\x02}l\x03\x02\x02\x02}u\x03\x02\x02\x02~\x0F" + + "\x03\x02\x02\x02\x7F\x80\x07#\x02\x02\x80\x81\x07\x1B\x02\x02\x81\x82" + + "\x07%\x02\x02\x82\x83\x05.\x18\x02\x83\x84\x07&\x02\x02\x84\x85\x05\x04" + + "\x03\x02\x85\x86\x07$\x02\x02\x86\x8C\x03\x02\x02\x02\x87\x88\x07#\x02" + + "\x02\x88\x89\x05\x04\x03\x02\x89\x8A\x07$\x02\x02\x8A\x8C\x03\x02\x02" + + "\x02\x8B\x7F\x03\x02\x02\x02\x8B\x87\x03\x02\x02\x02\x8C\x11\x03\x02\x02" + + "\x02\x8D\x8E\x07#\x02\x02\x8E\x8F\x07\x1B\x02\x02\x8F\x90\x07)\x02\x02" + + "\x90\x91\x05\x04\x03\x02\x91\x92\x07$\x02\x02\x92\x13\x03\x02\x02\x02" + + "\x93\x94\x07#\x02\x02\x94\x96\x07\x1B\x02\x02\x95\x97\x05\x16\f\x02\x96" + + "\x95\x03\x02\x02\x02\x97\x98\x03\x02\x02\x02\x98\x96\x03\x02\x02\x02\x98" + + "\x99\x03\x02\x02\x02\x99\x9A\x03\x02\x02\x02\x9A\x9B\x07$\x02\x02\x9B" + + "\x15\x03\x02\x02\x02\x9C\x9D\t\x02\x02\x02\x9D\x17\x03\x02\x02\x02\x9E" + + "\xA8\x05\x1C\x0F\x02\x9F\xA8\x05\x1E\x10\x02\xA0\xA8\x05\x0E\b\x02\xA1" + + "\xA8\x05\x10\t\x02\xA2\xA8\x05\x12\n\x02\xA3\xA8\x05\x14\v\x02\xA4\xA8" + + "\x07\x0E\x02\x02\xA5\xA8\x07\x19\x02\x02\xA6\xA8\x07!\x02\x02\xA7\x9E" + + "\x03\x02\x02\x02\xA7\x9F\x03\x02\x02\x02\xA7\xA0\x03\x02\x02\x02\xA7\xA1" + + "\x03\x02\x02\x02\xA7\xA2\x03\x02\x02\x02\xA7\xA3\x03\x02\x02\x02\xA7\xA4" + + "\x03\x02\x02\x02\xA7\xA5\x03\x02\x02\x02\xA7\xA6\x03\x02\x02\x02\xA8\x19" + + "\x03\x02\x02\x02\xA9\xAA\x05 \x11\x02\xAA\xAB\x07\x1A\x02\x02\xAB\xAC" + + "\x05 \x11\x02\xAC\xB0\x03\x02\x02\x02\xAD\xB0\x05\x1C\x0F\x02\xAE\xB0" + + "\x05 \x11\x02\xAF\xA9\x03\x02\x02\x02\xAF\xAD\x03\x02\x02\x02\xAF\xAE" + + "\x03\x02\x02\x02\xB0\x1B\x03\x02\x02\x02\xB1\xB2\t\x03\x02\x02\xB2\x1D" + + "\x03\x02\x02\x02\xB3\xB6\x05\"\x12\x02\xB4\xB6\x07\x18\x02\x02\xB5\xB3" + + "\x03\x02\x02\x02\xB5\xB4\x03\x02\x02\x02\xB6\x1F\x03\x02\x02\x02\xB7\xC3" + + "\x05\"\x12\x02\xB8\xC3\x07\x0E\x02\x02\xB9\xC3\x07\x17\x02\x02\xBA\xC3" + + "\x07\x19\x02\x02\xBB\xC3\x07\x1B\x02\x02\xBC\xC3\x07\x1C\x02\x02\xBD\xC3" + + "\x07\x1D\x02\x02\xBE\xC3\x07!\x02\x02\xBF\xC3\x07\"\x02\x02\xC0\xC3\x07" + + "#\x02\x02\xC1\xC3\x07$\x02\x02\xC2\xB7\x03\x02\x02\x02\xC2\xB8\x03\x02" + + "\x02\x02\xC2\xB9\x03\x02\x02\x02\xC2\xBA\x03\x02\x02\x02\xC2\xBB\x03\x02" + + "\x02\x02\xC2\xBC\x03\x02\x02\x02\xC2\xBD\x03\x02\x02\x02\xC2\xBE\x03\x02" + + "\x02\x02\xC2\xBF\x03\x02\x02\x02\xC2\xC0\x03\x02\x02\x02\xC2\xC1\x03\x02" + + "\x02\x02\xC3!\x03\x02\x02\x02\xC4\xDF\x05&\x14\x02\xC5\xDF\x056\x1C\x02" + + "\xC6\xDF\x05,\x17\x02\xC7\xDF\x07\x05\x02\x02\xC8\xDF\x07\x07\x02\x02" + + "\xC9\xDF\x07\b\x02\x02\xCA\xDF\x07\t\x02\x02\xCB\xDF\x07\n\x02\x02\xCC" + + "\xDF\x07\v\x02\x02\xCD\xDF\x07\r\x02\x02\xCE\xDF\x07\x03\x02\x02\xCF\xDF" + + "\x07\x04\x02\x02\xD0\xDF\x07\x1E\x02\x02\xD1\xDF\x07\x1F\x02\x02\xD2\xDF" + + "\x07 \x02\x02\xD3\xDF\x07\x1A\x02\x02\xD4\xDF\x07%\x02\x02\xD5\xDF\x07" + + "&\x02\x02\xD6\xDF\x07\'\x02\x02\xD7\xDF\x07(\x02\x02\xD8\xDF\x07)\x02" + + "\x02\xD9\xDF\x07*\x02\x02\xDA\xDF\x07+\x02\x02\xDB\xDF\x07,\x02\x02\xDC" + + "\xDF\x07-\x02\x02\xDD\xDF\x07l\x02\x02\xDE\xC4\x03\x02\x02\x02\xDE\xC5" + + "\x03\x02\x02\x02\xDE\xC6\x03\x02\x02\x02\xDE\xC7\x03\x02\x02\x02\xDE\xC8" + + "\x03\x02\x02\x02\xDE\xC9\x03\x02\x02\x02\xDE\xCA\x03\x02\x02\x02\xDE\xCB" + + "\x03\x02\x02\x02\xDE\xCC\x03\x02\x02\x02\xDE\xCD\x03\x02\x02\x02\xDE\xCE" + + "\x03\x02\x02\x02\xDE\xCF\x03\x02\x02\x02\xDE\xD0\x03\x02\x02\x02\xDE\xD1" + + "\x03\x02\x02\x02\xDE\xD2\x03\x02\x02\x02\xDE\xD3\x03\x02\x02\x02\xDE\xD4" + + "\x03\x02\x02\x02\xDE\xD5\x03\x02\x02\x02\xDE\xD6\x03\x02\x02\x02\xDE\xD7" + + "\x03\x02\x02\x02\xDE\xD8\x03\x02\x02\x02\xDE\xD9\x03\x02\x02\x02\xDE\xDA" + + "\x03\x02\x02\x02\xDE\xDB\x03\x02\x02\x02\xDE\xDC\x03\x02\x02\x02\xDE\xDD" + + "\x03\x02\x02\x02\xDF#\x03\x02\x02\x02\xE0\xE1\x05*\x16\x02\xE1%\x03\x02" + + "\x02\x02\xE2\xE3\x07\f\x02\x02\xE3\xE4\t\x04\x02\x02\xE4\xE5\x05(\x15" + + "\x02\xE5\xE6\x05(\x15\x02\xE6\xEC\x03\x02\x02\x02\xE7\xE8\x07\f\x02\x02" + + "\xE8\xE9\x05(\x15\x02\xE9\xEA\x05(\x15\x02\xEA\xEC\x03\x02\x02\x02\xEB" + + "\xE2\x03\x02\x02\x02\xEB\xE7\x03\x02\x02\x02\xEC\'\x03\x02\x02\x02\xED" + + "\xEE\t\x05\x02\x02\xEE)\x03\x02\x02\x02\xEF\xF1\x05,\x17\x02\xF0\xEF\x03" + + "\x02\x02\x02\xF1\xF2\x03\x02\x02\x02\xF2\xF0\x03\x02\x02\x02\xF2\xF3\x03" + + "\x02\x02\x02\xF3+\x03\x02\x02\x02\xF4\xF5\t\x06\x02\x02\xF5-\x03\x02\x02" + + "\x02\xF6\xF7\x050\x19\x02\xF7/\x03\x02\x02\x02\xF8\xFB\x056\x1C\x02\xF9" + + "\xFB\x07(\x02\x02\xFA\xF8\x03\x02\x02\x02\xFA\xF9\x03\x02\x02\x02\xFB" + + "\u0101\x03\x02\x02\x02\xFC\u0100\x056\x1C\x02\xFD\u0100\x07(\x02\x02\xFE" + + "\u0100\x05,\x17\x02\xFF\xFC\x03\x02\x02\x02\xFF\xFD\x03\x02\x02\x02\xFF" + + "\xFE\x03\x02\x02\x02\u0100\u0103\x03\x02\x02\x02\u0101\xFF\x03\x02\x02" + + "\x02\u0101\u0102\x03\x02\x02\x02\u01021\x03\x02\x02\x02\u0103\u0101\x03" + + "\x02\x02\x02\u0104\u0106\x054\x1B\x02\u0105\u0104\x03\x02\x02\x02\u0106" + + "\u0107\x03\x02\x02\x02\u0107\u0105\x03\x02\x02\x02\u0107\u0108\x03\x02" + + "\x02\x02\u01083\x03\x02\x02\x02\u0109\u010A\n\x07\x02\x02\u010A5\x03\x02" + + "\x02\x02\u010B\u010C\t\b\x02\x02\u010C7\x03\x02\x02\x02\x17@FKejqy}\x8B" + + "\x98\xA7\xAF\xB5\xC2\xDE\xEB\xF2\xFA\xFF\u0101\u0107"; + class ParseContext extends ParserRuleContext_1.ParserRuleContext { + alternation() { + return this.getRuleContext(0, AlternationContext); + } + EOF() { return this.getToken(CommonRegexParser$1.EOF, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_parse; } + // @Override + enterRule(listener) { + if (listener.enterParse) { + listener.enterParse(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitParse) { + listener.exitParse(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitParse) { + return visitor.visitParse(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.ParseContext = ParseContext; + class AlternationContext extends ParserRuleContext_1.ParserRuleContext { + expr(i) { + if (i === undefined) { + return this.getRuleContexts(ExprContext); + } + else { + return this.getRuleContext(i, ExprContext); + } + } + Pipe(i) { + if (i === undefined) { + return this.getTokens(CommonRegexParser$1.Pipe); + } + else { + return this.getToken(CommonRegexParser$1.Pipe, i); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_alternation; } + // @Override + enterRule(listener) { + if (listener.enterAlternation) { + listener.enterAlternation(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitAlternation) { + listener.exitAlternation(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitAlternation) { + return visitor.visitAlternation(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.AlternationContext = AlternationContext; + class ExprContext extends ParserRuleContext_1.ParserRuleContext { + element(i) { + if (i === undefined) { + return this.getRuleContexts(ElementContext); + } + else { + return this.getRuleContext(i, ElementContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_expr; } + // @Override + enterRule(listener) { + if (listener.enterExpr) { + listener.enterExpr(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitExpr) { + listener.exitExpr(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitExpr) { + return visitor.visitExpr(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.ExprContext = ExprContext; + class ElementContext extends ParserRuleContext_1.ParserRuleContext { + atom() { + return this.getRuleContext(0, AtomContext); + } + quantifier() { + return this.tryGetRuleContext(0, QuantifierContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_element; } + // @Override + enterRule(listener) { + if (listener.enterElement) { + listener.enterElement(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitElement) { + listener.exitElement(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitElement) { + return visitor.visitElement(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.ElementContext = ElementContext; + class QuantifierContext extends ParserRuleContext_1.ParserRuleContext { + QuestionMark() { return this.tryGetToken(CommonRegexParser$1.QuestionMark, 0); } + quantifier_type() { + return this.getRuleContext(0, Quantifier_typeContext); + } + Plus() { return this.tryGetToken(CommonRegexParser$1.Plus, 0); } + Star() { return this.tryGetToken(CommonRegexParser$1.Star, 0); } + OpenBrace() { return this.tryGetToken(CommonRegexParser$1.OpenBrace, 0); } + number(i) { + if (i === undefined) { + return this.getRuleContexts(NumberContext); + } + else { + return this.getRuleContext(i, NumberContext); + } + } + CloseBrace() { return this.tryGetToken(CommonRegexParser$1.CloseBrace, 0); } + Comma() { return this.tryGetToken(CommonRegexParser$1.Comma, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_quantifier; } + // @Override + enterRule(listener) { + if (listener.enterQuantifier) { + listener.enterQuantifier(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitQuantifier) { + listener.exitQuantifier(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitQuantifier) { + return visitor.visitQuantifier(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.QuantifierContext = QuantifierContext; + class Quantifier_typeContext extends ParserRuleContext_1.ParserRuleContext { + Plus() { return this.tryGetToken(CommonRegexParser$1.Plus, 0); } + QuestionMark() { return this.tryGetToken(CommonRegexParser$1.QuestionMark, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_quantifier_type; } + // @Override + enterRule(listener) { + if (listener.enterQuantifier_type) { + listener.enterQuantifier_type(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitQuantifier_type) { + listener.exitQuantifier_type(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitQuantifier_type) { + return visitor.visitQuantifier_type(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Quantifier_typeContext = Quantifier_typeContext; + class Character_classContext extends ParserRuleContext_1.ParserRuleContext { + CharacterClassStart() { return this.getToken(CommonRegexParser$1.CharacterClassStart, 0); } + Caret() { return this.tryGetToken(CommonRegexParser$1.Caret, 0); } + CharacterClassEnd() { return this.getToken(CommonRegexParser$1.CharacterClassEnd, 0); } + cc_atom(i) { + if (i === undefined) { + return this.getRuleContexts(Cc_atomContext); + } + else { + return this.getRuleContext(i, Cc_atomContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_character_class; } + // @Override + enterRule(listener) { + if (listener.enterCharacter_class) { + listener.enterCharacter_class(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitCharacter_class) { + listener.exitCharacter_class(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitCharacter_class) { + return visitor.visitCharacter_class(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Character_classContext = Character_classContext; + class CaptureContext extends ParserRuleContext_1.ParserRuleContext { + OpenParen() { return this.getToken(CommonRegexParser$1.OpenParen, 0); } + QuestionMark() { return this.tryGetToken(CommonRegexParser$1.QuestionMark, 0); } + LessThan() { return this.tryGetToken(CommonRegexParser$1.LessThan, 0); } + name() { + return this.tryGetRuleContext(0, NameContext); + } + GreaterThan() { return this.tryGetToken(CommonRegexParser$1.GreaterThan, 0); } + alternation() { + return this.getRuleContext(0, AlternationContext); + } + CloseParen() { return this.getToken(CommonRegexParser$1.CloseParen, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_capture; } + // @Override + enterRule(listener) { + if (listener.enterCapture) { + listener.enterCapture(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitCapture) { + listener.exitCapture(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitCapture) { + return visitor.visitCapture(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.CaptureContext = CaptureContext; + class Non_captureContext extends ParserRuleContext_1.ParserRuleContext { + OpenParen() { return this.getToken(CommonRegexParser$1.OpenParen, 0); } + QuestionMark() { return this.getToken(CommonRegexParser$1.QuestionMark, 0); } + Colon() { return this.getToken(CommonRegexParser$1.Colon, 0); } + alternation() { + return this.getRuleContext(0, AlternationContext); + } + CloseParen() { return this.getToken(CommonRegexParser$1.CloseParen, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_non_capture; } + // @Override + enterRule(listener) { + if (listener.enterNon_capture) { + listener.enterNon_capture(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitNon_capture) { + listener.exitNon_capture(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitNon_capture) { + return visitor.visitNon_capture(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Non_captureContext = Non_captureContext; + class OptionContext extends ParserRuleContext_1.ParserRuleContext { + OpenParen() { return this.getToken(CommonRegexParser$1.OpenParen, 0); } + QuestionMark() { return this.getToken(CommonRegexParser$1.QuestionMark, 0); } + CloseParen() { return this.getToken(CommonRegexParser$1.CloseParen, 0); } + option_flag(i) { + if (i === undefined) { + return this.getRuleContexts(Option_flagContext); + } + else { + return this.getRuleContext(i, Option_flagContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_option; } + // @Override + enterRule(listener) { + if (listener.enterOption) { + listener.enterOption(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitOption) { + listener.exitOption(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitOption) { + return visitor.visitOption(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.OptionContext = OptionContext; + class Option_flagContext extends ParserRuleContext_1.ParserRuleContext { + ILC() { return this.tryGetToken(CommonRegexParser$1.ILC, 0); } + MLC() { return this.tryGetToken(CommonRegexParser$1.MLC, 0); } + SLC() { return this.tryGetToken(CommonRegexParser$1.SLC, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_option_flag; } + // @Override + enterRule(listener) { + if (listener.enterOption_flag) { + listener.enterOption_flag(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitOption_flag) { + listener.exitOption_flag(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitOption_flag) { + return visitor.visitOption_flag(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Option_flagContext = Option_flagContext; + class AtomContext extends ParserRuleContext_1.ParserRuleContext { + shared_atom() { + return this.tryGetRuleContext(0, Shared_atomContext); + } + literal() { + return this.tryGetRuleContext(0, LiteralContext); + } + character_class() { + return this.tryGetRuleContext(0, Character_classContext); + } + capture() { + return this.tryGetRuleContext(0, CaptureContext); + } + non_capture() { + return this.tryGetRuleContext(0, Non_captureContext); + } + option() { + return this.tryGetRuleContext(0, OptionContext); + } + Dot() { return this.tryGetToken(CommonRegexParser$1.Dot, 0); } + Caret() { return this.tryGetToken(CommonRegexParser$1.Caret, 0); } + EndOfSubject() { return this.tryGetToken(CommonRegexParser$1.EndOfSubject, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_atom; } + // @Override + enterRule(listener) { + if (listener.enterAtom) { + listener.enterAtom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitAtom) { + listener.exitAtom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitAtom) { + return visitor.visitAtom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.AtomContext = AtomContext; + class Cc_atomContext extends ParserRuleContext_1.ParserRuleContext { + cc_literal(i) { + if (i === undefined) { + return this.getRuleContexts(Cc_literalContext); + } + else { + return this.getRuleContext(i, Cc_literalContext); + } + } + Hyphen() { return this.tryGetToken(CommonRegexParser$1.Hyphen, 0); } + shared_atom() { + return this.tryGetRuleContext(0, Shared_atomContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_cc_atom; } + // @Override + enterRule(listener) { + if (listener.enterCc_atom) { + listener.enterCc_atom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitCc_atom) { + listener.exitCc_atom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitCc_atom) { + return visitor.visitCc_atom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Cc_atomContext = Cc_atomContext; + class Shared_atomContext extends ParserRuleContext_1.ParserRuleContext { + ControlChar() { return this.tryGetToken(CommonRegexParser$1.ControlChar, 0); } + DecimalDigit() { return this.tryGetToken(CommonRegexParser$1.DecimalDigit, 0); } + NotDecimalDigit() { return this.tryGetToken(CommonRegexParser$1.NotDecimalDigit, 0); } + CharWithProperty() { return this.tryGetToken(CommonRegexParser$1.CharWithProperty, 0); } + CharWithoutProperty() { return this.tryGetToken(CommonRegexParser$1.CharWithoutProperty, 0); } + WhiteSpace() { return this.tryGetToken(CommonRegexParser$1.WhiteSpace, 0); } + NotWhiteSpace() { return this.tryGetToken(CommonRegexParser$1.NotWhiteSpace, 0); } + WordChar() { return this.tryGetToken(CommonRegexParser$1.WordChar, 0); } + NotWordChar() { return this.tryGetToken(CommonRegexParser$1.NotWordChar, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_shared_atom; } + // @Override + enterRule(listener) { + if (listener.enterShared_atom) { + listener.enterShared_atom(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitShared_atom) { + listener.exitShared_atom(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitShared_atom) { + return visitor.visitShared_atom(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Shared_atomContext = Shared_atomContext; + class LiteralContext extends ParserRuleContext_1.ParserRuleContext { + shared_literal() { + return this.tryGetRuleContext(0, Shared_literalContext); + } + CharacterClassEnd() { return this.tryGetToken(CommonRegexParser$1.CharacterClassEnd, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_literal; } + // @Override + enterRule(listener) { + if (listener.enterLiteral) { + listener.enterLiteral(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitLiteral) { + listener.exitLiteral(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitLiteral) { + return visitor.visitLiteral(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.LiteralContext = LiteralContext; + class Cc_literalContext extends ParserRuleContext_1.ParserRuleContext { + shared_literal() { + return this.tryGetRuleContext(0, Shared_literalContext); + } + Dot() { return this.tryGetToken(CommonRegexParser$1.Dot, 0); } + CharacterClassStart() { return this.tryGetToken(CommonRegexParser$1.CharacterClassStart, 0); } + Caret() { return this.tryGetToken(CommonRegexParser$1.Caret, 0); } + QuestionMark() { return this.tryGetToken(CommonRegexParser$1.QuestionMark, 0); } + Plus() { return this.tryGetToken(CommonRegexParser$1.Plus, 0); } + Star() { return this.tryGetToken(CommonRegexParser$1.Star, 0); } + EndOfSubject() { return this.tryGetToken(CommonRegexParser$1.EndOfSubject, 0); } + Pipe() { return this.tryGetToken(CommonRegexParser$1.Pipe, 0); } + OpenParen() { return this.tryGetToken(CommonRegexParser$1.OpenParen, 0); } + CloseParen() { return this.tryGetToken(CommonRegexParser$1.CloseParen, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_cc_literal; } + // @Override + enterRule(listener) { + if (listener.enterCc_literal) { + listener.enterCc_literal(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitCc_literal) { + listener.exitCc_literal(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitCc_literal) { + return visitor.visitCc_literal(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Cc_literalContext = Cc_literalContext; + class Shared_literalContext extends ParserRuleContext_1.ParserRuleContext { + octal_char() { + return this.tryGetRuleContext(0, Octal_charContext); + } + letter() { + return this.tryGetRuleContext(0, LetterContext); + } + digit() { + return this.tryGetRuleContext(0, DigitContext); + } + BellChar() { return this.tryGetToken(CommonRegexParser$1.BellChar, 0); } + EscapeChar() { return this.tryGetToken(CommonRegexParser$1.EscapeChar, 0); } + FormFeed() { return this.tryGetToken(CommonRegexParser$1.FormFeed, 0); } + NewLine() { return this.tryGetToken(CommonRegexParser$1.NewLine, 0); } + CarriageReturn() { return this.tryGetToken(CommonRegexParser$1.CarriageReturn, 0); } + Tab() { return this.tryGetToken(CommonRegexParser$1.Tab, 0); } + HexChar() { return this.tryGetToken(CommonRegexParser$1.HexChar, 0); } + Quoted() { return this.tryGetToken(CommonRegexParser$1.Quoted, 0); } + BlockQuoted() { return this.tryGetToken(CommonRegexParser$1.BlockQuoted, 0); } + OpenBrace() { return this.tryGetToken(CommonRegexParser$1.OpenBrace, 0); } + CloseBrace() { return this.tryGetToken(CommonRegexParser$1.CloseBrace, 0); } + Comma() { return this.tryGetToken(CommonRegexParser$1.Comma, 0); } + Hyphen() { return this.tryGetToken(CommonRegexParser$1.Hyphen, 0); } + LessThan() { return this.tryGetToken(CommonRegexParser$1.LessThan, 0); } + GreaterThan() { return this.tryGetToken(CommonRegexParser$1.GreaterThan, 0); } + SingleQuote() { return this.tryGetToken(CommonRegexParser$1.SingleQuote, 0); } + Underscore() { return this.tryGetToken(CommonRegexParser$1.Underscore, 0); } + Colon() { return this.tryGetToken(CommonRegexParser$1.Colon, 0); } + Hash() { return this.tryGetToken(CommonRegexParser$1.Hash, 0); } + Equals() { return this.tryGetToken(CommonRegexParser$1.Equals, 0); } + Exclamation() { return this.tryGetToken(CommonRegexParser$1.Exclamation, 0); } + Ampersand() { return this.tryGetToken(CommonRegexParser$1.Ampersand, 0); } + OtherChar() { return this.tryGetToken(CommonRegexParser$1.OtherChar, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_shared_literal; } + // @Override + enterRule(listener) { + if (listener.enterShared_literal) { + listener.enterShared_literal(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitShared_literal) { + listener.exitShared_literal(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitShared_literal) { + return visitor.visitShared_literal(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Shared_literalContext = Shared_literalContext; + class NumberContext extends ParserRuleContext_1.ParserRuleContext { + digits() { + return this.getRuleContext(0, DigitsContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_number; } + // @Override + enterRule(listener) { + if (listener.enterNumber) { + listener.enterNumber(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitNumber) { + listener.exitNumber(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitNumber) { + return visitor.visitNumber(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.NumberContext = NumberContext; + class Octal_charContext extends ParserRuleContext_1.ParserRuleContext { + Backslash() { return this.tryGetToken(CommonRegexParser$1.Backslash, 0); } + octal_digit(i) { + if (i === undefined) { + return this.getRuleContexts(Octal_digitContext); + } + else { + return this.getRuleContext(i, Octal_digitContext); + } + } + D0() { return this.tryGetToken(CommonRegexParser$1.D0, 0); } + D1() { return this.tryGetToken(CommonRegexParser$1.D1, 0); } + D2() { return this.tryGetToken(CommonRegexParser$1.D2, 0); } + D3() { return this.tryGetToken(CommonRegexParser$1.D3, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_octal_char; } + // @Override + enterRule(listener) { + if (listener.enterOctal_char) { + listener.enterOctal_char(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitOctal_char) { + listener.exitOctal_char(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitOctal_char) { + return visitor.visitOctal_char(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Octal_charContext = Octal_charContext; + class Octal_digitContext extends ParserRuleContext_1.ParserRuleContext { + D0() { return this.tryGetToken(CommonRegexParser$1.D0, 0); } + D1() { return this.tryGetToken(CommonRegexParser$1.D1, 0); } + D2() { return this.tryGetToken(CommonRegexParser$1.D2, 0); } + D3() { return this.tryGetToken(CommonRegexParser$1.D3, 0); } + D4() { return this.tryGetToken(CommonRegexParser$1.D4, 0); } + D5() { return this.tryGetToken(CommonRegexParser$1.D5, 0); } + D6() { return this.tryGetToken(CommonRegexParser$1.D6, 0); } + D7() { return this.tryGetToken(CommonRegexParser$1.D7, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_octal_digit; } + // @Override + enterRule(listener) { + if (listener.enterOctal_digit) { + listener.enterOctal_digit(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitOctal_digit) { + listener.exitOctal_digit(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitOctal_digit) { + return visitor.visitOctal_digit(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Octal_digitContext = Octal_digitContext; + class DigitsContext extends ParserRuleContext_1.ParserRuleContext { + digit(i) { + if (i === undefined) { + return this.getRuleContexts(DigitContext); + } + else { + return this.getRuleContext(i, DigitContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_digits; } + // @Override + enterRule(listener) { + if (listener.enterDigits) { + listener.enterDigits(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitDigits) { + listener.exitDigits(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitDigits) { + return visitor.visitDigits(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.DigitsContext = DigitsContext; + class DigitContext extends ParserRuleContext_1.ParserRuleContext { + D0() { return this.tryGetToken(CommonRegexParser$1.D0, 0); } + D1() { return this.tryGetToken(CommonRegexParser$1.D1, 0); } + D2() { return this.tryGetToken(CommonRegexParser$1.D2, 0); } + D3() { return this.tryGetToken(CommonRegexParser$1.D3, 0); } + D4() { return this.tryGetToken(CommonRegexParser$1.D4, 0); } + D5() { return this.tryGetToken(CommonRegexParser$1.D5, 0); } + D6() { return this.tryGetToken(CommonRegexParser$1.D6, 0); } + D7() { return this.tryGetToken(CommonRegexParser$1.D7, 0); } + D8() { return this.tryGetToken(CommonRegexParser$1.D8, 0); } + D9() { return this.tryGetToken(CommonRegexParser$1.D9, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_digit; } + // @Override + enterRule(listener) { + if (listener.enterDigit) { + listener.enterDigit(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitDigit) { + listener.exitDigit(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitDigit) { + return visitor.visitDigit(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.DigitContext = DigitContext; + class NameContext extends ParserRuleContext_1.ParserRuleContext { + alpha_nums() { + return this.getRuleContext(0, Alpha_numsContext); + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_name; } + // @Override + enterRule(listener) { + if (listener.enterName) { + listener.enterName(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitName) { + listener.exitName(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitName) { + return visitor.visitName(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.NameContext = NameContext; + class Alpha_numsContext extends ParserRuleContext_1.ParserRuleContext { + letter(i) { + if (i === undefined) { + return this.getRuleContexts(LetterContext); + } + else { + return this.getRuleContext(i, LetterContext); + } + } + Underscore(i) { + if (i === undefined) { + return this.getTokens(CommonRegexParser$1.Underscore); + } + else { + return this.getToken(CommonRegexParser$1.Underscore, i); + } + } + digit(i) { + if (i === undefined) { + return this.getRuleContexts(DigitContext); + } + else { + return this.getRuleContext(i, DigitContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_alpha_nums; } + // @Override + enterRule(listener) { + if (listener.enterAlpha_nums) { + listener.enterAlpha_nums(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitAlpha_nums) { + listener.exitAlpha_nums(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitAlpha_nums) { + return visitor.visitAlpha_nums(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Alpha_numsContext = Alpha_numsContext; + class Non_close_parensContext extends ParserRuleContext_1.ParserRuleContext { + non_close_paren(i) { + if (i === undefined) { + return this.getRuleContexts(Non_close_parenContext); + } + else { + return this.getRuleContext(i, Non_close_parenContext); + } + } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_non_close_parens; } + // @Override + enterRule(listener) { + if (listener.enterNon_close_parens) { + listener.enterNon_close_parens(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitNon_close_parens) { + listener.exitNon_close_parens(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitNon_close_parens) { + return visitor.visitNon_close_parens(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Non_close_parensContext = Non_close_parensContext; + class Non_close_parenContext extends ParserRuleContext_1.ParserRuleContext { + CloseParen() { return this.getToken(CommonRegexParser$1.CloseParen, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_non_close_paren; } + // @Override + enterRule(listener) { + if (listener.enterNon_close_paren) { + listener.enterNon_close_paren(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitNon_close_paren) { + listener.exitNon_close_paren(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitNon_close_paren) { + return visitor.visitNon_close_paren(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.Non_close_parenContext = Non_close_parenContext; + class LetterContext extends ParserRuleContext_1.ParserRuleContext { + ALC() { return this.tryGetToken(CommonRegexParser$1.ALC, 0); } + BLC() { return this.tryGetToken(CommonRegexParser$1.BLC, 0); } + CLC() { return this.tryGetToken(CommonRegexParser$1.CLC, 0); } + DLC() { return this.tryGetToken(CommonRegexParser$1.DLC, 0); } + ELC() { return this.tryGetToken(CommonRegexParser$1.ELC, 0); } + FLC() { return this.tryGetToken(CommonRegexParser$1.FLC, 0); } + GLC() { return this.tryGetToken(CommonRegexParser$1.GLC, 0); } + HLC() { return this.tryGetToken(CommonRegexParser$1.HLC, 0); } + ILC() { return this.tryGetToken(CommonRegexParser$1.ILC, 0); } + JLC() { return this.tryGetToken(CommonRegexParser$1.JLC, 0); } + KLC() { return this.tryGetToken(CommonRegexParser$1.KLC, 0); } + LLC() { return this.tryGetToken(CommonRegexParser$1.LLC, 0); } + MLC() { return this.tryGetToken(CommonRegexParser$1.MLC, 0); } + NLC() { return this.tryGetToken(CommonRegexParser$1.NLC, 0); } + OLC() { return this.tryGetToken(CommonRegexParser$1.OLC, 0); } + PLC() { return this.tryGetToken(CommonRegexParser$1.PLC, 0); } + QLC() { return this.tryGetToken(CommonRegexParser$1.QLC, 0); } + RLC() { return this.tryGetToken(CommonRegexParser$1.RLC, 0); } + SLC() { return this.tryGetToken(CommonRegexParser$1.SLC, 0); } + TLC() { return this.tryGetToken(CommonRegexParser$1.TLC, 0); } + ULC() { return this.tryGetToken(CommonRegexParser$1.ULC, 0); } + VLC() { return this.tryGetToken(CommonRegexParser$1.VLC, 0); } + WLC() { return this.tryGetToken(CommonRegexParser$1.WLC, 0); } + XLC() { return this.tryGetToken(CommonRegexParser$1.XLC, 0); } + YLC() { return this.tryGetToken(CommonRegexParser$1.YLC, 0); } + ZLC() { return this.tryGetToken(CommonRegexParser$1.ZLC, 0); } + AUC() { return this.tryGetToken(CommonRegexParser$1.AUC, 0); } + BUC() { return this.tryGetToken(CommonRegexParser$1.BUC, 0); } + CUC() { return this.tryGetToken(CommonRegexParser$1.CUC, 0); } + DUC() { return this.tryGetToken(CommonRegexParser$1.DUC, 0); } + EUC() { return this.tryGetToken(CommonRegexParser$1.EUC, 0); } + FUC() { return this.tryGetToken(CommonRegexParser$1.FUC, 0); } + GUC() { return this.tryGetToken(CommonRegexParser$1.GUC, 0); } + HUC() { return this.tryGetToken(CommonRegexParser$1.HUC, 0); } + IUC() { return this.tryGetToken(CommonRegexParser$1.IUC, 0); } + JUC() { return this.tryGetToken(CommonRegexParser$1.JUC, 0); } + KUC() { return this.tryGetToken(CommonRegexParser$1.KUC, 0); } + LUC() { return this.tryGetToken(CommonRegexParser$1.LUC, 0); } + MUC() { return this.tryGetToken(CommonRegexParser$1.MUC, 0); } + NUC() { return this.tryGetToken(CommonRegexParser$1.NUC, 0); } + OUC() { return this.tryGetToken(CommonRegexParser$1.OUC, 0); } + PUC() { return this.tryGetToken(CommonRegexParser$1.PUC, 0); } + QUC() { return this.tryGetToken(CommonRegexParser$1.QUC, 0); } + RUC() { return this.tryGetToken(CommonRegexParser$1.RUC, 0); } + SUC() { return this.tryGetToken(CommonRegexParser$1.SUC, 0); } + TUC() { return this.tryGetToken(CommonRegexParser$1.TUC, 0); } + UUC() { return this.tryGetToken(CommonRegexParser$1.UUC, 0); } + VUC() { return this.tryGetToken(CommonRegexParser$1.VUC, 0); } + WUC() { return this.tryGetToken(CommonRegexParser$1.WUC, 0); } + XUC() { return this.tryGetToken(CommonRegexParser$1.XUC, 0); } + YUC() { return this.tryGetToken(CommonRegexParser$1.YUC, 0); } + ZUC() { return this.tryGetToken(CommonRegexParser$1.ZUC, 0); } + constructor(parent, invokingState) { + super(parent, invokingState); + } + // @Override + get ruleIndex() { return CommonRegexParser$1.RULE_letter; } + // @Override + enterRule(listener) { + if (listener.enterLetter) { + listener.enterLetter(this); + } + } + // @Override + exitRule(listener) { + if (listener.exitLetter) { + listener.exitLetter(this); + } + } + // @Override + accept(visitor) { + if (visitor.visitLetter) { + return visitor.visitLetter(this); + } + else { + return visitor.visitChildren(this); + } + } + } + CommonRegexParser.LetterContext = LetterContext; + + return CommonRegexParser; +} + +var CommonRegexVisitor = {}; + +var hasRequiredCommonRegexVisitor; + +function requireCommonRegexVisitor () { + if (hasRequiredCommonRegexVisitor) return CommonRegexVisitor; + hasRequiredCommonRegexVisitor = 1; + // Generated from src/CommonRegex.g4 by ANTLR 4.7.3-SNAPSHOT + Object.defineProperty(CommonRegexVisitor, "__esModule", { value: true }); + + return CommonRegexVisitor; +} + +var hasRequiredGenerated; + +function requireGenerated () { + if (hasRequiredGenerated) return generated; + hasRequiredGenerated = 1; + (function (exports) { + var __createBinding = (generated && generated.__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 = (generated && generated.__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 }); + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + __exportStar(requireCommonRegexLexer(), exports); + __exportStar(requireCommonRegexListener(), exports); + __exportStar(requireCommonRegexParser(), exports); + __exportStar(requireCommonRegexVisitor(), exports); + + } (generated)); + return generated; +} + +var regexErrorListener = {}; + +var hasRequiredRegexErrorListener; + +function requireRegexErrorListener () { + if (hasRequiredRegexErrorListener) return regexErrorListener; + hasRequiredRegexErrorListener = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(regexErrorListener, "__esModule", { value: true }); + regexErrorListener.RegexErrorListener = void 0; + /** + * Error listener for Regex. + */ + class RegexErrorListener { + /** + * Upon syntax error, notify any interested parties. + * + * @param _recognizer What parser got the error. From this object, you can access the context as well as the input stream. + * @param _offendingSymbol Offending token in the input token stream, unless recognizer is a lexer, then it's null. + * @param _line Line number in the input where the error occurred. + * @param _charPositionInLine Character position within the line where the error occurred. + * @param _msg Message to emit. + * @param _e Exception generated by the parser that led to the reporting of an error. + */ + syntaxError(_recognizer, _offendingSymbol, _line, _charPositionInLine, _msg, _e) { + throw Error('Regular expression is invalid.'); + } + } + regexErrorListener.RegexErrorListener = RegexErrorListener; + RegexErrorListener.Instance = new RegexErrorListener(); + + return regexErrorListener; +} + +var hasRequiredCommonRegex; + +function requireCommonRegex () { + if (hasRequiredCommonRegex) return commonRegex; + hasRequiredCommonRegex = 1; + var __importDefault = (commonRegex && commonRegex.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(commonRegex, "__esModule", { value: true }); + commonRegex.CommonRegex = void 0; + /* eslint-disable security/detect-non-literal-regexp */ + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + const antlr4ts_1 = requireAntlr4ts(); + const lru_cache_1 = __importDefault(requireLruCache()); + const generated_1 = requireGenerated(); + const regexErrorListener_1 = requireRegexErrorListener(); + // tslint:disable-next-line: completed-docs + /** + * Convert PCRE regex string to RegExp + * PCRE ref: http://www.pcre.org/. + * PCRE antlr g4 file: CommonRegex.g4. + */ + class CommonRegex { + /** + * Create RegExp object from PCRE pattern string. + * + * @param pattern PCRE pattern string. + * @returns RegExp object. + */ + static CreateRegex(pattern) { + let result; + if (pattern && this.regexCache.has(pattern)) { + result = this.regexCache.get(pattern); + } + else { + if (!pattern || !this.isCommonRegex(pattern)) { + throw new Error(`'${pattern}' is not a valid regex.`); + } + result = this.getRegExpFromString(pattern); + this.regexCache.set(pattern, result); + } + return result; + } + /** + * @private + */ + static getRegExpFromString(pattern) { + const flags = ['(?i)', '(?m)', '(?s)']; + let flag = ''; + flags.forEach((e) => { + if (pattern.includes(e)) { + flag += e.substr(2, 1); + pattern = pattern.replace(e, ''); + } + }); + let regexp; + if (flag) { + regexp = new RegExp(`${pattern}`, flag); + } + else { + regexp = new RegExp(`${pattern}`); + } + return regexp; + } + /** + * @private + */ + static isCommonRegex(pattern) { + try { + this.antlrParse(pattern); + } + catch (_a) { + return false; + } + return true; + } + /** + * @private + */ + static antlrParse(pattern) { + const inputStream = new antlr4ts_1.ANTLRInputStream(pattern); + const lexer = new generated_1.CommonRegexLexer(inputStream); + lexer.removeErrorListeners(); + const tokenStream = new antlr4ts_1.CommonTokenStream(lexer); + const parser = new generated_1.CommonRegexParser(tokenStream); + parser.removeErrorListeners(); + // tslint:disable-next-line: no-use-before-declare + parser.addErrorListener(regexErrorListener_1.RegexErrorListener.Instance); + parser.buildParseTree = true; + return parser.parse(); + } + } + commonRegex.CommonRegex = CommonRegex; + CommonRegex.regexCache = new lru_cache_1.default(15); + + return commonRegex; +} + +var hasRequiredIsMatch; + +function requireIsMatch () { + if (hasRequiredIsMatch) return isMatch; + hasRequiredIsMatch = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isMatch, "__esModule", { value: true }); + isMatch.IsMatch = void 0; + const commonRegex_1 = requireCommonRegex(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given string matches a specified regular expression pattern. + */ + class IsMatch extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsMatch](xref:adaptive-expressions.IsMatch) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsMatch, IsMatch.evaluator(), returnType_1.ReturnType.Boolean, IsMatch.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const regex = commonRegex_1.CommonRegex.CreateRegex(args[1].toString()); + const inputString = args[0] ? args[0].toString() : ''; + const value = regex.test(inputString); + return { value, undefined }; + }, functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.String); + const second = expression.children[1]; + if (second.returnType === returnType_1.ReturnType.String && second.type === expressionType_1.ExpressionType.Constant) { + commonRegex_1.CommonRegex.CreateRegex(second.value.toString()); + } + } + } + isMatch.IsMatch = IsMatch; + + return isMatch; +} + +var isObject = {}; + +var hasRequiredIsObject; + +function requireIsObject () { + if (hasRequiredIsObject) return isObject; + hasRequiredIsObject = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isObject, "__esModule", { value: true }); + isObject.IsObject = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is a complex object or return false if it is a primitive object. + * Primitive objects include strings, numbers, and Booleans; + * complex types, contain properties. + */ + class IsObject extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsObject](xref:adaptive-expressions.IsObject) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsObject, IsObject.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => typeof args[0] === 'object'); + } + } + isObject.IsObject = IsObject; + + return isObject; +} + +var isPresent = {}; + +var hasRequiredIsPresent; + +function requireIsPresent () { + if (hasRequiredIsPresent) return isPresent; + hasRequiredIsPresent = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isPresent, "__esModule", { value: true }); + isPresent.IsPresent = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to the present. + */ + class IsPresent extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsPresent](xref:adaptive-expressions.IsPresent) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsPresent, IsPresent.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = parsed.now !== undefined; + } + return { value, error }; + } + } + isPresent.IsPresent = IsPresent; + + return isPresent; +} + +var isString = {}; + +var hasRequiredIsString; + +function requireIsString () { + if (hasRequiredIsString) return isString; + hasRequiredIsString = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isString, "__esModule", { value: true }); + isString.IsString = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given input is a string. + */ + class IsString extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsString](xref:adaptive-expressions.IsString) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsString, IsString.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => typeof args[0] === 'string'); + } + } + isString.IsString = IsString; + + return isString; +} + +var isTime = {}; + +var hasRequiredIsTime; + +function requireIsTime () { + if (hasRequiredIsTime) return isTime; + hasRequiredIsTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isTime, "__esModule", { value: true }); + isTime.IsTime = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to a valid time. + * Valid time contains hours, minutes and seconds. + */ + class IsTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsTime](xref:adaptive-expressions.IsTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsTime, IsTime.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = parsed.hour !== undefined && parsed.minute !== undefined && parsed.second !== undefined; + } + return { value, error }; + } + } + isTime.IsTime = IsTime; + + return isTime; +} + +var isTimeRange = {}; + +var hasRequiredIsTimeRange; + +function requireIsTimeRange () { + if (hasRequiredIsTimeRange) return isTimeRange; + hasRequiredIsTimeRange = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(isTimeRange, "__esModule", { value: true }); + isTimeRange.IsTimeRange = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given `TimexProperty` or Timex string refers to a valid time range Valid time ranges contain partOfDay. + */ + class IsTimeRange extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [IsTimeRange](xref:adaptive-expressions.IsTimeRange) class. + */ + constructor() { + super(expressionType_1.ExpressionType.IsTimeRange, IsTimeRange.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (parsed && !error) { + value = parsed.partOfDay !== undefined; + } + return { value, error }; + } + } + isTimeRange.IsTimeRange = IsTimeRange; + + return isTimeRange; +} + +var join = {}; + +var hasRequiredJoin; + +function requireJoin () { + if (hasRequiredJoin) return join; + hasRequiredJoin = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(join, "__esModule", { value: true }); + join.Join = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return a string that has all the items from an array, with each character separated by a delimiter. + */ + class Join extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the Join class. + */ + constructor() { + super(expressionType_1.ExpressionType.Join, Join.evaluator, returnType_1.ReturnType.String, Join.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (!Array.isArray(args[0])) { + error = `${expression.children[0]} evaluates to ${args[0]} which is not a list.`; + } + else { + if (args.length === 2) { + value = args[0].join(args[1]); + } + else { + if (args[0].length < 3) { + value = args[0].join(args[2]); + } + else { + const firstPart = args[0].slice(0, args[0].length - 1).join(args[1]); + value = firstPart.concat(args[2], args[0][args[0].length - 1]); + } + } + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String], returnType_1.ReturnType.Array, returnType_1.ReturnType.String); + } + } + join.Join = Join; + + return join; +} + +var jPath = {}; + +var jspath$1 = {exports: {}}; + +var hasRequiredJspath$1; + +function requireJspath$1 () { + if (hasRequiredJspath$1) return jspath$1.exports; + hasRequiredJspath$1 = 1; + (function (module) { + /** + * JSPath + * + * Copyright (c) 2012 Filatov Dmitry (dfilatov@yandex-team.ru) + * With parts by Marat Dulin (mdevils@gmail.com) + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * @version 0.4.0 + */ + + (function() { + + var SYNTAX = { + PATH : 1, + SELECTOR : 2, + OBJ_PRED : 3, + POS_PRED : 4, + LOGICAL_EXPR : 5, + COMPARISON_EXPR : 6, + MATH_EXPR : 7, + CONCAT_EXPR : 8, + UNARY_EXPR : 9, + POS_EXPR : 10, + LITERAL : 11 + }; + + // parser + + var parse = (function() { + + var TOKEN = { + ID : 1, + NUM : 2, + STR : 3, + BOOL : 4, + NULL : 5, + PUNCT : 6, + EOP : 7 + }, + MESSAGES = { + UNEXP_TOKEN : 'Unexpected token "%0"', + UNEXP_EOP : 'Unexpected end of path' + }; + + var path, idx, buf, len; + + function parse(_path) { + path = _path.split(''); + idx = 0; + buf = null; + len = path.length; + + var res = parsePathConcatExpr(), + token = lex(); + + if(token.type !== TOKEN.EOP) { + throwUnexpected(token); + } + + return res; + } + + function parsePathConcatExpr() { + var expr = parsePathConcatPartExpr(), + operands; + + while(match('|')) { + lex(); + (operands || (operands = [expr])).push(parsePathConcatPartExpr()); + } + + return operands? + { + type : SYNTAX.CONCAT_EXPR, + args : operands + } : + expr; + } + + function parsePathConcatPartExpr() { + return match('(')? + parsePathGroupExpr() : + parsePath(); + } + + function parsePathGroupExpr() { + expect('('); + var expr = parsePathConcatExpr(); + expect(')'); + + var parts = [], + part; + while((part = parsePredicate())) { + parts.push(part); + } + + if(!parts.length) { + return expr; + } + else if(expr.type === SYNTAX.PATH) { + expr.parts = expr.parts.concat(parts); + return expr; + } + + parts.unshift(expr); + + return { + type : SYNTAX.PATH, + parts : parts + }; + } + + function parsePredicate() { + if(match('[')) { + return parsePosPredicate(); + } + + if(match('{')) { + return parseObjectPredicate(); + } + + if(match('(')) { + return parsePathGroupExpr(); + } + } + + function parsePath() { + if(!matchPath()) { + throwUnexpected(lex()); + } + + var fromRoot = false, + subst; + + if(match('^')) { + lex(); + fromRoot = true; + } + else if(matchSubst()) { + subst = lex().val.substr(1); + } + + var parts = [], + part; + while((part = parsePathPart())) { + parts.push(part); + } + + return { + type : SYNTAX.PATH, + fromRoot : fromRoot, + subst : subst, + parts : parts + }; + } + + function parsePathPart() { + return matchSelector()? + parseSelector() : + parsePredicate(); + } + + function parseSelector() { + var selector = lex().val, + token = lookahead(), + prop; + + if(match('*') || token.type === TOKEN.ID || token.type === TOKEN.STR) { + prop = lex().val; + } + + return { + type : SYNTAX.SELECTOR, + selector : selector, + prop : prop + }; + } + + function parsePosPredicate() { + expect('['); + var expr = parsePosExpr(); + expect(']'); + + return { + type : SYNTAX.POS_PRED, + arg : expr + }; + } + + function parseObjectPredicate() { + expect('{'); + var expr = parseLogicalORExpr(); + expect('}'); + + return { + type : SYNTAX.OBJ_PRED, + arg : expr + }; + } + + function parseLogicalORExpr() { + var expr = parseLogicalANDExpr(), + operands; + + while(match('||')) { + lex(); + (operands || (operands = [expr])).push(parseLogicalANDExpr()); + } + + return operands? + { + type : SYNTAX.LOGICAL_EXPR, + op : '||', + args : operands + } : + expr; + } + + function parseLogicalANDExpr() { + var expr = parseEqualityExpr(), + operands; + + while(match('&&')) { + lex(); + (operands || (operands = [expr])).push(parseEqualityExpr()); + } + + return operands? + { + type : SYNTAX.LOGICAL_EXPR, + op : '&&', + args : operands + } : + expr; + } + + function parseEqualityExpr() { + var expr = parseRelationalExpr(); + + while( + match('==') || match('!=') || match('===') || match('!==') || + match('^==') || match('==^') ||match('^=') || match('=^') || + match('$==') || match('==$') || match('$=') || match('=$') || + match('*==') || match('==*')|| match('*=') || match('=*') + ) { + expr = { + type : SYNTAX.COMPARISON_EXPR, + op : lex().val, + args : [expr, parseEqualityExpr()] + }; + } + + return expr; + } + + function parseRelationalExpr() { + var expr = parseAdditiveExpr(); + + while(match('<') || match('>') || match('<=') || match('>=')) { + expr = { + type : SYNTAX.COMPARISON_EXPR, + op : lex().val, + args : [expr, parseRelationalExpr()] + }; + } + + return expr; + } + + function parseAdditiveExpr() { + var expr = parseMultiplicativeExpr(); + + while(match('+') || match('-')) { + expr = { + type : SYNTAX.MATH_EXPR, + op : lex().val, + args : [expr, parseMultiplicativeExpr()] + }; + } + + return expr; + } + + function parseMultiplicativeExpr() { + var expr = parseUnaryExpr(); + + while(match('*') || match('/') || match('%')) { + expr = { + type : SYNTAX.MATH_EXPR, + op : lex().val, + args : [expr, parseMultiplicativeExpr()] + }; + } + + return expr; + } + + function parsePosExpr() { + if(match(':')) { + lex(); + return { + type : SYNTAX.POS_EXPR, + toIdx : parseUnaryExpr() + }; + } + + var fromExpr = parseUnaryExpr(); + if(match(':')) { + lex(); + if(match(']')) { + return { + type : SYNTAX.POS_EXPR, + fromIdx : fromExpr + }; + } + + return { + type : SYNTAX.POS_EXPR, + fromIdx : fromExpr, + toIdx : parseUnaryExpr() + }; + } + + return { + type : SYNTAX.POS_EXPR, + idx : fromExpr + }; + } + + function parseUnaryExpr() { + if(match('!') || match('-')) { + return { + type : SYNTAX.UNARY_EXPR, + op : lex().val, + arg : parseUnaryExpr() + }; + } + + return parsePrimaryExpr(); + } + + function parsePrimaryExpr() { + var token = lookahead(), + type = token.type; + + if(type === TOKEN.STR || type === TOKEN.NUM || type === TOKEN.BOOL || type === TOKEN.NULL) { + return { + type : SYNTAX.LITERAL, + val : lex().val + }; + } + + if(matchPath()) { + return parsePath(); + } + + if(match('(')) { + return parseGroupExpr(); + } + + return throwUnexpected(lex()); + } + + function parseGroupExpr() { + expect('('); + var expr = parseLogicalORExpr(); + expect(')'); + + return expr; + } + + function match(val) { + var token = lookahead(); + return token.type === TOKEN.PUNCT && token.val === val; + } + + function matchPath() { + return matchSelector() || matchSubst() || match('^'); + } + + function matchSelector() { + var token = lookahead(); + if(token.type === TOKEN.PUNCT) { + var val = token.val; + return val === '.' || val === '..'; + } + + return false; + } + + function matchSubst() { + var token = lookahead(); + return token.type === TOKEN.ID && token.val[0] === '$'; + } + + function expect(val) { + var token = lex(); + if(token.type !== TOKEN.PUNCT || token.val !== val) { + throwUnexpected(token); + } + } + + function lookahead() { + if(buf !== null) { + return buf; + } + + var pos = idx; + buf = advance(); + idx = pos; + + return buf; + } + + function advance() { + while(isWhiteSpace(path[idx])) { + ++idx; + } + + if(idx >= len) { + return { + type : TOKEN.EOP, + range : [idx, idx] + }; + } + + var token = scanPunctuator(); + if(token || + (token = scanId()) || + (token = scanString()) || + (token = scanNumeric())) { + return token; + } + + token = { range : [idx, idx] }; + idx >= len? + token.type = TOKEN.EOP : + token.val = path[idx]; + + throwUnexpected(token); + } + + function lex() { + var token; + + if(buf) { + idx = buf.range[1]; + token = buf; + buf = null; + return token; + } + + return advance(); + } + + function isDigit(ch) { + return '0123456789'.indexOf(ch) >= 0; + } + + function isWhiteSpace(ch) { + return ' \r\n\t'.indexOf(ch) > -1; + } + + function isIdStart(ch) { + return ch === '$' || ch === '@' || ch === '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); + } + + function isIdPart(ch) { + return isIdStart(ch) || (ch >= '0' && ch <= '9'); + } + + function scanId() { + var ch = path[idx]; + + if(!isIdStart(ch)) { + return; + } + + var start = idx, + id = ch; + + while(++idx < len) { + ch = path[idx]; + if(!isIdPart(ch)) { + break; + } + id += ch; + } + + switch(id) { + case 'true': + case 'false': + return { + type : TOKEN.BOOL, + val : id === 'true', + range : [start, idx] + }; + + case 'null': + return { + type : TOKEN.NULL, + val : null, + range : [start, idx] + }; + + default: + return { + type : TOKEN.ID, + val : id, + range : [start, idx] + }; + } + } + + function scanString() { + if(path[idx] !== '"' && path[idx] !== '\'') { + return; + } + + var orig = path[idx], + start = ++idx, + str = '', + eosFound = false, + ch; + + while(idx < len) { + ch = path[idx++]; + if(ch === '\\') { + ch = path[idx++]; + } + else if((ch === '"' || ch === '\'') && ch === orig) { + eosFound = true; + break; + } + str += ch; + } + + if(eosFound) { + return { + type : TOKEN.STR, + val : str, + range : [start, idx] + }; + } + } + + function scanNumeric() { + var start = idx, + ch = path[idx], + isFloat = ch === '.'; + + if(isFloat || isDigit(ch)) { + var num = ch; + while(++idx < len) { + ch = path[idx]; + if(ch === '.') { + if(isFloat) { + return; + } + isFloat = true; + } + else if(!isDigit(ch)) { + break; + } + + num += ch; + } + + return { + type : TOKEN.NUM, + val : isFloat? parseFloat(num) : parseInt(num, 10), + range : [start, idx] + }; + } + } + + function scanPunctuator() { + var start = idx, + ch1 = path[idx], + ch2 = path[idx + 1]; + + if(ch1 === '.') { + if(isDigit(ch2)) { + return; + } + + return path[++idx] === '.'? + { + type : TOKEN.PUNCT, + val : '..', + range : [start, ++idx] + } : + { + type : TOKEN.PUNCT, + val : '.', + range : [start, idx] + }; + } + + if(ch2 === '=') { + var ch3 = path[idx + 2]; + if(ch3 === '=') { + if('=!^$*'.indexOf(ch1) >= 0) { + return { + type : TOKEN.PUNCT, + val : ch1 + ch2 + ch3, + range : [start, idx += 3] + }; + } + } + else if('^$*'.indexOf(ch3) >= 0) { + if(ch1 === '=') { + return { + type : TOKEN.PUNCT, + val : ch1 + ch2 + ch3, + range : [start, idx += 3] + }; + } + } + else if('=!^$*><'.indexOf(ch1) >= 0) { + return { + type : TOKEN.PUNCT, + val : ch1 + ch2, + range : [start, idx += 2] + }; + } + } + else if(ch1 === '=' && '^$*'.indexOf(ch2) >= 0) { + return { + type : TOKEN.PUNCT, + val : ch1 + ch2, + range : [start, idx += 2] + }; + } + + if(ch1 === ch2 && (ch1 === '|' || ch1 === '&')) { + return { + type : TOKEN.PUNCT, + val : ch1 + ch2, + range : [start, idx += 2] + }; + } + + if(':{}()[]^+-*/%!><|'.indexOf(ch1) >= 0) { + return { + type : TOKEN.PUNCT, + val : ch1, + range : [start, ++idx] + }; + } + } + + function throwUnexpected(token) { + if(token.type === TOKEN.EOP) { + throwError(token, MESSAGES.UNEXP_EOP); + } + + throwError(token, MESSAGES.UNEXP_TOKEN, token.val); + } + + function throwError(token, messageFormat) { + var args = Array.prototype.slice.call(arguments, 2), + msg = messageFormat.replace( + /%(\d)/g, + function(_, idx) { + return args[idx] || ''; + }), + error = new Error(msg); + + error.column = token.range[0]; + + throw error; + } + + return parse; + })(); + + // translator + + var translate = (function() { + + var body, vars, lastVarId, unusedVars; + + function acquireVar() { + if(unusedVars.length) { + return unusedVars.shift(); + } + + var varName = 'v' + ++lastVarId; + vars.push(varName); + return varName; + } + + function releaseVars() { + var args = arguments, i = args.length; + while(i--) { + unusedVars.push(args[i]); + } + } + + function translate(ast) { + body = []; + vars = ['res']; + lastVarId = 0; + unusedVars = []; + + translateExpr(ast, 'res', 'data'); + + body.unshift( + 'var ', + Array.isArray? + 'isArr = Array.isArray' : + 'toStr = Object.prototype.toString, isArr = function(o) { return toStr.call(o) === "[object Array]"; }', + ', concat = Array.prototype.concat', + ',', vars.join(','), ';'); + + if(ast.type === SYNTAX.PATH) { + var lastPart = ast.parts[ast.parts.length - 1]; + if(lastPart && lastPart.type === SYNTAX.POS_PRED && 'idx' in lastPart.arg) { + body.push('res = res[0];'); + } + } + + body.push('return res;'); + + return body.join(''); + } + + function translatePath(path, dest, ctx) { + var parts = path.parts, + i = 0, len = parts.length; + + body.push( + dest, '=', path.fromRoot? 'data' : path.subst? 'subst.' + path.subst : ctx, ';', + 'isArr(' + dest + ') || (' + dest + ' = [' + dest + ']);'); + + while(i < len) { + var item = parts[i++]; + switch(item.type) { + case SYNTAX.SELECTOR: + item.selector === '..'? + translateDescendantSelector(item, dest, dest) : + translateSelector(item, dest, dest); + break; + + case SYNTAX.OBJ_PRED: + translateObjectPredicate(item, dest, dest); + break; + + case SYNTAX.POS_PRED: + translatePosPredicate(item, dest, dest); + break; + + case SYNTAX.CONCAT_EXPR: + translateConcatExpr(item, dest, dest); + break; + } + } + } + + function translateSelector(sel, dest, ctx) { + if(sel.prop) { + var propStr = escapeStr(sel.prop), + res = acquireVar(), i = acquireVar(), len = acquireVar(), + curCtx = acquireVar(), + j = acquireVar(), val = acquireVar(), tmpArr = acquireVar(); + + body.push( + res, '= [];', i, '= 0;', len, '=', ctx, '.length;', tmpArr, '= [];', + 'while(', i, '<', len, ') {', + curCtx, '=', ctx, '[', i, '++];', + 'if(', curCtx, '!= null) {'); + if(sel.prop === '*') { + body.push( + 'if(typeof ', curCtx, '=== "object") {', + 'if(isArr(', curCtx, ')) {', + res, '=', res, '.concat(', curCtx, ');', + '}', + 'else {', + 'for(', j, ' in ', curCtx, ') {', + 'if(', curCtx, '.hasOwnProperty(', j, ')) {', + val, '=', curCtx, '[', j, '];'); + inlineAppendToArray(res, val); + body.push( + '}', + '}', + '}', + '}'); + } + else { + body.push( + val, '=', curCtx, '[', propStr, '];'); + inlineAppendToArray(res, val, tmpArr, len); + } + body.push( + '}', + '}', + dest, '=', len, '> 1 &&', tmpArr, '.length?', tmpArr, '.length > 1?', + 'concat.apply(', res, ',', tmpArr, ') :', res, '.concat(', tmpArr, '[0]) :', res, ';'); + + releaseVars(res, i, len, curCtx, j, val, tmpArr); + } + } + + function translateDescendantSelector(sel, dest, baseCtx) { + var prop = sel.prop, + ctx = acquireVar(), curCtx = acquireVar(), childCtxs = acquireVar(), + i = acquireVar(), j = acquireVar(), val = acquireVar(), + len = acquireVar(), res = acquireVar(); + + body.push( + ctx, '=', baseCtx, '.slice(),', res, '= [];', + 'while(', ctx, '.length) {', + curCtx, '=', ctx, '.shift();'); + prop? + body.push( + 'if(typeof ', curCtx, '=== "object" &&', curCtx, ') {') : + body.push( + 'if(typeof ', curCtx, '!= null) {'); + body.push( + childCtxs, '= [];', + 'if(isArr(', curCtx, ')) {', + i, '= 0,', len, '=', curCtx, '.length;', + 'while(', i, '<', len, ') {', + val, '=', curCtx, '[', i, '++];'); + prop && body.push( + 'if(typeof ', val, '=== "object") {'); + inlineAppendToArray(childCtxs, val); + prop && body.push( + '}'); + body.push( + '}', + '}', + 'else {'); + if(prop) { + if(prop !== '*') { + body.push( + val, '=', curCtx, '["' + prop + '"];'); + inlineAppendToArray(res, val); + } + } + else { + inlineAppendToArray(res, curCtx); + body.push( + 'if(typeof ', curCtx, '=== "object") {'); + } + + body.push( + 'for(', j, ' in ', curCtx, ') {', + 'if(', curCtx, '.hasOwnProperty(', j, ')) {', + val, '=', curCtx, '[', j, '];'); + inlineAppendToArray(childCtxs, val); + prop === '*' && inlineAppendToArray(res, val); + body.push( + '}', + '}'); + prop || body.push( + '}'); + body.push( + '}', + childCtxs, '.length &&', ctx, '.unshift.apply(', ctx, ',', childCtxs, ');', + '}', + '}', + dest, '=', res, ';'); + + releaseVars(ctx, curCtx, childCtxs, i, j, val, len, res); + } + + function translateObjectPredicate(expr, dest, ctx) { + var resVar = acquireVar(), i = acquireVar(), len = acquireVar(), + cond = acquireVar(), curItem = acquireVar(); + + body.push( + resVar, '= [];', + i, '= 0;', + len, '=', ctx, '.length;', + 'while(', i, '<', len, ') {', + curItem, '=', ctx, '[', i, '++];'); + translateExpr(expr.arg, cond, curItem); + body.push( + convertToBool(expr.arg, cond), '&&', resVar, '.push(', curItem, ');', + '}', + dest, '=', resVar, ';'); + + releaseVars(resVar, i, len, curItem, cond); + } + + function translatePosPredicate(item, dest, ctx) { + var arrayExpr = item.arg, fromIdx, toIdx; + if(arrayExpr.idx) { + var idx = acquireVar(); + translateExpr(arrayExpr.idx, idx, ctx); + body.push( + idx, '< 0 && (', idx, '=', ctx, '.length +', idx, ');', + dest, '=', ctx, '[', idx, '] == null? [] : [', ctx, '[', idx, ']];'); + releaseVars(idx); + return false; + } + else if(arrayExpr.fromIdx) { + if(arrayExpr.toIdx) { + translateExpr(arrayExpr.fromIdx, fromIdx = acquireVar(), ctx); + translateExpr(arrayExpr.toIdx, toIdx = acquireVar(), ctx); + body.push(dest, '=', ctx, '.slice(', fromIdx, ',', toIdx, ');'); + releaseVars(fromIdx, toIdx); + } + else { + translateExpr(arrayExpr.fromIdx, fromIdx = acquireVar(), ctx); + body.push(dest, '=', ctx, '.slice(', fromIdx, ');'); + releaseVars(fromIdx); + } + } + else { + translateExpr(arrayExpr.toIdx, toIdx = acquireVar(), ctx); + body.push(dest, '=', ctx, '.slice(0,', toIdx, ');'); + releaseVars(toIdx); + } + } + + function translateExpr(expr, dest, ctx) { + switch(expr.type) { + case SYNTAX.PATH: + translatePath(expr, dest, ctx); + break; + + case SYNTAX.CONCAT_EXPR: + translateConcatExpr(expr, dest, ctx); + break; + + case SYNTAX.COMPARISON_EXPR: + translateComparisonExpr(expr, dest, ctx); + break; + + case SYNTAX.MATH_EXPR: + translateMathExpr(expr, dest, ctx); + break; + + case SYNTAX.LOGICAL_EXPR: + translateLogicalExpr(expr, dest, ctx); + break; + + case SYNTAX.UNARY_EXPR: + translateUnaryExpr(expr, dest, ctx); + break; + + case SYNTAX.LITERAL: + body.push(dest, '='); + translateLiteral(expr.val); + body.push(';'); + break; + } + } + + function translateLiteral(val) { + body.push(typeof val === 'string'? escapeStr(val) : val === null? 'null' : val); + } + + function translateComparisonExpr(expr, dest, ctx) { + var val1 = acquireVar(), val2 = acquireVar(), + isVal1Array = acquireVar(), isVal2Array = acquireVar(), + i = acquireVar(), j = acquireVar(), + len1 = acquireVar(), len2 = acquireVar(), + leftArg = expr.args[0], rightArg = expr.args[1]; + + body.push(dest, '= false;'); + + translateExpr(leftArg, val1, ctx); + translateExpr(rightArg, val2, ctx); + + var isLeftArgPath = leftArg.type === SYNTAX.PATH, + isRightArgLiteral = rightArg.type === SYNTAX.LITERAL; + + body.push(isVal1Array, '='); + isLeftArgPath? body.push('true;') : body.push('isArr(', val1, ');'); + + body.push(isVal2Array, '='); + isRightArgLiteral? body.push('false;') : body.push('isArr(', val2, ');'); + + body.push( + 'if('); + isLeftArgPath || body.push(isVal1Array, '&&'); + body.push(val1, '.length === 1) {', + val1, '=', val1, '[0];', + isVal1Array, '= false;', + '}'); + isRightArgLiteral || body.push( + 'if(', isVal2Array, '&&', val2, '.length === 1) {', + val2, '=', val2, '[0];', + isVal2Array, '= false;', + '}'); + + body.push(i, '= 0;', + 'if(', isVal1Array, ') {', + len1, '=', val1, '.length;'); + + if(!isRightArgLiteral) { + body.push( + 'if(', isVal2Array, ') {', + len2, '=', val2, '.length;', + 'while(', i, '<', len1, '&& !', dest, ') {', + j, '= 0;', + 'while(', j, '<', len2, ') {'); + writeCondition(expr.op, [val1, '[', i, ']'].join(''), [val2, '[', j, ']'].join('')); + body.push( + dest, '= true;', + 'break;', + '}', + '++', j, ';', + '}', + '++', i, ';', + '}', + '}', + 'else {'); + } + body.push( + 'while(', i, '<', len1, ') {'); + writeCondition(expr.op, [val1, '[', i, ']'].join(''), val2); + body.push( + dest, '= true;', + 'break;', + '}', + '++', i, ';', + '}'); + + isRightArgLiteral || body.push( + '}'); + + body.push( + '}'); + + if(!isRightArgLiteral) { + body.push( + 'else if(', isVal2Array,') {', + len2, '=', val2, '.length;', + 'while(', i, '<', len2, ') {'); + writeCondition(expr.op, val1, [val2, '[', i, ']'].join('')); + body.push( + dest, '= true;', + 'break;', + '}', + '++', i, ';', + '}', + '}'); + } + + body.push( + 'else {', + dest, '=', binaryOperators[expr.op](val1, val2), ';', + '}'); + + releaseVars(val1, val2, isVal1Array, isVal2Array, i, j, len1, len2); + } + + function writeCondition(op, val1Expr, val2Expr) { + body.push('if(', binaryOperators[op](val1Expr, val2Expr), ') {'); + } + + function translateLogicalExpr(expr, dest, ctx) { + var conditionVars = [], + args = expr.args, len = args.length, + i = 0, val; + + body.push(dest, '= false;'); + switch(expr.op) { + case '&&': + while(i < len) { + conditionVars.push(val = acquireVar()); + translateExpr(args[i], val, ctx); + body.push('if(', convertToBool(args[i++], val), ') {'); + } + body.push(dest, '= true;'); + break; + + case '||': + while(i < len) { + conditionVars.push(val = acquireVar()); + translateExpr(args[i], val, ctx); + body.push( + 'if(', convertToBool(args[i], val), ') {', + dest, '= true;', + '}'); + if(i++ + 1 < len) { + body.push('else {'); + } + } + --len; + break; + } + + while(len--) { + body.push('}'); + } + + releaseVars.apply(null, conditionVars); + } + + function translateMathExpr(expr, dest, ctx) { + var val1 = acquireVar(), + val2 = acquireVar(), + args = expr.args; + + translateExpr(args[0], val1, ctx); + translateExpr(args[1], val2, ctx); + + body.push( + dest, '=', + binaryOperators[expr.op]( + convertToSingleValue(args[0], val1), + convertToSingleValue(args[1], val2)), + ';'); + + releaseVars(val1, val2); + } + + function translateUnaryExpr(expr, dest, ctx) { + var val = acquireVar(), + arg = expr.arg; + + translateExpr(arg, val, ctx); + + switch(expr.op) { + case '!': + body.push(dest, '= !', convertToBool(arg, val) + ';'); + break; + + case '-': + body.push(dest, '= -', convertToSingleValue(arg, val) + ';'); + break; + } + + releaseVars(val); + } + + function translateConcatExpr(expr, dest, ctx) { + var argVars = [], + args = expr.args, + len = args.length, + i = 0; + + while(i < len) { + argVars.push(acquireVar()); + translateExpr(args[i], argVars[i++], ctx); + } + + body.push(dest, '= concat.call(', argVars.join(','), ');'); + + releaseVars.apply(null, argVars); + } + + function escapeStr(s) { + return '\'' + s.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + '\''; + } + + function inlineAppendToArray(res, val, tmpArr, len) { + body.push( + 'if(typeof ', val, '!== "undefined") {', + 'if(isArr(', val, ')) {'); + if(tmpArr) { + body.push( + len, '> 1?'); + inlinePushToArray(tmpArr, val); + body.push( + ':'); + } + body.push( + res, '=', res, '.length?', res, '.concat(', val, ') :', val, '.slice()', ';', + '}', + 'else {'); + tmpArr && body.push( + 'if(', tmpArr, '.length) {', + res, '= concat.apply(', res, ',', tmpArr, ');', + tmpArr, '= [];', + '}'); + inlinePushToArray(res, val); + body.push(';', + '}', + '}'); + } + + function inlinePushToArray(res, val) { + body.push(res, '.length?', res, '.push(', val, ') :', res, '[0] =', val); + } + + function convertToBool(arg, varName) { + switch(arg.type) { + case SYNTAX.LOGICAL_EXPR: + return varName; + + case SYNTAX.LITERAL: + return '!!' + varName; + + case SYNTAX.PATH: + return varName + '.length > 0'; + + default: + return ['(typeof ', varName, '=== "boolean"?', + varName, ':', + 'isArr(', varName, ')?', varName, '.length > 0 : !!', varName, ')'].join(''); + } + } + + function convertToSingleValue(arg, varName) { + switch(arg.type) { + case SYNTAX.LITERAL: + return varName; + + case SYNTAX.PATH: + return varName + '[0]'; + + default: + return ['(isArr(', varName, ')?', varName, '[0] : ', varName, ')'].join(''); + } + } + + function startsWithStrict(val1, val2) { + return ['typeof ', val1, '=== "string" && typeof ', val2, '=== "string" &&', + val1, '.indexOf(', val2, ') === 0'].join(''); + } + + function startsWith(val1, val2) { + return [val1, '!= null &&', val2, '!= null &&', + val1, '.toString().toLowerCase().indexOf(', val2, '.toString().toLowerCase()) === 0'].join(''); + } + + function endsWithStrict(val1, val2) { + return ['typeof ', val1, '=== "string" && typeof ', val2, '=== "string" &&', + val1, '.length >=', val2, '.length &&', + val1, '.lastIndexOf(', val2, ') ===', val1, '.length -', val2, '.length'].join(''); + } + + function endsWith(val1, val2) { + return [val1, '!= null &&', val2, '!= null &&', + '(', val1, '=', val1, '.toString()).length >=', '(', val2, '=', val2, '.toString()).length &&', + '(', val1, '.toLowerCase()).lastIndexOf(', '(', val2, '.toLowerCase())) ===', + val1, '.length -', val2, '.length'].join(''); + } + + function containsStrict(val1, val2) { + return ['typeof ', val1, '=== "string" && typeof ', val2, '=== "string" &&', + val1, '.indexOf(', val2, ') > -1'].join(''); + } + + function contains(val1, val2) { + return [val1, '!= null && ', val2, '!= null &&', + val1, '.toString().toLowerCase().indexOf(', val2, '.toString().toLowerCase()) > -1'].join(''); + } + + var binaryOperators = { + '===' : function(val1, val2) { + return val1 + '===' + val2; + }, + + '==' : function(val1, val2) { + return ['typeof ', val1, '=== "string" && typeof ', val2, '=== "string"?', + val1, '.toLowerCase() ===', val2, '.toLowerCase() :' + + val1, '==', val2].join(''); + }, + + '>=' : function(val1, val2) { + return val1 + '>=' + val2; + }, + + '>' : function(val1, val2) { + return val1 + '>' + val2; + }, + + '<=' : function(val1, val2) { + return val1 + '<=' + val2; + }, + + '<' : function(val1, val2) { + return val1 + '<' + val2; + }, + + '!==' : function(val1, val2) { + return val1 + '!==' + val2; + }, + + '!=' : function(val1, val2) { + return val1 + '!=' + val2; + }, + + '^==' : startsWithStrict, + + '==^' : function(val1, val2) { + return startsWithStrict(val2, val1); + }, + + '^=' : startsWith, + + '=^' : function(val1, val2) { + return startsWith(val2, val1); + }, + + '$==' : endsWithStrict, + + '==$' : function(val1, val2) { + return endsWithStrict(val2, val1); + }, + + '$=' : endsWith, + + '=$' : function(val1, val2) { + return endsWith(val2, val1); + }, + + '*==' : containsStrict, + + '==*' : function(val1, val2) { + return containsStrict(val2, val1); + }, + + '=*' : function(val1, val2) { + return contains(val2, val1); + }, + + '*=' : contains, + + '+' : function(val1, val2) { + return val1 + '+' + val2; + }, + + '-' : function(val1, val2) { + return val1 + '-' + val2; + }, + + '*' : function(val1, val2) { + return val1 + '*' + val2; + }, + + '/' : function(val1, val2) { + return val1 + '/' + val2; + }, + + '%' : function(val1, val2) { + return val1 + '%' + val2; + } + }; + + return translate; + })(); + + function compile(path) { + return Function('data,subst', translate(parse(path))); + } + + var cache = {}, + cacheKeys = [], + params = { + cacheSize : 100 + }, + setParamsHooks = { + cacheSize : function(oldVal, newVal) { + if(newVal < oldVal && cacheKeys.length > newVal) { + var removedKeys = cacheKeys.splice(0, cacheKeys.length - newVal), + i = removedKeys.length; + + while(i--) { + delete cache[removedKeys[i]]; + } + } + } + }; + + var decl = function(path, ctx, substs) { + if(!cache[path]) { + cache[path] = compile(path); + if(cacheKeys.push(path) > params.cacheSize) { + delete cache[cacheKeys.shift()]; + } + } + + return cache[path](ctx, substs || {}); + }; + + decl.version = '0.3.4'; + + decl.params = function(_params) { + if(!arguments.length) { + return params; + } + + for(var name in _params) { + if(_params.hasOwnProperty(name)) { + setParamsHooks[name] && setParamsHooks[name](params[name], _params[name]); + params[name] = _params[name]; + } + } + }; + + decl.compile = compile; + + decl.apply = decl; + + { + module.exports = decl; + } + + })(); + } (jspath$1)); + return jspath$1.exports; +} + +var jspath; +var hasRequiredJspath; + +function requireJspath () { + if (hasRequiredJspath) return jspath; + hasRequiredJspath = 1; + jspath = requireJspath$1(); + return jspath; +} + +var hasRequiredJPath; + +function requireJPath () { + if (hasRequiredJPath) return jPath; + hasRequiredJPath = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __createBinding = (jPath && jPath.__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 = (jPath && jPath.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = (jPath && jPath.__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(jPath, "__esModule", { value: true }); + jPath.JPath = void 0; + const jsPath = __importStar(requireJspath()); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Check JSON or a JSON string for nodes or values that match a path expression, and return the matching nodes. + */ + class JPath extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [JPath](xref:adaptive-expressions.JPath) class. + */ + constructor() { + super(expressionType_1.ExpressionType.JPath, JPath.evaluator(), returnType_1.ReturnType.Object, JPath.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => JPath.evalJPath(args[0], args[1].toString())); + } + /** + * @private + */ + static evalJPath(jsonEntity, path) { + let error; + let evaled; + let json; + if (typeof jsonEntity === 'string') { + try { + json = JSON.parse(jsonEntity); + } + catch (_a) { + error = `${jsonEntity} is not a valid json string`; + } + } + else if (typeof jsonEntity === 'object') { + json = jsonEntity; + } + else { + error = 'the first parameter should be either an object or a string'; + } + if (!error) { + try { + evaled = jsPath.apply(path, json); + } + catch (e) { + error = `${path} is not a valid path + ${e}`; + } + } + return { value: evaled, error }; + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, undefined, returnType_1.ReturnType.Object, returnType_1.ReturnType.String); + } + } + jPath.JPath = JPath; + + return jPath; +} + +var json = {}; + +var hasRequiredJson; + +function requireJson () { + if (hasRequiredJson) return json; + hasRequiredJson = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(json, "__esModule", { value: true }); + json.Json = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the JavaScript Object Notation (JSON) type value or object of a string or XML. + */ + class Json extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Json](xref:adaptive-expressions.Json) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Json, Json.evaluator(), returnType_1.ReturnType.Object, Json.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => JSON.parse(args[0].trim())); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.String); + } + } + json.Json = Json; + + return json; +} + +var jsonStringify = {}; + +var hasRequiredJsonStringify; + +function requireJsonStringify () { + if (hasRequiredJsonStringify) return jsonStringify; + hasRequiredJsonStringify = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(jsonStringify, "__esModule", { value: true }); + jsonStringify.JsonStringify = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the string version of a value. + */ + class JsonStringify extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [JsonStringify](xref:adaptive-expressions.JsonStringify) class. + */ + constructor() { + super(expressionType_1.ExpressionType.JsonStringify, JsonStringify.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + return JSON.stringify(args[0]); + }); + } + } + jsonStringify.JsonStringify = JsonStringify; + + return jsonStringify; +} + +var last = {}; + +var hasRequiredLast; + +function requireLast () { + if (hasRequiredLast) return last; + hasRequiredLast = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(last, "__esModule", { value: true }); + last.Last = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the last item from a collection. + */ + class Last extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Last](xref:adaptive-expressions.Last) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Last, Last.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let last; + if (typeof args[0] === 'string' && args[0].length > 0) { + last = args[0][args[0].length - 1]; + } + if (Array.isArray(args[0]) && args[0].length > 0) { + last = functionUtils_internal_1.InternalFunctionUtils.accessIndex(args[0], args[0].length - 1).value; + } + return last; + }); + } + } + last.Last = Last; + + return last; +} + +var lastIndexOf = {}; + +var hasRequiredLastIndexOf; + +function requireLastIndexOf () { + if (hasRequiredLastIndexOf) return lastIndexOf; + hasRequiredLastIndexOf = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(lastIndexOf, "__esModule", { value: true }); + lastIndexOf.LastIndexOf = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Returns the index of the last occurrence of a specified value in an array. + * The zero-based index position of value if that value is found, or -1 if it is not. + */ + class LastIndexOf extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [LastIndexOf](xref:adaptive-expressions.LastIndexOf) class. + */ + constructor() { + super(expressionType_1.ExpressionType.LastIndexOf, LastIndexOf.evaluator, returnType_1.ReturnType.Number, LastIndexOf.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value = -1; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (args[0] == null || typeof args[0] === 'string') { + if (args[1] === undefined || typeof args[1] === 'string') { + const str = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]); + const searchValue = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1]); + value = str.lastIndexOf(searchValue, str.length - 1); + } + else { + error = `Can only look for indexof string in ${expression}`; + } + } + else if (Array.isArray(args[0])) { + value = args[0].lastIndexOf(args[1]); + } + else { + error = `${expression} works only on string or list.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.String | returnType_1.ReturnType.Array, returnType_1.ReturnType.Object); + } + } + lastIndexOf.LastIndexOf = LastIndexOf; + + return lastIndexOf; +} + +var length = {}; + +var hasRequiredLength; + +function requireLength () { + if (hasRequiredLength) return length; + hasRequiredLength = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(length, "__esModule", { value: true }); + length.Length = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the length of a string. + */ + class Length extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Length](xref:adaptive-expressions.Length) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Length, Length.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).length, functionUtils_1.FunctionUtils.verifyStringOrNull); + } + } + length.Length = Length; + + return length; +} + +var lessThan = {}; + +var hasRequiredLessThan; + +function requireLessThan () { + if (hasRequiredLessThan) return lessThan; + hasRequiredLessThan = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(lessThan, "__esModule", { value: true }); + lessThan.LessThan = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether the first value is less than the second value. + * Return true if the first value is less, or return false if the first value is more. + */ + class LessThan extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [LessThan](xref:adaptive-expressions.LessThan) class. + */ + constructor() { + super(expressionType_1.ExpressionType.LessThan, LessThan.func, functionUtils_1.FunctionUtils.validateBinary, functionUtils_1.FunctionUtils.verifyNotNull); + } + /** + * @private + */ + static func(args) { + if ((functionUtils_1.FunctionUtils.isNumber(args[0]) && functionUtils_1.FunctionUtils.isNumber(args[1])) || + (typeof args[0] === 'string' && typeof args[1] === 'string') || + (args[0] instanceof Date && args[1] instanceof Date)) { + return args[0] < args[1]; + } + else { + throw new Error(`${args[0]} and ${args[1]} must be comparable.`); + } + } + } + lessThan.LessThan = LessThan; + + return lessThan; +} + +var lessThanOrEqual = {}; + +var hasRequiredLessThanOrEqual; + +function requireLessThanOrEqual () { + if (hasRequiredLessThanOrEqual) return lessThanOrEqual; + hasRequiredLessThanOrEqual = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(lessThanOrEqual, "__esModule", { value: true }); + lessThanOrEqual.LessThanOrEqual = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Check whether the first value is less than or equal to the second value. + * Return true if the first value is less than or equal, or return false if the first value is more. + */ + class LessThanOrEqual extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [LessThanOrEqual](xref:adaptive-expressions.LessThanOrEqual) class. + */ + constructor() { + super(expressionType_1.ExpressionType.LessThanOrEqual, LessThanOrEqual.func, functionUtils_1.FunctionUtils.validateBinary, functionUtils_1.FunctionUtils.verifyNotNull); + } + /** + * @private + */ + static func(args) { + if ((functionUtils_1.FunctionUtils.isNumber(args[0]) && functionUtils_1.FunctionUtils.isNumber(args[1])) || + (typeof args[0] === 'string' && typeof args[1] === 'string') || + (args[0] instanceof Date && args[1] instanceof Date)) { + return args[0] <= args[1]; + } + else { + throw new Error(`${args[0]} and ${args[1]} must be comparable.`); + } + } + } + lessThanOrEqual.LessThanOrEqual = LessThanOrEqual; + + return lessThanOrEqual; +} + +var max$1 = {}; + +var hasRequiredMax; + +function requireMax () { + if (hasRequiredMax) return max$1; + hasRequiredMax = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(max$1, "__esModule", { value: true }); + max$1.Max = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the highest value from an array. The array is inclusive at both ends. + */ + class Max extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Max](xref:adaptive-expressions.Max) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Max, Max.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let result = Number.NEGATIVE_INFINITY; + if (args.length === 1) { + if (Array.isArray(args[0])) { + for (const value of args[0]) { + result = Math.max(result, value); + } + } + else { + result = Math.max(result, args[0]); + } + } + else { + for (const arg of args) { + if (Array.isArray(arg)) { + for (const value of arg) { + result = Math.max(result, value); + } + } + else { + result = Math.max(result, arg); + } + } + } + return result; + }, functionUtils_1.FunctionUtils.verifyNumberOrNumericList); + } + } + max$1.Max = Max; + + return max$1; +} + +var merge = {}; + +var hasRequiredMerge; + +function requireMerge () { + if (hasRequiredMerge) return merge; + hasRequiredMerge = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(merge, "__esModule", { value: true }); + merge.Merge = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Merge multiple object(json) into one object(json). + * If the item is array, the elements of the array are merged as well. + */ + class Merge extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Merge](xref:adaptive-expressions.Merge) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Merge, Merge.evaluator(), returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const result = {}; + for (const arg of args) { + const objectResult = this.parseToObjectList(arg); + if (objectResult.error != null) { + return { value: undefined, error: objectResult.error }; + } + for (const item of objectResult.result) { + Object.assign(result, item); + } + } + return { value: result, error: undefined }; + }); + } + static parseToObjectList(arg) { + const result = []; + let error; + if (arg == null) { + error = `The argument ${arg} must be a JSON object or array.`; + } + else if (Array.isArray(arg)) { + for (const item of arg) { + if (typeof item === 'object' && !Array.isArray(item)) { + result.push(item); + } + else { + error = `The argument ${item} in array must be a JSON object.`; + } + } + } + else if (typeof arg === 'object') { + result.push(arg); + } + else { + error = `The argument ${arg} must be a JSON object or array.`; + } + return { result: result, error: error }; + } + } + merge.Merge = Merge; + + return merge; +} + +var min = {}; + +var hasRequiredMin; + +function requireMin () { + if (hasRequiredMin) return min; + hasRequiredMin = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(min, "__esModule", { value: true }); + min.Min = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the lowest value from a set of numbers in an array. + */ + class Min extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Min](xref:adaptive-expressions.Min) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Min, Min.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let result = Number.POSITIVE_INFINITY; + if (args.length === 1) { + if (Array.isArray(args[0])) { + for (const value of args[0]) { + result = Math.min(result, value); + } + } + else { + result = Math.min(result, args[0]); + } + } + else { + for (const arg of args) { + if (Array.isArray(arg)) { + for (const value of arg) { + result = Math.min(result, value); + } + } + else { + result = Math.min(result, arg); + } + } + } + return result; + }, functionUtils_1.FunctionUtils.verifyNumberOrNumericList); + } + } + min.Min = Min; + + return min; +} + +var mod = {}; + +var hasRequiredMod; + +function requireMod () { + if (hasRequiredMod) return mod; + hasRequiredMod = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(mod, "__esModule", { value: true }); + mod.Mod = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the remainder from dividing two numbers. + */ + class Mod extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Mod](xref:adaptive-expressions.Mod) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Mod, Mod.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateBinaryNumber); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error; + let value; + if (Number(args[1]) === 0) { + error = 'Cannot mod by 0.'; + } + else { + value = args[0] % args[1]; + } + return { value, error }; + }, functionUtils_1.FunctionUtils.verifyInteger); + } + } + mod.Mod = Mod; + + return mod; +} + +var month = {}; + +var hasRequiredMonth; + +function requireMonth () { + if (hasRequiredMonth) return month; + hasRequiredMonth = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(month, "__esModule", { value: true }); + month.Month = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the month of the specified timestamp. + */ + class Month extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Month](xref:adaptive-expressions.Month) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Month, Month.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + return { value: new Date(args[0]).getUTCMonth() + 1, error }; + } + return { value: undefined, error }; + }, functionUtils_1.FunctionUtils.verifyString); + } + } + month.Month = Month; + + return month; +} + +var multiply = {}; + +var hasRequiredMultiply; + +function requireMultiply () { + if (hasRequiredMultiply) return multiply; + hasRequiredMultiply = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(multiply, "__esModule", { value: true }); + multiply.Multiply = void 0; + const expressionType_1 = requireExpressionType(); + const multivariateNumericEvaluator_1 = requireMultivariateNumericEvaluator(); + /** + * Return the product from multiplying any number of numbers. + */ + class Multiply extends multivariateNumericEvaluator_1.MultivariateNumericEvaluator { + /** + * Initializes a new instance of the [Multiply](xref:adaptive-expressions.Multiply) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Multiply, Multiply.func); + } + /** + * @private + */ + static func(args) { + return Number(args[0]) * Number(args[1]); + } + } + multiply.Multiply = Multiply; + + return multiply; +} + +var newGuid = {}; + +var max = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; + +var nil = '00000000-0000-0000-0000-000000000000'; + +var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + var v; + var arr = new Uint8Array(16); + + // Parse ########-....-....-....-............ + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; + + // Parse ........-####-....-....-............ + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; + + // Parse ........-....-####-....-............ + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; + + // Parse ........-....-....-####-............ + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; + + // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + // + // Note to future-self: No, you can't remove the `toLowerCase()` call. + // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 + return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + var uuid = unsafeStringify(arr, offset); + // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} + +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). + +var getRandomValues; +var rnds8 = new Uint8Array(16); +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + return getRandomValues(rnds8); +} + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || new Array(16); + options = options || {}; + var node = options.node; + var clockseq = options.clockseq; + + // v1 only: Use cached `node` and `clockseq` values + if (!options._v6) { + if (!node) { + node = _nodeId; + } + if (clockseq == null) { + clockseq = _clockseq; + } + } + + // Handle cases where we need entropy. We do this lazily to minimize issues + // related to insufficient system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || rng)(); + + // Randomize node + if (node == null) { + node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + + // v1 only: cache node value for reuse + if (!_nodeId && !options._v6) { + // per RFC4122 4.5: Set MAC multicast bit (v1 only) + node[0] |= 0x01; // Set multicast bit + + _nodeId = node; + } + } + + // Randomize clockseq + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + if (_clockseq === undefined && !options._v6) { + _clockseq = clockseq; + } + } + } + + // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is + // handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : Date.now(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + return buf || unsafeStringify(b); +} + +/** + * Convert a v1 UUID to a v6 UUID + * + * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 + * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg + * (string or Uint8Array) + */ +function v1ToV6(uuid) { + var v1Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + var v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? unsafeStringify(v6Bytes) : v6Bytes; +} + +// Do the field transformation needed for v1 -> v6 +function _v1ToV6(v1Bytes, randomize = false) { + return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + var bytes = []; + for (var i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + return bytes; +} +var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === 'string') { + value = stringToBytes(value); + } + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + + // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + if (buf) { + offset = offset || 0; + for (var i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); + } + + // Function#name is not settable on some platforms (#270) + try { + generateUUID.name = name; + } catch (err) {} + + // For CommonJS default export support + generateUUID.DNS = DNS; + generateUUID.URL = URL$1; + return generateUUID; +} + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + for (var i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} + +/* + * Convert an array of little-endian words to an array of bytes + */ +function md5ToHexEncodedArray(input) { + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + for (var i = 0; i < length32; i += 8) { + var x = input[i >> 5] >>> i % 32 & 0xff; + var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + return output; +} + +/** + * Calculate output length with padding and bit length + */ +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return [a, b, c, d]; +} + +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + var length8 = input.length * 8; + var output = new Uint32Array(getOutputLength(length8)); + for (var i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + return output; +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safeAdd(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var v3 = v35('v3', 0x30, md5); + +var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var native = { + randomUUID +}; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + offset = offset || 0; + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + case 1: + return x ^ y ^ z; + case 2: + return x & y ^ x & z ^ y & z; + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + for (var i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); + for (var _i = 0; _i < N; ++_i) { + var arr = new Uint32Array(16); + for (var j = 0; j < 16; ++j) { + arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; + } + M[_i] = arr; + } + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + for (var _i2 = 0; _i2 < N; ++_i2) { + var W = new Uint32Array(80); + for (var t = 0; t < 16; ++t) { + W[t] = M[_i2][t]; + } + for (var _t = 16; _t < 80; ++_t) { + W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); + } + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s = Math.floor(_t2 / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var v5 = v35('v5', 0x50, sha1); + +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; } +function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } +function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } + +/** + * + * @param {object} options + * @param {Uint8Array=} buf + * @param {number=} offset + * @returns + */ +function v6(options = {}, buf, offset = 0) { + // v6 is v1 with different field layout, so we start with a v1 UUID, albeit + // with slightly different behavior around how the clock_seq and node fields + // are randomized, which is why we call v1 with _v6: true. + var bytes = v1(_objectSpread(_objectSpread({}, options), {}, { + _v6: true + }), new Uint8Array(16)); + + // Reorder the fields to v6 layout. + bytes = v1ToV6(bytes); + + // Return as a byte array if requested + if (buf) { + for (var i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} + +/** + * Convert a v6 UUID to a v1 UUID + * + * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 + * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg + * (string or Uint8Array) + */ +function v6ToV1(uuid) { + var v6Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + var v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? unsafeStringify(v1Bytes) : v1Bytes; +} + +// Do the field transformation needed for v6 -> v1 +function _v6ToV1(v6Bytes) { + return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} + +/** + * UUID V7 - Unix Epoch time-based UUID + * + * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This + * implementation of V7 is based on the accepted, though not yet approved, + * revisions. + * + * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique + * IDentifiers (UUIDs) + + * + * Sample V7 value: + * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value + * + * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: + * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 + * + * 0 1 2 3 0 1 2 3 4 5 6 + * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | unix_ts_ms | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | unix_ts_ms | ver | seq_hi | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * |var| seq_low | rand | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | rand | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit + * seq_low, and randomly initialized upon timestamp change. 31 bit counter size + * was selected as any bitwise operations in node are done as _signed_ 32 bit + * ints. we exclude the sign bit. + */ + +var _seqLow = null; +var _seqHigh = null; +var _msecs = 0; +function v7(options, buf, offset) { + options = options || {}; + + // initialize buffer and pointer + var i = buf && offset || 0; + var b = buf || new Uint8Array(16); + + // rnds is Uint8Array(16) filled with random bytes + var rnds = options.random || (options.rng || rng)(); + + // milliseconds since unix epoch, 1970-01-01 00:00 + var msecs = options.msecs !== undefined ? options.msecs : Date.now(); + + // seq is user provided 31 bit counter + var seq = options.seq !== undefined ? options.seq : null; + + // initialize local seq high/low parts + var seqHigh = _seqHigh; + var seqLow = _seqLow; + + // check if clock has advanced and user has not provided msecs + if (msecs > _msecs && options.msecs === undefined) { + _msecs = msecs; + + // unless user provided seq, reset seq parts + if (seq !== null) { + seqHigh = null; + seqLow = null; + } + } + + // if we have a user provided seq + if (seq !== null) { + // trim provided seq to 31 bits of value, avoiding overflow + if (seq > 0x7fffffff) { + seq = 0x7fffffff; + } + + // split provided seq into high/low parts + seqHigh = seq >>> 19 & 0xfff; + seqLow = seq & 0x7ffff; + } + + // randomly initialize seq + if (seqHigh === null || seqLow === null) { + seqHigh = rnds[6] & 0x7f; + seqHigh = seqHigh << 8 | rnds[7]; + seqLow = rnds[8] & 0x3f; // pad for var + seqLow = seqLow << 8 | rnds[9]; + seqLow = seqLow << 5 | rnds[10] >>> 3; + } + + // increment seq if within msecs window + if (msecs + 10000 > _msecs && seq === null) { + if (++seqLow > 0x7ffff) { + seqLow = 0; + if (++seqHigh > 0xfff) { + seqHigh = 0; + + // increment internal _msecs. this allows us to continue incrementing + // while staying monotonic. Note, once we hit 10k milliseconds beyond system + // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) + _msecs++; + } + } + } else { + // resetting; we have advanced more than + // 10k milliseconds beyond system clock + _msecs = msecs; + } + _seqHigh = seqHigh; + _seqLow = seqLow; + + // [bytes 0-5] 48 bits of local timestamp + b[i++] = _msecs / 0x10000000000 & 0xff; + b[i++] = _msecs / 0x100000000 & 0xff; + b[i++] = _msecs / 0x1000000 & 0xff; + b[i++] = _msecs / 0x10000 & 0xff; + b[i++] = _msecs / 0x100 & 0xff; + b[i++] = _msecs & 0xff; + + // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi + b[i++] = seqHigh >>> 4 & 0x0f | 0x70; + + // [byte 7] remaining 8 bits of seq_hi + b[i++] = seqHigh & 0xff; + + // [byte 8] - variant (2 bits), first 6 bits seq_low + b[i++] = seqLow >>> 13 & 0x3f | 0x80; + + // [byte 9] 8 bits seq_low + b[i++] = seqLow >>> 5 & 0xff; + + // [byte 10] remaining 5 bits seq_low, 3 bits random + b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; + + // [bytes 11-15] always random + b[i++] = rnds[11]; + b[i++] = rnds[12]; + b[i++] = rnds[13]; + b[i++] = rnds[14]; + b[i++] = rnds[15]; + return buf || unsafeStringify(b); +} + +function version$1(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} + +var esmBrowser = /*#__PURE__*/Object.freeze({ + __proto__: null, + MAX: max, + NIL: nil, + parse: parse, + stringify: stringify, + v1: v1, + v1ToV6: v1ToV6, + v3: v3, + v4: v4, + v5: v5, + v6: v6, + v6ToV1: v6ToV1, + v7: v7, + validate: validate, + version: version$1 +}); + +var require$$0 = /*@__PURE__*/getAugmentedNamespace(esmBrowser); + +var hasRequiredNewGuid; + +function requireNewGuid () { + if (hasRequiredNewGuid) return newGuid; + hasRequiredNewGuid = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(newGuid, "__esModule", { value: true }); + newGuid.NewGuid = void 0; + const uuid_1 = require$$0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return a new Guid string. + */ + class NewGuid extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [NewGuid](xref:adaptive-expressions.NewGuid) class. + */ + constructor() { + super(expressionType_1.ExpressionType.NewGuid, NewGuid.evaluator(), returnType_1.ReturnType.String, NewGuid.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply(() => NewGuid.evalNewGuid()); + } + /** + * @private + */ + static evalNewGuid() { + return (0, uuid_1.v4)(); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 0, 0); + } + } + newGuid.NewGuid = NewGuid; + + return newGuid; +} + +var not = {}; + +var hasRequiredNot; + +function requireNot () { + if (hasRequiredNot) return not; + hasRequiredNot = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(not, "__esModule", { value: true }); + not.Not = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const options_1 = requireOptions(); + const returnType_1 = requireReturnType(); + /** + * Check whether an expression is false. + * Return true if the expression is false, or return false if true. + */ + class Not extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Not](xref:adaptive-expressions.Not) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Not, Not.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = false; + let error; + const newOptions = new options_1.Options(options); + newOptions.nullSubstitution = undefined; + ({ value: result, error } = expression.children[0].tryEvaluate(state, newOptions)); + if (!error) { + result = !functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(result); + } + else { + error = undefined; + result = true; + } + return { value: result, error }; + } + } + not.Not = Not; + + return not; +} + +var notEqual = {}; + +var hasRequiredNotEqual; + +function requireNotEqual () { + if (hasRequiredNotEqual) return notEqual; + hasRequiredNotEqual = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(notEqual, "__esModule", { value: true }); + notEqual.NotEqual = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const comparisonEvaluator_1 = requireComparisonEvaluator(); + /** + * Return true if the two items are not equal. + */ + class NotEqual extends comparisonEvaluator_1.ComparisonEvaluator { + /** + * Initializes a new instance of the [NotEqual](xref:adaptive-expressions.NotEqual) class. + */ + constructor() { + super(expressionType_1.ExpressionType.NotEqual, (args) => !functionUtils_1.FunctionUtils.commonEquals(args[0], args[1]), functionUtils_1.FunctionUtils.validateBinary); + } + } + notEqual.NotEqual = NotEqual; + + return notEqual; +} + +var numericEvaluator = {}; + +var hasRequiredNumericEvaluator; + +function requireNumericEvaluator () { + if (hasRequiredNumericEvaluator) return numericEvaluator; + hasRequiredNumericEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(numericEvaluator, "__esModule", { value: true }); + numericEvaluator.NumericEvaluator = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Numeric operators that can have 1 or more args. + */ + class NumericEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [NumericEvaluator](xref:adaptive-expressions.NumericEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The evaluation function, it takes a list of objects and returns a number. + */ + constructor(type, func) { + super(type, NumericEvaluator.evaluator(func), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateNumber); + } + /** + * @private + */ + static evaluator(func) { + return functionUtils_1.FunctionUtils.applySequence(func, functionUtils_1.FunctionUtils.verifyNumber); + } + } + numericEvaluator.NumericEvaluator = NumericEvaluator; + + return numericEvaluator; +} + +var optional = {}; + +var hasRequiredOptional; + +function requireOptional () { + if (hasRequiredOptional) return optional; + hasRequiredOptional = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(optional, "__esModule", { value: true }); + optional.Optional = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * For the MostSpecificSelector, this is a short hand so that instead of having to do A & B || A you can do A & optional(B) to mean the same thing. + */ + class Optional extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Optional](xref:adaptive-expressions.Optional) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Optional, Optional.evaluator(), returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateUnaryBoolean); + this.negation = this; + } + /** + * @private + */ + static evaluator() { + return undefined; + } + } + optional.Optional = Optional; + + return optional; +} + +var or = {}; + +var hasRequiredOr; + +function requireOr () { + if (hasRequiredOr) return or; + hasRequiredOr = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(or, "__esModule", { value: true }); + or.Or = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const options_1 = requireOptions(); + const returnType_1 = requireReturnType(); + /** + * Check whether at least one expression is true. + * Return true if at least one expression is true, or return false if all are false. + */ + class Or extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Or](xref:adaptive-expressions.Or) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Or, Or.evaluator, returnType_1.ReturnType.Boolean, functionUtils_1.FunctionUtils.validateAtLeastOne); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result = false; + let error; + for (const child of expression.children) { + const newOptions = new options_1.Options(options); + newOptions.nullSubstitution = undefined; + ({ value: result, error } = child.tryEvaluate(state, newOptions)); + if (!error) { + if (functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(result)) { + result = true; + break; + } + } + else { + error = undefined; + } + } + return { value: result, error }; + } + } + or.Or = Or; + + return or; +} + +var power = {}; + +var hasRequiredPower; + +function requirePower () { + if (hasRequiredPower) return power; + hasRequiredPower = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(power, "__esModule", { value: true }); + power.Power = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const multivariateNumericEvaluator_1 = requireMultivariateNumericEvaluator(); + /** + * Return exponentiation of one number to another. + */ + class Power extends multivariateNumericEvaluator_1.MultivariateNumericEvaluator { + /** + * Initializes a new instance of the [Power](xref:adaptive-expressions.Power) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Power, Power.func, functionUtils_1.FunctionUtils.verifyNumberOrNumericList); + } + /** + * @private + */ + static func(args) { + return Math.pow(args[0], args[1]); + } + } + power.Power = Power; + + return power; +} + +var rand = {}; + +var hasRequiredRand; + +function requireRand () { + if (hasRequiredRand) return rand; + hasRequiredRand = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(rand, "__esModule", { value: true }); + rand.Rand = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const extensions_1 = requireExtensions(); + /** + * Return a random integer from a specified range, which is inclusive only at the starting end. + */ + class Rand extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Rand](xref:adaptive-expressions.Rand) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Rand, Rand.evaluator, returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateBinaryNumber); + } + static evaluator(expression, state, options) { + let result; + let minValue; + let maxValue; + let error; + const [maybeMinValue, maybeMaxValue] = expression.children; + // eslint-disable-next-line prefer-const + ({ value: minValue, error } = maybeMinValue.tryEvaluate(state, options)); + if (error) { + return { value: undefined, error }; + } + if (!Number.isInteger(minValue)) { + return { value: undefined, error: `${minValue} is not an integer.` }; + } + // eslint-disable-next-line prefer-const + ({ value: maxValue, error } = maybeMaxValue.tryEvaluate(state, options)); + if (error) { + return { value: undefined, error }; + } + if (!Number.isInteger(maxValue)) { + return { value: undefined, error: `${maxValue} is not an integer.` }; + } + if (minValue > maxValue) { + error = `Min value ${minValue} cannot be greater than max value ${maxValue}.`; + } + else { + result = extensions_1.Extensions.randomNext(state, minValue, maxValue); + } + return { value: result, error }; + } + } + rand.Rand = Rand; + + return rand; +} + +var range = {}; + +var hasRequiredRange; + +function requireRange () { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(range, "__esModule", { value: true }); + range.Range = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return an integer array that starts from a specified integer with the given length. + */ + class Range extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Range](xref:adaptive-expressions.Range) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Range, Range.evaluator(), returnType_1.ReturnType.Array, functionUtils_1.FunctionUtils.validateBinaryNumber); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error; + if (args[1] <= 0) { + error = 'Second paramter must be more than zero'; + } + const result = [...Array(args[1]).keys()].map((u) => u + Number(args[0])); + return { value: result, error }; + }, functionUtils_1.FunctionUtils.verifyInteger); + } + } + range.Range = Range; + + return range; +} + +var removeProperty = {}; + +var hasRequiredRemoveProperty; + +function requireRemoveProperty () { + if (hasRequiredRemoveProperty) return removeProperty; + hasRequiredRemoveProperty = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(removeProperty, "__esModule", { value: true }); + removeProperty.RemoveProperty = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Remove a property from an object and return the updated object. + */ + class RemoveProperty extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [RemoveProperty](xref:adaptive-expressions.RemoveProperty) class. + */ + constructor() { + super(expressionType_1.ExpressionType.RemoveProperty, RemoveProperty.evaluator(), returnType_1.ReturnType.Object, RemoveProperty.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + const temp = args[0]; + delete temp[String(args[1])]; + return temp; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Object, returnType_1.ReturnType.String); + } + } + removeProperty.RemoveProperty = RemoveProperty; + + return removeProperty; +} + +var replace = {}; + +var hasRequiredReplace; + +function requireReplace () { + if (hasRequiredReplace) return replace; + hasRequiredReplace = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(replace, "__esModule", { value: true }); + replace.Replace = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Replace a substring with the specified string, and return the result string. + * This function is case-sensitive. + */ + class Replace extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Replace](xref:adaptive-expressions.Replace) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Replace, Replace.evaluator(), returnType_1.ReturnType.String, Replace.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error = undefined; + let result = undefined; + if (functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1]).length === 0) { + error = `${args[1]} should be a string with length at least 1`; + } + if (!error) { + result = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]) + .split(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1])) + .join(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[2])); + } + return { value: result, error }; + }, functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 3, 3, returnType_1.ReturnType.String); + } + } + replace.Replace = Replace; + + return replace; +} + +var replaceIgnoreCase = {}; + +var hasRequiredReplaceIgnoreCase; + +function requireReplaceIgnoreCase () { + if (hasRequiredReplaceIgnoreCase) return replaceIgnoreCase; + hasRequiredReplaceIgnoreCase = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(replaceIgnoreCase, "__esModule", { value: true }); + replaceIgnoreCase.ReplaceIgnoreCase = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Replace a substring with the specified string, and return the result string. + * This function is case-insensitive. + */ + class ReplaceIgnoreCase extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [ReplaceIgnoreCase](xref:adaptive-expressions.ReplaceIgnoreCase) class. + */ + constructor() { + super(expressionType_1.ExpressionType.ReplaceIgnoreCase, ReplaceIgnoreCase.evaluator(), returnType_1.ReturnType.String, ReplaceIgnoreCase.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error = undefined; + let result = undefined; + if (functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1]).length === 0) { + error = `${args[1]} should be a string with length at least 1`; + } + if (!error) { + result = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).replace( + // eslint-disable-next-line security/detect-non-literal-regexp + new RegExp(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1]), 'gi'), functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[2])); + } + return { value: result, error }; + }, functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 3, 3, returnType_1.ReturnType.String); + } + } + replaceIgnoreCase.ReplaceIgnoreCase = ReplaceIgnoreCase; + + return replaceIgnoreCase; +} + +var reverse = {}; + +var hasRequiredReverse; + +function requireReverse () { + if (hasRequiredReverse) return reverse; + hasRequiredReverse = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(reverse, "__esModule", { value: true }); + reverse.Reverse = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Reverses the order of the elements in a String or Array. + */ + class Reverse extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the `Reverse` class. + */ + constructor() { + super(expressionType_1.ExpressionType.Reverse, Reverse.evaluator(), returnType_1.ReturnType.String | returnType_1.ReturnType.Array, Reverse.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let value = undefined; + let error = undefined; + if (typeof args[0] === 'string') { + value = args[0].split('').reverse().join(''); + } + else if (Array.isArray(args[0])) { + value = args[0].reverse(); + } + else { + error = `${args[0]} is not a string or list.`; + } + return { value, error }; + }, functionUtils_1.FunctionUtils.verifyContainer); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.String | returnType_1.ReturnType.Array); + } + } + reverse.Reverse = Reverse; + + return reverse; +} + +var round = {}; + +var hasRequiredRound; + +function requireRound () { + if (hasRequiredRound) return round; + hasRequiredRound = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(round, "__esModule", { value: true }); + round.Round = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Rounds a number value to the nearest integer. + */ + class Round extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Round](xref:adaptive-expressions.Round) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Round, Round.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryOrBinaryNumber); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let result; + let error; + if (args.length === 2 && !Number.isInteger(args[1])) { + error = `The second parameter ${args[1]} must be an integer.`; + } + if (!error) { + const digits = args.length === 2 ? args[1] : 0; + if (digits < 0 || digits > 15) { + error = `The second parameter ${args[1]} must be an integer between 0 and 15;`; + } + else { + result = Round.roundToPrecision(args[0], digits); + } + } + return { value: result, error }; + }, functionUtils_1.FunctionUtils.verifyNumber); + } + } + round.Round = Round; + Round.roundToPrecision = (num, digits) => Math.round(num * Math.pow(10, digits)) / Math.pow(10, digits); + + return round; +} + +var select = {}; + +var hasRequiredSelect; + +function requireSelect () { + if (hasRequiredSelect) return select; + hasRequiredSelect = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(select, "__esModule", { value: true }); + select.Select = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Operate on each element and return the new collection of transformed elements. + */ + class Select extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Select](xref:adaptive-expressions.Select) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Select, functionUtils_internal_1.InternalFunctionUtils.foreach, returnType_1.ReturnType.Array, functionUtils_internal_1.InternalFunctionUtils.ValidateLambdaExpression); + } + } + select.Select = Select; + + return select; +} + +var sentenceCase = {}; + +var stringTransformEvaluator = {}; + +var hasRequiredStringTransformEvaluator; + +function requireStringTransformEvaluator () { + if (hasRequiredStringTransformEvaluator) return stringTransformEvaluator; + hasRequiredStringTransformEvaluator = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(stringTransformEvaluator, "__esModule", { value: true }); + stringTransformEvaluator.StringTransformEvaluator = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Evaluator that transforms a string to another string. + */ + class StringTransformEvaluator extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StringTransformEvaluator](xref:adaptive-expressions.StringTransformEvaluator) class. + * + * @param type Name of the built-in function. + * @param func The string transformation function, it takes a list of objects and returns an string. + * @param validator The validation function. + */ + constructor(type, func, validator) { + super(type, functionUtils_1.FunctionUtils.applyWithOptions(func, functionUtils_1.FunctionUtils.verifyStringOrNull), returnType_1.ReturnType.String, validator ? validator : functionUtils_1.FunctionUtils.validateUnaryString); + } + } + stringTransformEvaluator.StringTransformEvaluator = StringTransformEvaluator; + + return stringTransformEvaluator; +} + +var hasRequiredSentenceCase; + +function requireSentenceCase () { + if (hasRequiredSentenceCase) return sentenceCase; + hasRequiredSentenceCase = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(sentenceCase, "__esModule", { value: true }); + sentenceCase.SentenceCase = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const stringTransformEvaluator_1 = requireStringTransformEvaluator(); + /** + * Capitalizing only the first word and leave others lowercase. + */ + class SentenceCase extends stringTransformEvaluator_1.StringTransformEvaluator { + /** + * Initializes a new instance of the [SentenceCase](xref:adaptive-expressions.SentenceCase) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SentenceCase, SentenceCase.evaluator, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(args, options) { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = functionUtils_1.FunctionUtils.determineLocale(args, 2, locale); + const firstArg = args[0]; + if (typeof firstArg === 'string' || firstArg === undefined) { + const inputStr = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(firstArg).toLocaleLowerCase(locale); + if (inputStr === '') { + return inputStr; + } + else { + return inputStr.charAt(0).toUpperCase() + inputStr.substr(1).toLocaleLowerCase(locale); + } + } + } + } + sentenceCase.SentenceCase = SentenceCase; + + return sentenceCase; +} + +var setPathToValue = {}; + +var hasRequiredSetPathToValue; + +function requireSetPathToValue () { + if (hasRequiredSetPathToValue) return setPathToValue; + hasRequiredSetPathToValue = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(setPathToValue, "__esModule", { value: true }); + setPathToValue.SetPathToValue = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Set path in a JSON object to value. + */ + class SetPathToValue extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SetPathToValue](xref:adaptive-expressions.SetPathToValue) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SetPathToValue, SetPathToValue.evaluator, returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateBinary); + } + /** + * @private + */ + static evaluator(expression, state, options) { + const { path, left, error } = functionUtils_1.FunctionUtils.tryAccumulatePath(expression.children[0], state, options); + if (error !== undefined) { + return { value: undefined, error }; + } + if (left) { + // the expression can't be fully merged as a path + return { value: undefined, error: `${expression.children[0].toString()} is not a valid path to set value` }; + } + const { value, error: err } = expression.children[1].tryEvaluate(state, options); + if (err) { + return { value: undefined, error: err }; + } + state.setValue(path, value); + return { value, error: undefined }; + } + } + setPathToValue.SetPathToValue = SetPathToValue; + + return setPathToValue; +} + +var setProperty = {}; + +var hasRequiredSetProperty; + +function requireSetProperty () { + if (hasRequiredSetProperty) return setProperty; + hasRequiredSetProperty = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(setProperty, "__esModule", { value: true }); + setProperty.SetProperty = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Set the value of an object's property and return the updated object. + */ + class SetProperty extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SetProperty](xref:adaptive-expressions.SetProperty) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SetProperty, SetProperty.evaluator(), returnType_1.ReturnType.Object, SetProperty.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + const temp = args[0]; + temp[String(args[1])] = args[2]; + return temp; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Object, returnType_1.ReturnType.String, returnType_1.ReturnType.Object); + } + } + setProperty.SetProperty = SetProperty; + + return setProperty; +} + +var skip = {}; + +var hasRequiredSkip; + +function requireSkip () { + if (hasRequiredSkip) return skip; + hasRequiredSkip = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(skip, "__esModule", { value: true }); + skip.Skip = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Remove items from the front of a collection, and return all the other items. + */ + class Skip extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Skip](xref:adaptive-expressions.Skip) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Skip, Skip.evaluator, returnType_1.ReturnType.Array, Skip.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + const { value: arr, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (Array.isArray(arr)) { + let start; + const startExpr = expression.children[1]; + ({ value: start, error } = startExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(start)) { + error = `${startExpr} is not an integer.`; + } + if (!error) { + start = Math.max(start, 0); + result = arr.slice(start); + } + } + else { + error = `${expression.children[0]} is not array.`; + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.Array, returnType_1.ReturnType.Number); + } + } + skip.Skip = Skip; + + return skip; +} + +var sortBy = {}; + +var hasRequiredSortBy; + +function requireSortBy () { + if (hasRequiredSortBy) return sortBy; + hasRequiredSortBy = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(sortBy, "__esModule", { value: true }); + sortBy.SortBy = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Sort elements in the collection in ascending order and return the sorted collection. + */ + class SortBy extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SortBy](xref:adaptive-expressions.SortBy) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SortBy, functionUtils_internal_1.InternalFunctionUtils.sortBy(false), returnType_1.ReturnType.Array, SortBy.validator); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String], returnType_1.ReturnType.Array); + } + } + sortBy.SortBy = SortBy; + + return sortBy; +} + +var sortByDescending = {}; + +var hasRequiredSortByDescending; + +function requireSortByDescending () { + if (hasRequiredSortByDescending) return sortByDescending; + hasRequiredSortByDescending = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(sortByDescending, "__esModule", { value: true }); + sortByDescending.SortByDescending = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Sort elements in the collection in descending order, and return the sorted collection. + */ + class SortByDescending extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SortByDescending](xref:adaptive-expressions.SortByDescending) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SortByDescending, functionUtils_internal_1.InternalFunctionUtils.sortBy(true), returnType_1.ReturnType.Array, SortByDescending.validator); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String], returnType_1.ReturnType.Array); + } + } + sortByDescending.SortByDescending = SortByDescending; + + return sortByDescending; +} + +var split = {}; + +var hasRequiredSplit; + +function requireSplit () { + if (hasRequiredSplit) return split; + hasRequiredSplit = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(split, "__esModule", { value: true }); + split.Split = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return an array that contains substrings, separated by commas, based on the specified delimiter character in the original string. + */ + class Split extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Split](xref:adaptive-expressions.Split) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Split, Split.evaluator(), returnType_1.ReturnType.Array, Split.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).split(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1] || '')), functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 1, 2, returnType_1.ReturnType.String); + } + } + split.Split = Split; + + return split; +} + +var sqrt = {}; + +var hasRequiredSqrt; + +function requireSqrt () { + if (hasRequiredSqrt) return sqrt; + hasRequiredSqrt = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(sqrt, "__esModule", { value: true }); + sqrt.Sqrt = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Returns the square root of a specified number. + */ + class Sqrt extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SortBy](xref:adaptive-expressions.Sqrt) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Sqrt, Sqrt.evaluator(), returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryNumber); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithError((args) => { + let error; + let value; + const originalNumber = Number(args[0]); + if (originalNumber < 0) { + error = 'Do not support square root extraction of negative numbers.'; + } + else { + value = Math.sqrt(originalNumber); + } + return { value, error }; + }, functionUtils_1.FunctionUtils.verifyNumber); + } + } + sqrt.Sqrt = Sqrt; + + return sqrt; +} + +var startOfDay = {}; + +var hasRequiredStartOfDay; + +function requireStartOfDay () { + if (hasRequiredStartOfDay) return startOfDay; + hasRequiredStartOfDay = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (startOfDay && startOfDay.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(startOfDay, "__esModule", { value: true }); + startOfDay.StartOfDay = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the start of the day for a timestamp. + */ + class StartOfDay extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StartOfDay](xref:adaptive-expressions.StartOfDay) class. + */ + constructor() { + super(expressionType_1.ExpressionType.StartOfDay, StartOfDay.evaluator, returnType_1.ReturnType.String, StartOfDay.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + if (typeof args[0] === 'string') { + ({ value, error } = StartOfDay.evalStartOfDay(args[0], format, locale)); + } + else { + error = `${expression} should contain an ISO format timestamp and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalStartOfDay(timeStamp, format, locale) { + let result; + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(timeStamp); + if (!error) { + result = (0, dayjs_1.default)(timeStamp).locale(locale).utc().startOf('day').format(format); + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String); + } + } + startOfDay.StartOfDay = StartOfDay; + + return startOfDay; +} + +var startOfHour = {}; + +var hasRequiredStartOfHour; + +function requireStartOfHour () { + if (hasRequiredStartOfHour) return startOfHour; + hasRequiredStartOfHour = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (startOfHour && startOfHour.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(startOfHour, "__esModule", { value: true }); + startOfHour.StartOfHour = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the start of the hour for a timestamp. + */ + class StartOfHour extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StartOfHour](xref:adaptive-expressions.StartOfHour) class. + */ + constructor() { + super(expressionType_1.ExpressionType.StartOfHour, StartOfHour.evaluator, returnType_1.ReturnType.String, StartOfHour.validator); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + if (typeof args[0] === 'string') { + ({ value, error } = StartOfHour.evalStartOfHour(args[0], format, locale)); + } + else { + error = `${expr} should contain an ISO format timestamp and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalStartOfHour(timeStamp, format, locale) { + let result; + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(timeStamp); + if (!error) { + result = (0, dayjs_1.default)(timeStamp).locale(locale).utc().startOf('hour').format(format); + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String); + } + } + startOfHour.StartOfHour = StartOfHour; + + return startOfHour; +} + +var startOfMonth = {}; + +var hasRequiredStartOfMonth; + +function requireStartOfMonth () { + if (hasRequiredStartOfMonth) return startOfMonth; + hasRequiredStartOfMonth = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (startOfMonth && startOfMonth.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(startOfMonth, "__esModule", { value: true }); + startOfMonth.StartOfMonth = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the start of the month for a timestamp. + */ + class StartOfMonth extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StartOfMonth](xref:adaptive-expressions.StartOfMonth) class. + */ + constructor() { + super(expressionType_1.ExpressionType.StartOfMonth, StartOfMonth.evaluator, returnType_1.ReturnType.String, StartOfMonth.validator); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + if (typeof args[0] === 'string') { + ({ value, error } = StartOfMonth.evalStartOfMonth(args[0], format, locale)); + } + else { + error = `${expr} should contain an ISO format timestamp and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalStartOfMonth(timeStamp, format, locale) { + let result; + const error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(timeStamp); + if (!error) { + result = (0, dayjs_1.default)(timeStamp).locale(locale).utc().startOf('month').format(format); + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String); + } + } + startOfMonth.StartOfMonth = StartOfMonth; + + return startOfMonth; +} + +var startsWith = {}; + +var hasRequiredStartsWith; + +function requireStartsWith () { + if (hasRequiredStartsWith) return startsWith; + hasRequiredStartsWith = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(startsWith, "__esModule", { value: true }); + startsWith.StartsWith = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Check whether a string starts with a specific substring. Return true if the substring is found, or return false if not found. + * This function is case-insensitive. + */ + class StartsWith extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StartsWith](xref:adaptive-expressions.StartsWith) class. + */ + constructor() { + super(expressionType_1.ExpressionType.StartsWith, StartsWith.evaluator(), returnType_1.ReturnType.Boolean, StartsWith.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[0]).startsWith(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(args[1])), functionUtils_1.FunctionUtils.verifyStringOrNull); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 2, 2, returnType_1.ReturnType.String); + } + } + startsWith.StartsWith = StartsWith; + + return startsWith; +} + +var string = {}; + +var hasRequiredString; + +function requireString () { + if (hasRequiredString) return string; + hasRequiredString = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(string, "__esModule", { value: true }); + string.String = void 0; + const d3_format_1 = requireD3Format(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const localeInfo_1 = requireLocaleInfo(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + /** + * Return the string version of a value. + */ + class String extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [String](xref:adaptive-expressions.String) class. + */ + constructor() { + super(expressionType_1.ExpressionType.String, String.evaluator(), returnType_1.ReturnType.String, String.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let result; + let error; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + { + locale = functionUtils_1.FunctionUtils.determineLocale(args, 2, locale); + } + { + if (typeof args[0] === 'string') { + result = args[0]; + } + else if (functionUtils_1.FunctionUtils.isNumber(args[0])) { + const formatLocale = localeInfo_1.localeInfo[locale]; + const tempStrValue = args[0].toString(); + let precision = 0; + if (tempStrValue.includes('.')) { + precision = tempStrValue.split('.')[1].length; + } + const fixedNotation = `,.${precision}f`; + if (formatLocale !== undefined) { + result = (0, d3_format_1.formatLocale)(formatLocale).format(fixedNotation)(args[0]); + } + else { + result = (0, d3_format_1.format)(fixedNotation)(args[0]); + } + } + else if (args[0] instanceof Date) { + result = args[0].toLocaleDateString(locale); + } + else if (args[0] instanceof Uint8Array) { + result = functionUtils_internal_1.InternalFunctionUtils.getTextDecoder().decode(args[0]); + } + else { + result = functionUtils_internal_1.InternalFunctionUtils.commonStringify(args[0]); + } + } + return { value: result, error: error }; + }); + } + /** + * @private + */ + static validator(expr) { + functionUtils_1.FunctionUtils.validateOrder(expr, [returnType_1.ReturnType.String], returnType_1.ReturnType.Object); + } + } + string.String = String; + + return string; +} + +var stringOrValue = {}; + +var hasRequiredStringOrValue; + +function requireStringOrValue () { + if (hasRequiredStringOrValue) return stringOrValue; + hasRequiredStringOrValue = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(stringOrValue, "__esModule", { value: true }); + stringOrValue.StringOrValue = void 0; + const constant_1 = requireConstant(); + const expression_1 = requireExpression(); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Wrap string interpolation to get real value. + * For example: stringOrValue('${1}'), would get number 1 + * stringOrValue('${1} item'), would get string "1 item". + */ + class StringOrValue extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [StringOrValue](xref:adaptive-expressions.StringOrValue) class. + */ + constructor() { + super(expressionType_1.ExpressionType.StringOrValue, StringOrValue.evaluator, returnType_1.ReturnType.Object, functionUtils_1.FunctionUtils.validateUnaryString); + } + /** + * @private + */ + static evaluator(expression, state, options) { + const { value: stringInput, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (typeof stringInput !== 'string') { + error = 'Parameter should be a string.'; + } + if (!error) { + const expr = expression_1.Expression.parse('`' + stringInput + '`'); + if (expr.children.length === 2) { + const firstChild = expr.children[0]; + const secondChild = expr.children[1]; + // If the Expression follows this format: + // concat('', childExpression) + // return the childExpression result directly. + if (firstChild instanceof constant_1.Constant && + firstChild.value.toString() === '' && + !(secondChild instanceof constant_1.Constant)) { + return secondChild.tryEvaluate(state, options); + } + } + return expr.tryEvaluate(state, options); + } + return { value: undefined, error }; + } + } + stringOrValue.StringOrValue = StringOrValue; + + return stringOrValue; +} + +var subArray = {}; + +var hasRequiredSubArray; + +function requireSubArray () { + if (hasRequiredSubArray) return subArray; + hasRequiredSubArray = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(subArray, "__esModule", { value: true }); + subArray.SubArray = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Returns a subarray from specified start and end positions. Index values start with the number 0. + */ + class SubArray extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SubArray](xref:adaptive-expressions.SubArray) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SubArray, SubArray.evaluator, returnType_1.ReturnType.Array, SubArray.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + const { value: arr, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (Array.isArray(arr)) { + let start; + const startExpr = expression.children[1]; + ({ value: start, error } = startExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(start)) { + error = `${startExpr} is not an integer.`; + } + else if (start < 0 || start > arr.length) { + error = `${startExpr}=${start} which is out of range for ${arr}`; + } + if (!error) { + let end; + if (expression.children.length === 2) { + end = arr.length; + } + else { + const endExpr = expression.children[2]; + ({ value: end, error } = endExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(end)) { + error = `${endExpr} is not an integer`; + } + else if (end < 0 || end > arr.length) { + error = `${endExpr}=${end} which is out of range for ${arr}`; + } + } + if (!error) { + result = arr.slice(start, end); + } + } + } + else { + error = `${expression.children[0]} is not array.`; + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.Number], returnType_1.ReturnType.Array, returnType_1.ReturnType.Number); + } + } + subArray.SubArray = SubArray; + + return subArray; +} + +var substring = {}; + +var hasRequiredSubstring; + +function requireSubstring () { + if (hasRequiredSubstring) return substring; + hasRequiredSubstring = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(substring, "__esModule", { value: true }); + substring.Substring = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return characters from a string, starting from the specified position or index. Index values start with the number 0. + */ + class Substring extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Substring](xref:adaptive-expressions.Substring) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Substring, Substring.evaluator, returnType_1.ReturnType.String, Substring.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + const { value: str, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (typeof str === 'string') { + let start; + const startExpr = expression.children[1]; + ({ value: start, error } = startExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(start)) { + error = `${startExpr} is not an integer.`; + } + else if (start < 0 || start > str.length) { + error = `${startExpr}=${start} which is out of range for ${str}`; + } + if (!error) { + let length; + if (expression.children.length === 2) { + // Without length, compute to end + length = str.length - start; + } + else { + const lengthExpr = expression.children[2]; + ({ value: length, error } = lengthExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(length)) { + error = `${lengthExpr} is not an integer`; + } + else if (length < 0 || Number(start) + Number(length) > str.length) { + error = `${lengthExpr}=${length} which is out of range for ${str}`; + } + } + if (!error) { + result = str.substr(start, length); + } + } + } + else if (str === undefined) { + result = ''; + } + else { + error = `${expression.children[0]} is neither a string nor a null object.`; + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.Number], returnType_1.ReturnType.String, returnType_1.ReturnType.Number); + } + } + substring.Substring = Substring; + + return substring; +} + +var subtract = {}; + +var hasRequiredSubtract; + +function requireSubtract () { + if (hasRequiredSubtract) return subtract; + hasRequiredSubtract = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(subtract, "__esModule", { value: true }); + subtract.Subtract = void 0; + const expressionType_1 = requireExpressionType(); + const multivariateNumericEvaluator_1 = requireMultivariateNumericEvaluator(); + /** + * Return the result from subtracting the next number from the previous number. + */ + class Subtract extends multivariateNumericEvaluator_1.MultivariateNumericEvaluator { + /** + * Initializes a new instance of the [Subtract](xref:adaptive-expressions.Subtract) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Subtract, Subtract.func); + } + /** + * @private + */ + static func(args) { + return Number(args[0]) - Number(args[1]); + } + } + subtract.Subtract = Subtract; + + return subtract; +} + +var subtractFromTime = {}; + +var hasRequiredSubtractFromTime; + +function requireSubtractFromTime () { + if (hasRequiredSubtractFromTime) return subtractFromTime; + hasRequiredSubtractFromTime = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (subtractFromTime && subtractFromTime.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(subtractFromTime, "__esModule", { value: true }); + subtractFromTime.SubtractFromTime = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Subtract a number of time units from a timestamp. + */ + class SubtractFromTime extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [SubtractFromTime](xref:adaptive-expressions.SubtractFromTime) class. + */ + constructor() { + super(expressionType_1.ExpressionType.SubtractFromTime, SubtractFromTime.evaluator, returnType_1.ReturnType.String, SubtractFromTime.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let value; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expression, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string' && Number.isInteger(args[1]) && typeof args[2] === 'string') { + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 5, format, locale)); + const { duration, tsStr } = functionUtils_internal_1.InternalFunctionUtils.timeUnitTransformer(args[1], args[2]); + if (tsStr === undefined) { + error = `${args[2]} is not a valid time unit.`; + } + else { + const dur = duration; + error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]); + if (!error) { + value = (0, dayjs_1.default)(args[0]).locale(locale).utc().subtract(dur, tsStr).format(format); + } + } + } + else { + error = `${expression} should contain an ISO format timestamp, a time interval integer, a string unit of time and an optional output format string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String], returnType_1.ReturnType.String, returnType_1.ReturnType.Number, returnType_1.ReturnType.String); + } + } + subtractFromTime.SubtractFromTime = SubtractFromTime; + + return subtractFromTime; +} + +var sum = {}; + +var hasRequiredSum; + +function requireSum () { + if (hasRequiredSum) return sum; + hasRequiredSum = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(sum, "__esModule", { value: true }); + sum.Sum = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the result from adding numbers in an array. + */ + class Sum extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Sum](xref:adaptive-expressions.Sum) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Sum, Sum.evaluator(), returnType_1.ReturnType.Number, Sum.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => args[0].reduce((x, y) => x + y), functionUtils_1.FunctionUtils.verifyNumericList); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.Array); + } + } + sum.Sum = Sum; + + return sum; +} + +var take = {}; + +var hasRequiredTake; + +function requireTake () { + if (hasRequiredTake) return take; + hasRequiredTake = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(take, "__esModule", { value: true }); + take.Take = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return items from the front of an array or take the specific prefix from a string. + */ + class Take extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Take](xref:adaptive-expressions.Take) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Take, Take.evaluator, returnType_1.ReturnType.Array | returnType_1.ReturnType.String, Take.validator); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + const { value: arr, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + if (Array.isArray(arr) || typeof arr === 'string') { + let start; + const startExpr = expression.children[1]; + ({ value: start, error } = startExpr.tryEvaluate(state, options)); + if (!error && !Number.isInteger(start)) { + error = `${startExpr} is not an integer.`; + } + if (!error) { + start = Math.max(start, 0); + result = arr.slice(0, start); + } + } + else { + error = `${expression.children[0]} is not array or string.`; + } + } + return { value: result, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.Array | returnType_1.ReturnType.String, returnType_1.ReturnType.Number); + } + } + take.Take = Take; + + return take; +} + +var ticks = {}; + +var hasRequiredTicks; + +function requireTicks () { + if (hasRequiredTicks) return ticks; + hasRequiredTicks = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(ticks, "__esModule", { value: true }); + ticks.Ticks = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the ticks property value of a specified timestamp. A tick is 100-nanosecond interval. + */ + class Ticks extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Ticks](xref:adaptive-expressions.Ticks) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Ticks, Ticks.evaluator, returnType_1.ReturnType.Number, Ticks.validator); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = functionUtils_internal_1.InternalFunctionUtils.ticks(args[0])); + } + else { + error = `${expr} should contain an ISO format timestamp.`; + } + } + return { value, error }; + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 1, 1, returnType_1.ReturnType.String); + } + } + ticks.Ticks = Ticks; + + return ticks; +} + +var ticksToDays = {}; + +var hasRequiredTicksToDays; + +function requireTicksToDays () { + if (hasRequiredTicksToDays) return ticksToDays; + hasRequiredTicksToDays = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (ticksToDays && ticksToDays.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(ticksToDays, "__esModule", { value: true }); + ticksToDays.TicksToDays = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const big_integer_1 = __importDefault(requireBigInteger()); + /** + * Convert ticks to number of days. + */ + class TicksToDays extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [TicksToDays](xref:adaptive-expressions.TicksToDays) class. + */ + constructor() { + super(expressionType_1.ExpressionType.TicksToDays, TicksToDays.evaluator, returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryNumber); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + const firstChild = args[0]; + if (Number.isInteger(firstChild)) { + value = firstChild / TicksToDays.TicksPerDay; + } + else if (big_integer_1.default.isInstance(firstChild)) { + value = firstChild.toJSNumber() / TicksToDays.TicksPerDay; + } + else { + error = `${expr} should contain an integer of ticks`; + } + } + return { value, error }; + } + } + ticksToDays.TicksToDays = TicksToDays; + TicksToDays.TicksPerDay = 24 * 60 * 60 * 10000000; + + return ticksToDays; +} + +var ticksToHours = {}; + +var hasRequiredTicksToHours; + +function requireTicksToHours () { + if (hasRequiredTicksToHours) return ticksToHours; + hasRequiredTicksToHours = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (ticksToHours && ticksToHours.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(ticksToHours, "__esModule", { value: true }); + ticksToHours.TicksToHours = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const big_integer_1 = __importDefault(requireBigInteger()); + /** + * Convert ticks to number of hours. + */ + class TicksToHours extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [TicksToHours](xref:adaptive-expressions.TicksToHours) class. + */ + constructor() { + super(expressionType_1.ExpressionType.TicksToHours, TicksToHours.evaluator, returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryNumber); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + const firstChild = args[0]; + if (Number.isInteger(firstChild)) { + value = firstChild / TicksToHours.TicksPerHour; + } + else if (big_integer_1.default.isInstance(firstChild)) { + value = firstChild.toJSNumber() / TicksToHours.TicksPerHour; + } + else { + error = `${expr} should contain an integer of ticks`; + } + } + return { value, error }; + } + } + ticksToHours.TicksToHours = TicksToHours; + TicksToHours.TicksPerHour = 60 * 60 * 10000000; + + return ticksToHours; +} + +var ticksToMinutes = {}; + +var hasRequiredTicksToMinutes; + +function requireTicksToMinutes () { + if (hasRequiredTicksToMinutes) return ticksToMinutes; + hasRequiredTicksToMinutes = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (ticksToMinutes && ticksToMinutes.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(ticksToMinutes, "__esModule", { value: true }); + ticksToMinutes.TicksToMinutes = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + const big_integer_1 = __importDefault(requireBigInteger()); + /** + * Convert ticks to number of minutes. + */ + class TicksToMinutes extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [TicksToMinutes](xref:adaptive-expressions.TicksToMinutes) class. + */ + constructor() { + super(expressionType_1.ExpressionType.TicksToMinutes, TicksToMinutes.evaluator, returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnaryNumber); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + const firstChild = args[0]; + if (Number.isInteger(firstChild)) { + value = firstChild / TicksToMinutes.TicksPerMinute; + } + else if (big_integer_1.default.isInstance(firstChild)) { + value = firstChild.toJSNumber() / TicksToMinutes.TicksPerMinute; + } + else { + error = `${expr} should contain an integer of ticks`; + } + } + return { value, error }; + } + } + ticksToMinutes.TicksToMinutes = TicksToMinutes; + TicksToMinutes.TicksPerMinute = 60 * 10000000; + + return ticksToMinutes; +} + +var timexResolve = {}; + +var hasRequiredTimexResolve; + +function requireTimexResolve () { + if (hasRequiredTimexResolve) return timexResolve; + hasRequiredTimexResolve = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(timexResolve, "__esModule", { value: true }); + timexResolve.TimexResolve = void 0; + const recognizers_text_data_types_timex_expression_1 = require$$0$1; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return true if a given TimexProperty or Timex expression refers to a valid time. + */ + class TimexResolve extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [TimexResolve](xref:adaptive-expressions.TimexResolve) class. + */ + constructor() { + super(expressionType_1.ExpressionType.TimexResolve, TimexResolve.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let parsed; + let value = false; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + ({ timexProperty: parsed, error: error } = functionUtils_internal_1.InternalFunctionUtils.parseTimexProperty(args[0])); + } + if (!error && parsed.types.size === 0) { + error = `The parsed TimexProperty of ${args[0]} in ${expr} has no types. It can't be resolved to a string value.`; + } + if (!error) { + const formatedTimex = parsed.timex; + try { + const resolvedValues = recognizers_text_data_types_timex_expression_1.valueResolver.resolve([formatedTimex]); + value = resolvedValues.values[0].value; + } + catch (err) { + error = `${args[0]} in ${expr} is not a valid argument. ${err.Message}`; + } + } + return { value, error }; + } + } + timexResolve.TimexResolve = TimexResolve; + + return timexResolve; +} + +var titleCase = {}; + +var hasRequiredTitleCase; + +function requireTitleCase () { + if (hasRequiredTitleCase) return titleCase; + hasRequiredTitleCase = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(titleCase, "__esModule", { value: true }); + titleCase.TitleCase = void 0; + const functionUtils_1 = requireFunctionUtils(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const stringTransformEvaluator_1 = requireStringTransformEvaluator(); + /** + * Converts the specified string to title case. + */ + class TitleCase extends stringTransformEvaluator_1.StringTransformEvaluator { + /** + * Initializes a new instance of the [TitleCase](xref:adaptive-expressions.TitleCase) class. + */ + constructor() { + super(expressionType_1.ExpressionType.TitleCase, TitleCase.evaluator, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + static evaluator(args, options) { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = functionUtils_1.FunctionUtils.determineLocale(args, 2, locale); + const firstArg = args[0]; + if (typeof firstArg === 'string' || firstArg === undefined) { + const inputStr = functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(firstArg).toLocaleLowerCase(locale); + if (inputStr === '') { + return inputStr; + } + else { + return inputStr.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLocaleLowerCase(locale)); + } + } + } + } + titleCase.TitleCase = TitleCase; + + return titleCase; +} + +var toLower = {}; + +var hasRequiredToLower; + +function requireToLower () { + if (hasRequiredToLower) return toLower; + hasRequiredToLower = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(toLower, "__esModule", { value: true }); + toLower.ToLower = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const stringTransformEvaluator_1 = requireStringTransformEvaluator(); + /** + * Return a string in lowercase format. + * If a character in the string doesn't have a lowercase version, that character stays unchanged in the returned string. + */ + class ToLower extends stringTransformEvaluator_1.StringTransformEvaluator { + /** + * Initializes a new instance of the [ToLower](xref:adaptive-expressions.ToLower) class. + */ + constructor() { + super(expressionType_1.ExpressionType.ToLower, ToLower.evaluator, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(args, options) { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = functionUtils_1.FunctionUtils.determineLocale(args, 2, locale); + const firstArg = args[0]; + if (typeof firstArg === 'string' || firstArg === undefined) { + return functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(firstArg).toLocaleLowerCase(locale); + } + } + } + toLower.ToLower = ToLower; + + return toLower; +} + +var toUpper = {}; + +var hasRequiredToUpper; + +function requireToUpper () { + if (hasRequiredToUpper) return toUpper; + hasRequiredToUpper = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(toUpper, "__esModule", { value: true }); + toUpper.ToUpper = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const stringTransformEvaluator_1 = requireStringTransformEvaluator(); + /** + * Return a string in uppercase format. + * If a character in the string doesn't have an uppercase version, that character stays unchanged in the returned string. + */ + class ToUpper extends stringTransformEvaluator_1.StringTransformEvaluator { + /** + * Initializes a new instance of the [ToUpper](xref:adaptive-expressions.ToUpper) class. + */ + constructor() { + super(expressionType_1.ExpressionType.ToUpper, ToUpper.evaluator, functionUtils_1.FunctionUtils.validateUnaryOrBinaryString); + } + /** + * @private + */ + static evaluator(args, options) { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = functionUtils_1.FunctionUtils.determineLocale(args, 2, locale); + const firstArg = args[0]; + if (typeof firstArg === 'string' || firstArg === undefined) { + return functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(firstArg).toLocaleUpperCase(locale); + } + } + } + toUpper.ToUpper = ToUpper; + + return toUpper; +} + +var trim = {}; + +var hasRequiredTrim; + +function requireTrim () { + if (hasRequiredTrim) return trim; + hasRequiredTrim = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(trim, "__esModule", { value: true }); + trim.Trim = void 0; + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const stringTransformEvaluator_1 = requireStringTransformEvaluator(); + /** + * Remove leading and trailing whitespace from a string, and return the updated string. + */ + class Trim extends stringTransformEvaluator_1.StringTransformEvaluator { + /** + * Initializes a new instance of the [Trim](xref:adaptive-expressions.Trim) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Trim, Trim.evaluator); + } + /** + * @private + */ + static evaluator(args) { + const firstArg = args[0]; + if (typeof firstArg === 'string' || firstArg === undefined) { + return String(functionUtils_internal_1.InternalFunctionUtils.parseStringOrUndefined(firstArg)).trim(); + } + } + } + trim.Trim = Trim; + + return trim; +} + +var union = {}; + +var hasRequiredUnion; + +function requireUnion () { + if (hasRequiredUnion) return union; + hasRequiredUnion = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(union, "__esModule", { value: true }); + union.Union = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return a collection that has all the items from the specified collections. + * To appear in the result, an item can appear in any collection passed to this function. + * If one or more items have the same name, the last item with that name appears in the result. + */ + class Union extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Union](xref:adaptive-expressions.Union) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Union, Union.evaluator(), returnType_1.ReturnType.Array, Union.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => { + let result = []; + for (const arg of args) { + result = result.concat(arg); + } + return Array.from(new Set(result)); + }, functionUtils_1.FunctionUtils.verifyList); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateArityAndAnyType(expression, 1, Number.MAX_SAFE_INTEGER, returnType_1.ReturnType.Array); + } + } + union.Union = Union; + + return union; +} + +var unique = {}; + +var hasRequiredUnique; + +function requireUnique () { + if (hasRequiredUnique) return unique; + hasRequiredUnique = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(unique, "__esModule", { value: true }); + unique.Unique = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Remove all duplicates from an array. + */ + class Unique extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Unique](xref:adaptive-expressions.Unique) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Unique, Unique.evaluator(), returnType_1.ReturnType.Array, Unique.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => [...new Set(args[0])], functionUtils_1.FunctionUtils.verifyList); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [], returnType_1.ReturnType.Array); + } + } + unique.Unique = Unique; + + return unique; +} + +var uriComponent = {}; + +var hasRequiredUriComponent; + +function requireUriComponent () { + if (hasRequiredUriComponent) return uriComponent; + hasRequiredUriComponent = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriComponent, "__esModule", { value: true }); + uriComponent.UriComponent = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the binary version of a uniform resource identifier (URI) component. + */ + class UriComponent extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriComponent](xref:adaptive-expressions.UriComponent) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriComponent, UriComponent.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => encodeURIComponent(args[0]), functionUtils_1.FunctionUtils.verifyString); + } + } + uriComponent.UriComponent = UriComponent; + + return uriComponent; +} + +var uriComponentToString = {}; + +var hasRequiredUriComponentToString; + +function requireUriComponentToString () { + if (hasRequiredUriComponentToString) return uriComponentToString; + hasRequiredUriComponentToString = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriComponentToString, "__esModule", { value: true }); + uriComponentToString.UriComponentToString = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the string version of a uniform resource identifier (URI) encoded string, effectively decoding the URI-encoded string. + */ + class UriComponentToString extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriComponentToString](xref:adaptive-expressions.UriComponentToString) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriComponentToString, UriComponentToString.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.apply((args) => decodeURIComponent(args[0]), functionUtils_1.FunctionUtils.verifyString); + } + } + uriComponentToString.UriComponentToString = UriComponentToString; + + return uriComponentToString; +} + +var uriHost = {}; + +var hasRequiredUriHost; + +function requireUriHost () { + if (hasRequiredUriHost) return uriHost; + hasRequiredUriHost = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriHost, "__esModule", { value: true }); + uriHost.UriHost = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the host value of a unified resource identifier (URI). + */ + class UriHost extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriHost](xref:adaptive-expressions.UriHost) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriHost, UriHost.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriHost.evalUriHost(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriHost(uri) { + let result; + const { value: parsed, error: parseError } = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri); + let error = parseError; + if (!error) { + try { + result = parsed.hostname; + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriHost.UriHost = UriHost; + + return uriHost; +} + +var uriPath = {}; + +var hasRequiredUriPath; + +function requireUriPath () { + if (hasRequiredUriPath) return uriPath; + hasRequiredUriPath = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriPath, "__esModule", { value: true }); + uriPath.UriPath = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the path value of a unified resource identifier (URI). + */ + class UriPath extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriPath](xref:adaptive-expressions.UriPath) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriPath, UriPath.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriPath.evalUriPath(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriPath(uri) { + let result; + let error = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri).error; + if (!error) { + try { + const uriObj = new URL(uri); + result = uriObj.pathname; + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriPath.UriPath = UriPath; + + return uriPath; +} + +var uriPathAndQuery = {}; + +var hasRequiredUriPathAndQuery; + +function requireUriPathAndQuery () { + if (hasRequiredUriPathAndQuery) return uriPathAndQuery; + hasRequiredUriPathAndQuery = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriPathAndQuery, "__esModule", { value: true }); + uriPathAndQuery.UriPathAndQuery = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the path and query value of a unified resource identifier (URI). + */ + class UriPathAndQuery extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriPathAndQuery](xref:adaptive-expressions.UriPathAndQuery) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriPathAndQuery, UriPathAndQuery.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriPathAndQuery.evalUriPathAndQuery(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriPathAndQuery(uri) { + let result; + const { value: parsed, error: parseError } = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri); + let error = parseError; + if (!error) { + try { + result = parsed.pathname + parsed.search; + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriPathAndQuery.UriPathAndQuery = UriPathAndQuery; + + return uriPathAndQuery; +} + +var uriPort = {}; + +var hasRequiredUriPort; + +function requireUriPort () { + if (hasRequiredUriPort) return uriPort; + hasRequiredUriPort = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriPort, "__esModule", { value: true }); + uriPort.UriPort = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the port value of a unified resource identifier (URI). + */ + class UriPort extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriPort](xref:adaptive-expressions.UriPort) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriPort, UriPort.evaluator, returnType_1.ReturnType.Number, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriPort.evalUriPort(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriPort(uri) { + let result; + const { value: parsed, error: parseError } = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri); + let error = parseError; + if (!error) { + try { + result = parseInt(parsed.port); + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriPort.UriPort = UriPort; + + return uriPort; +} + +var uriQuery = {}; + +var hasRequiredUriQuery; + +function requireUriQuery () { + if (hasRequiredUriQuery) return uriQuery; + hasRequiredUriQuery = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriQuery, "__esModule", { value: true }); + uriQuery.UriQuery = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the query value of a unified resource identifier (URI). + */ + class UriQuery extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriQuery](xref:adaptive-expressions.UriQuery) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriQuery, UriQuery.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriQuery.evalUriQuery(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriQuery(uri) { + let result; + const { value: parsed, error: parseError } = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri); + let error = parseError; + if (!error) { + try { + result = parsed.search; + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriQuery.UriQuery = UriQuery; + + return uriQuery; +} + +var uriScheme = {}; + +var hasRequiredUriScheme; + +function requireUriScheme () { + if (hasRequiredUriScheme) return uriScheme; + hasRequiredUriScheme = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(uriScheme, "__esModule", { value: true }); + uriScheme.UriScheme = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Return the scheme value of a unified resource identifier (URI). + */ + class UriScheme extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UriScheme](xref:adaptive-expressions.UriScheme) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UriScheme, UriScheme.evaluator, returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); + } + /** + * @private + */ + static evaluator(expr, state, options) { + let value; + const { args, error: childrenError } = functionUtils_1.FunctionUtils.evaluateChildren(expr, state, options); + let error = childrenError; + if (!error) { + if (typeof args[0] === 'string') { + ({ value, error } = UriScheme.evalUriScheme(args[0])); + } + else { + error = `${expr} should contain a URI string.`; + } + } + return { value, error }; + } + /** + * @private + */ + static evalUriScheme(uri) { + let result; + const { value: parsed, error: parseError } = functionUtils_internal_1.InternalFunctionUtils.parseUri(uri); + let error = parseError; + if (!error) { + try { + result = parsed.protocol.replace(':', ''); + } + catch (_a) { + error = 'invalid operation, input uri should be an absolute URI'; + } + } + return { value: result, error }; + } + } + uriScheme.UriScheme = UriScheme; + + return uriScheme; +} + +var utcNow = {}; + +var hasRequiredUtcNow; + +function requireUtcNow () { + if (hasRequiredUtcNow) return utcNow; + hasRequiredUtcNow = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + var __importDefault = (utcNow && utcNow.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(utcNow, "__esModule", { value: true }); + utcNow.UtcNow = void 0; + const dayjs_1 = __importDefault(requireDayjs_min()); + const utc_1 = __importDefault(requireUtc()); + dayjs_1.default.extend(utc_1.default); + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_1 = requireFunctionUtils(); + const returnType_1 = requireReturnType(); + /** + * Return the current timestamp. + */ + class UtcNow extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [UtcNow](xref:adaptive-expressions.UtcNow) class. + */ + constructor() { + super(expressionType_1.ExpressionType.UtcNow, UtcNow.evaluator(), returnType_1.ReturnType.String, UtcNow.validator); + } + /** + * @private + */ + static evaluator() { + return functionUtils_1.FunctionUtils.applyWithOptionsAndError((args, options) => { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = functionUtils_1.FunctionUtils.DefaultDateTimeFormat; + ({ format, locale } = functionUtils_1.FunctionUtils.determineFormatAndLocale(args, 2, format, locale)); + return { + value: (0, dayjs_1.default)(new Date()).locale(locale).utc().format(format), + error: undefined, + }; + }); + } + /** + * @private + */ + static validator(expression) { + functionUtils_1.FunctionUtils.validateOrder(expression, [returnType_1.ReturnType.String, returnType_1.ReturnType.String]); + } + } + utcNow.UtcNow = UtcNow; + + return utcNow; +} + +var where = {}; + +var hasRequiredWhere; + +function requireWhere () { + if (hasRequiredWhere) return where; + hasRequiredWhere = 1; + /** + * @module adaptive-expressions + */ + /** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + Object.defineProperty(where, "__esModule", { value: true }); + where.Where = void 0; + const expressionEvaluator_1 = requireExpressionEvaluator(); + const expressionType_1 = requireExpressionType(); + const functionUtils_internal_1 = requireFunctionUtils_internal(); + const returnType_1 = requireReturnType(); + /** + * Filter on each element and return the new collection of filtered elements which match a specific condition. + */ + class Where extends expressionEvaluator_1.ExpressionEvaluator { + /** + * Initializes a new instance of the [Where](xref:adaptive-expressions.Where) class. + */ + constructor() { + super(expressionType_1.ExpressionType.Where, Where.evaluator, returnType_1.ReturnType.Array, functionUtils_internal_1.InternalFunctionUtils.ValidateLambdaExpression); + } + /** + * @private + */ + static evaluator(expression, state, options) { + let result; + const { value: instance, error: childrenError } = expression.children[0].tryEvaluate(state, options); + let error = childrenError; + if (!error) { + const list = functionUtils_internal_1.InternalFunctionUtils.convertToList(instance); + if (!list) { + error = `${expression.children[0]} is not a collection or structure object to run Where`; + } + else { + result = []; + functionUtils_internal_1.InternalFunctionUtils.lambdaEvaluator(expression, state, options, list, (currentItem, r, e) => { + if (functionUtils_internal_1.InternalFunctionUtils.isLogicTrue(r) && !e) { + // add if only if it evaluates to true + result.push(currentItem); + } + return false; + }); + //reconstruct object if instance is object, otherwise, return array result + if (!Array.isArray(instance)) { + const objResult = {}; + for (const item of result) { + objResult[item.key] = item.value; + } + result = objResult; + } + } + } + return { value: result, error }; + } + } + where.Where = Where; + + return where; +} + +var xml = {}; + +var validator = {}; + +var util = {}; + +var hasRequiredUtil; + +function requireUtil () { + if (hasRequiredUtil) return util; + hasRequiredUtil = 1; + (function (exports) { + + const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; + const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; + const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'; + const regexName = new RegExp('^' + nameRegexp + '$'); + + const getAllMatches = function (string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; + }; + + const isName = function (string) { + const match = regexName.exec(string); + return !(match === null || typeof match === 'undefined'); + }; + + exports.isExist = function (v) { + return typeof v !== 'undefined'; + }; + + exports.isEmptyObject = function (obj) { + return Object.keys(obj).length === 0; + }; + + /** + * Copy all the properties of a into b. + * @param {*} target + * @param {*} a + */ + exports.merge = function (target, a, arrayMode) { + if (a) { + const keys = Object.keys(a); // will return an array of own properties + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + if (arrayMode === 'strict') { + target[keys[i]] = [a[keys[i]]]; + } else { + target[keys[i]] = a[keys[i]]; + } + } + } + }; + /* exports.merge =function (b,a){ + return Object.assign(b,a); + } */ + + exports.getValue = function (v) { + if (exports.isExist(v)) { + return v; + } else { + return ''; + } + }; + + /** + * Dangerous property names that could lead to prototype pollution or security issues + */ + const DANGEROUS_PROPERTY_NAMES = [ + // '__proto__', + // 'constructor', + // 'prototype', + 'hasOwnProperty', + 'toString', + 'valueOf', + '__defineGetter__', + '__defineSetter__', + '__lookupGetter__', + '__lookupSetter__' + ]; + + const criticalProperties = ["__proto__", "constructor", "prototype"]; + + exports.isName = isName; + exports.getAllMatches = getAllMatches; + exports.nameRegexp = nameRegexp; + exports.DANGEROUS_PROPERTY_NAMES = DANGEROUS_PROPERTY_NAMES; + exports.criticalProperties = criticalProperties; + } (util)); + return util; +} + +var hasRequiredValidator; + +function requireValidator () { + if (hasRequiredValidator) return validator; + hasRequiredValidator = 1; + + const util = requireUtil(); + + const defaultOptions = { + allowBooleanAttributes: false, //A tag can have attributes without any value + unpairedTags: [] + }; + + //const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g"); + validator.validate = function (xmlData, options) { + options = Object.assign({}, defaultOptions, options); + + //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line + //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag + //xmlData = xmlData.replace(/()/g,"");//Remove DOCTYPE + const tags = []; + let tagFound = false; + + //indicates that the root tag has been closed (aka. depth 0 has been reached) + let reachedRoot = false; + + if (xmlData[0] === '\ufeff') { + // check for byte order mark (BOM) + xmlData = xmlData.substr(1); + } + + for (let i = 0; i < xmlData.length; i++) { + + if (xmlData[i] === '<' && xmlData[i+1] === '?') { + i+=2; + i = readPI(xmlData,i); + if (i.err) return i; + }else if (xmlData[i] === '<') { + //starting of tag + //read until you reach to '>' avoiding any '>' in attribute value + let tagStartPos = i; + i++; + + if (xmlData[i] === '!') { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === '/') { + //closing tag + closingTag = true; + i++; + } + //read tagname + let tagName = ''; + for (; i < xmlData.length && + xmlData[i] !== '>' && + xmlData[i] !== ' ' && + xmlData[i] !== '\t' && + xmlData[i] !== '\n' && + xmlData[i] !== '\r'; i++ + ) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + //console.log(tagName); + + if (tagName[tagName.length - 1] === '/') { + //self closing tag without attributes + tagName = tagName.substring(0, tagName.length - 1); + //continue; + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '"+tagName+"' is an invalid name."; + } + return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i)); + } + + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + + if (attrStr[attrStr.length - 1] === '/') { + //self closing tag + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + //continue; //text may presents after self closing tag + } else { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags.length === 0) { + return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject('InvalidTag', + "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.", + getLineNumberForPosition(xmlData, tagStartPos)); + } + + //when there are no more tags, we reached the root level. + if (tags.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + //the result from the nested function returns the position of the error within the attribute + //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute + //this gives us the absolute index in the entire xml, which we can use to find the line at last + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + + //if the root level has been reached before ... + if (reachedRoot === true) { + return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i)); + } else if(options.unpairedTags.indexOf(tagName) !== -1); else { + tags.push({tagName, tagStartPos}); + } + tagFound = true; + } + + //skip tag text value + //It may include comments and CDATA value + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + if (xmlData[i + 1] === '!') { + //comment or CADATA + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i+1] === '?') { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === '&') { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + }else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } //end of reading tag text value + if (xmlData[i] === '<') { + i--; + } + } + } else { + if ( isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + + if (!tagFound) { + return getErrorObject('InvalidXml', 'Start tag expected.', 1); + }else if (tags.length == 1) { + return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos)); + }else if (tags.length > 0) { + return getErrorObject('InvalidXml', "Invalid '"+ + JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+ + "' found.", {line: 1, col: 1}); + } + + return true; + }; + + function isWhiteSpace(char){ + return char === ' ' || char === '\t' || char === '\n' || char === '\r'; + } + /** + * Read Processing insstructions and skip + * @param {*} xmlData + * @param {*} i + */ + function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == '?' || xmlData[i] == ' ') { + //tagname + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === 'xml') { + return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') { + //check if valid attribut string + i++; + break; + } else { + continue; + } + } + } + return i; + } + + function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') { + //comment + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } else if ( + xmlData.length > i + 8 && + xmlData[i + 1] === 'D' && + xmlData[i + 2] === 'O' && + xmlData[i + 3] === 'C' && + xmlData[i + 4] === 'T' && + xmlData[i + 5] === 'Y' && + xmlData[i + 6] === 'P' && + xmlData[i + 7] === 'E' + ) { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === '<') { + angleBracketsCount++; + } else if (xmlData[i] === '>') { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if ( + xmlData.length > i + 9 && + xmlData[i + 1] === '[' && + xmlData[i + 2] === 'C' && + xmlData[i + 3] === 'D' && + xmlData[i + 4] === 'A' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'A' && + xmlData[i + 7] === '[' + ) { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') { + i += 2; + break; + } + } + } + + return i; + } + + const doubleQuote = '"'; + const singleQuote = "'"; + + /** + * Keep reading xmlData until '<' is found outside the attribute value. + * @param {string} xmlData + * @param {number} i + */ + function readAttributeStr(xmlData, i) { + let attrStr = ''; + let startChar = ''; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === '') { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) ; else { + startChar = ''; + } + } else if (xmlData[i] === '>') { + if (startChar === '') { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== '') { + return false; + } + + return { + value: attrStr, + index: i, + tagClosed: tagClosed + }; + } + + /** + * Select all the attributes whether valid or invalid. + */ + const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g'); + + //attr, ="sd", a="amit's", a="sd"b="saf", ab cd="" + + function validateAttributeString(attrStr, options) { + //console.log("start:"+attrStr+":end"); + + //if(attrStr.trim().length === 0) return true; //empty string + + const matches = util.getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + //nospace before attribute name: a="sd"b="saf" + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i])) + } else if (matches[i][3] !== undefined && matches[i][4] === undefined) { + return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) { + //independent attribute: ab + return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i])); + } + /* else if(matches[i][6] === undefined){//attribute without value: ab= + return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}}; + } */ + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!attrNames.hasOwnProperty(attrName)) { + //check for duplicate attribute. + attrNames[attrName] = 1; + } else { + return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i])); + } + } + + return true; + } + + function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === 'x') { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ';') + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; + } + + function validateAmpersand(xmlData, i) { + // https://www.w3.org/TR/xml/#dt-charref + i++; + if (xmlData[i] === ';') + return -1; + if (xmlData[i] === '#') { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ';') + break; + return -1; + } + return i; + } + + function getErrorObject(code, message, lineNumber) { + return { + err: { + code: code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col, + }, + }; + } + + function validateAttrName(attrName) { + return util.isName(attrName); + } + + // const startsWithXML = /^xml/i; + + function validateTagName(tagname) { + return util.isName(tagname) /* && !tagname.match(startsWithXML) */; + } + + //this function returns the line number for the character at the given index + function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; + } + + //this function returns the position of the first character of match within attrStr + function getPositionFromMatch(match) { + return match.startIndex + match[1].length; + } + return validator; +} + +var OptionsBuilder = {}; + +var hasRequiredOptionsBuilder; + +function requireOptionsBuilder () { + if (hasRequiredOptionsBuilder) return OptionsBuilder; + hasRequiredOptionsBuilder = 1; + const { DANGEROUS_PROPERTY_NAMES, criticalProperties } = requireUtil(); + + const defaultOnDangerousProperty = (name) => { + if (DANGEROUS_PROPERTY_NAMES.includes(name)) { + return "__" + name; + } + return name; + }; + const defaultOptions = { + preserveOrder: false, + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + removeNSPrefix: false, // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true + }, + tagValueProcessor: function (tagName, val) { + return val; + }, + attributeValueProcessor: function (attrName, val) { + return val; + }, + stopNodes: [], //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: () => false, + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: function (tagName, jPath, attrs) { + return tagName + }, + // skipEmptyListItem: false + captureMetaData: false, + maxNestedTags: 100, + strictReservedNames: true, + onDangerousProperty: defaultOnDangerousProperty + }; + /** + * Validates that a property name is safe to use + * @param {string} propertyName - The property name to validate + * @param {string} optionName - The option field name (for error message) + * @throws {Error} If property name is dangerous + */ + function validatePropertyName(propertyName, optionName) { + if (typeof propertyName !== 'string') { + return; // Only validate string property names + } + + const normalized = propertyName.toLowerCase(); + if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + + if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + } + + /** + * Normalizes processEntities option for backward compatibility + * @param {boolean|object} value + * @returns {object} Always returns normalized object + */ + function normalizeProcessEntities(value) { + // Boolean backward compatibility + if (typeof value === 'boolean') { + return { + enabled: value, // true or false + maxEntitySize: 10000, + maxExpansionDepth: 10, + maxTotalExpansions: 1000, + maxExpandedLength: 100000, + allowedTags: null, + tagFilter: null + }; + } + + // Object config - merge with defaults + if (typeof value === 'object' && value !== null) { + return { + enabled: value.enabled !== false, + maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000), + maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000), + maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity), + maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000), + maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000), + allowedTags: value.allowedTags ?? null, + tagFilter: value.tagFilter ?? null + }; + } + + // Default to enabled with limits + return normalizeProcessEntities(true); + } + + const buildOptions = function (options) { + const built = Object.assign({}, defaultOptions, options); + + + // Validate property names to prevent prototype pollution + const propertyNameOptions = [ + { value: built.attributeNamePrefix, name: 'attributeNamePrefix' }, + { value: built.attributesGroupName, name: 'attributesGroupName' }, + { value: built.textNodeName, name: 'textNodeName' }, + { value: built.cdataPropName, name: 'cdataPropName' }, + { value: built.commentPropName, name: 'commentPropName' } + ]; + + for (const { value, name } of propertyNameOptions) { + if (value) { + validatePropertyName(value, name); + } + } + + if (built.onDangerousProperty === null) { + built.onDangerousProperty = defaultOnDangerousProperty; + } + + // Always normalize processEntities for backward compatibility and validation + built.processEntities = normalizeProcessEntities(built.processEntities); + //console.debug(built.processEntities) + return built; + }; + + OptionsBuilder.buildOptions = buildOptions; + OptionsBuilder.defaultOptions = defaultOptions; + return OptionsBuilder; +} + +var xmlNode; +var hasRequiredXmlNode; + +function requireXmlNode () { + if (hasRequiredXmlNode) return xmlNode; + hasRequiredXmlNode = 1; + + class XmlNode{ + constructor(tagname) { + this.tagname = tagname; + this.child = []; //nested tags, text, cdata, comments in order + this[":@"] = {}; //attributes map + } + add(key,val){ + // this.child.push( {name : key, val: val, isCdata: isCdata }); + if(key === "__proto__") key = "#__proto__"; + this.child.push( {[key]: val }); + } + addChild(node) { + if(node.tagname === "__proto__") node.tagname = "#__proto__"; + if(node[":@"] && Object.keys(node[":@"]).length > 0){ + this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] }); + }else { + this.child.push( { [node.tagname]: node.child }); + } + }; + } + + xmlNode = XmlNode; + return xmlNode; +} + +var DocTypeReader_1; +var hasRequiredDocTypeReader; + +function requireDocTypeReader () { + if (hasRequiredDocTypeReader) return DocTypeReader_1; + hasRequiredDocTypeReader = 1; + const util = requireUtil(); + + class DocTypeReader { + constructor(options) { + this.suppressValidationErr = !options; + this.options = options || {}; + } + + readDocType(xmlData, i) { + const entities = Object.create(null); + let entityCount = 0; + + if (xmlData[i + 3] === 'O' && + xmlData[i + 4] === 'C' && + xmlData[i + 5] === 'T' && + xmlData[i + 6] === 'Y' && + xmlData[i + 7] === 'P' && + xmlData[i + 8] === 'E') { + + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + + for (; i < xmlData.length; i++) { + if (xmlData[i] === '<' && !comment) { //Determine the tag type + if (hasBody && hasSeq(xmlData, "!ENTITY", i)) { + i += 7; + let entityName, val; + [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) { //Parameter entities are not supported + if (this.options.enabled !== false && + this.options.maxEntityCount != null && + entityCount >= this.options.maxEntityCount) { + throw new Error( + `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})` + ); + } + //const escaped = entityName.replace(/[.\-+*:]/g, '\\.'); + const escaped = entityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + entities[entityName] = { + regx: RegExp(`&${escaped};`, "g"), + val: val + }; + entityCount++; + } + } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) { + i += 8; //Not supported + const { index } = this.readElementExp(xmlData, i + 1); + i = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) { + i += 8; //Not supported + // const {index} = this.readAttlistExp(xmlData,i+1); + // i = index; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) { + i += 9; //Not supported + const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr); + i = index; + } else if (hasSeq(xmlData, "!--", i)) { + comment = true; + } else { + throw new Error(`Invalid DOCTYPE`); + } + + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === '>') { //Read tag content + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === '[') { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + + return { entities, i }; + } + + readEntityExp(xmlData, i) { + //External entities are not supported + // + + //Parameter entities are not supported + // + + //Internal entities are supported + // + + // Skip leading whitespace after this.options.maxEntitySize) { + throw new Error( + `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})` + ); + } + + i--; + return [entityName, entityValue, i]; + } + + readNotationExp(xmlData, i) { + // Skip leading whitespace after + // + // + // + // + + // Skip leading whitespace after { + while (index < data.length && /\s/.test(data[index])) { + index++; + } + return index; + }; + + function hasSeq(data, seq, i) { + for (let j = 0; j < seq.length; j++) { + if (seq[j] !== data[i + j + 1]) return false; + } + return true; + } + + function validateEntityName(name) { + if (util.isName(name)) + return name; + else + throw new Error(`Invalid entity name ${name}`); + } + + DocTypeReader_1 = DocTypeReader; + return DocTypeReader_1; +} + +var strnum; +var hasRequiredStrnum; + +function requireStrnum () { + if (hasRequiredStrnum) return strnum; + hasRequiredStrnum = 1; + const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; + const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; + // const octRegex = /^0x[a-z0-9]+/; + // const binRegex = /0x[a-z0-9]+/; + + + const consider = { + hex : true, + // oct: false, + leadingZeros: true, + decimalPoint: "\.", + eNotation: true, + //skipLike: /regex/ + }; + + function toNumber(str, options = {}){ + options = Object.assign({}, consider, options ); + if(!str || typeof str !== "string" ) return str; + + let trimmedStr = str.trim(); + + if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; + else if(str==="0") return 0; + else if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + // }else if (options.oct && octRegex.test(str)) { + // return Number.parseInt(val, 8); + }else if (trimmedStr.search(/[eE]/)!== -1) { //eNotation + const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/); + // +00.123 => [ , '+', '00', '.123', .. + if(notation){ + // console.log(notation) + if(options.leadingZeros){ //accept with leading zeros + trimmedStr = (notation[1] || "") + notation[3]; + }else { + if(notation[2] === "0" && notation[3][0]=== ".");else { + return str; + } + } + return options.eNotation ? Number(trimmedStr) : str; + }else { + return str; + } + // }else if (options.parseBin && binRegex.test(str)) { + // return Number.parseInt(val, 2); + }else { + //separate negative sign, leading zeros, and rest number + const match = numRegex.exec(trimmedStr); + // +00.123 => [ , '+', '00', '.123', .. + if(match){ + const sign = match[1]; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros + //trim ending zeros for floating number + + if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123 + else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123 + else if(options.leadingZeros && leadingZeros===str) return 0; //00 + + else {//no leading zeros or leading zeros are allowed + const num = Number(trimmedStr); + const numStr = "" + num; + + if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation + if(options.eNotation) return num; + else return str; + }else if(trimmedStr.indexOf(".") !== -1){ //floating number + if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0 + else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000 + else if( sign && numStr === "-"+numTrimmedByZeros) return num; + else return str; + } + + if(leadingZeros){ + return (numTrimmedByZeros === numStr) || (sign+numTrimmedByZeros === numStr) ? num : str + }else { + return (trimmedStr === numStr) || (trimmedStr === sign+numStr) ? num : str + } + } + }else { //non-numeric string + return str; + } + } + } + + /** + * + * @param {string} numStr without leading zeros + * @returns + */ + function trimZeros(numStr){ + if(numStr && numStr.indexOf(".") !== -1){//float + numStr = numStr.replace(/0+$/, ""); //remove ending zeros + if(numStr === ".") numStr = "0"; + else if(numStr[0] === ".") numStr = "0"+numStr; + else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1); + return numStr; + } + return numStr; + } + + function parse_int(numStr, base){ + //polyfill + if(parseInt) return parseInt(numStr, base); + else if(Number.parseInt) return Number.parseInt(numStr, base); + else if(window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported") + } + + strnum = toNumber; + return strnum; +} + +var ignoreAttributes; +var hasRequiredIgnoreAttributes; + +function requireIgnoreAttributes () { + if (hasRequiredIgnoreAttributes) return ignoreAttributes; + hasRequiredIgnoreAttributes = 1; + function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === 'function') { + return ignoreAttributes + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === 'string' && attrName === pattern) { + return true + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true + } + } + } + } + return () => false + } + + ignoreAttributes = getIgnoreAttributesFn; + return ignoreAttributes; +} + +var OrderedObjParser_1; +var hasRequiredOrderedObjParser; + +function requireOrderedObjParser () { + if (hasRequiredOrderedObjParser) return OrderedObjParser_1; + hasRequiredOrderedObjParser = 1; + ///@ts-check + + const util = requireUtil(); + const xmlNode = requireXmlNode(); + const DocTypeReader = requireDocTypeReader(); + const toNumber = requireStrnum(); + const getIgnoreAttributesFn = requireIgnoreAttributes(); + + // const regx = + // '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)' + // .replace(/NAME/g, util.nameRegexp); + + //const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g"); + //const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g"); + + class OrderedObjParser { + constructor(options) { + this.options = options; + this.currentNode = null; + this.tagsNodeStack = []; + this.docTypeEntities = {}; + this.lastEntities = { + "apos": { regex: /&(apos|#39|#x27);/g, val: "'" }, + "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" }, + "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" }, + "quot": { regex: /&(quot|#34|#x22);/g, val: "\"" }, + }; + this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }; + this.htmlEntities = { + "space": { regex: /&(nbsp|#160);/g, val: " " }, + // "lt" : { regex: /&(lt|#60);/g, val: "<" }, + // "gt" : { regex: /&(gt|#62);/g, val: ">" }, + // "amp" : { regex: /&(amp|#38);/g, val: "&" }, + // "quot" : { regex: /&(quot|#34);/g, val: "\"" }, + // "apos" : { regex: /&(apos|#39);/g, val: "'" }, + "cent": { regex: /&(cent|#162);/g, val: "¢" }, + "pound": { regex: /&(pound|#163);/g, val: "£" }, + "yen": { regex: /&(yen|#165);/g, val: "¥" }, + "euro": { regex: /&(euro|#8364);/g, val: "€" }, + "copyright": { regex: /&(copy|#169);/g, val: "©" }, + "reg": { regex: /&(reg|#174);/g, val: "®" }, + "inr": { regex: /&(inr|#8377);/g, val: "₹" }, + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => fromCodePoint(str, 10, "&#") }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => fromCodePoint(str, 16, "&#x") }, + }; + this.addExternalEntities = addExternalEntities; + this.parseXml = parseXml; + this.parseTextData = parseTextData; + this.resolveNameSpace = resolveNameSpace; + this.buildAttributesMap = buildAttributesMap; + this.isItStopNode = isItStopNode; + this.replaceEntitiesValue = replaceEntitiesValue; + this.readStopNodeData = readStopNodeData; + this.saveTextToParentTag = saveTextToParentTag; + this.addChild = addChild; + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + + if (this.options.stopNodes && this.options.stopNodes.length > 0) { + this.stopNodesExact = new Set(); + this.stopNodesWildcard = new Set(); + for (let i = 0; i < this.options.stopNodes.length; i++) { + const stopNodeExp = this.options.stopNodes[i]; + if (typeof stopNodeExp !== 'string') continue; + if (stopNodeExp.startsWith("*.")) { + this.stopNodesWildcard.add(stopNodeExp.substring(2)); + } else { + this.stopNodesExact.add(stopNodeExp); + } + } + } + } + + } + + function addExternalEntities(externalEntities) { + const entKeys = Object.keys(externalEntities); + for (let i = 0; i < entKeys.length; i++) { + const ent = entKeys[i]; + const escaped = ent.replace(/[.\-+*:]/g, '\\.'); + this.lastEntities[ent] = { + regex: new RegExp("&" + escaped + ";", "g"), + val: externalEntities[ent] + }; + } + } + + /** + * @param {string} val + * @param {string} tagName + * @param {string} jPath + * @param {boolean} dontTrim + * @param {boolean} hasAttributes + * @param {boolean} isLeafNode + * @param {boolean} escapeEntities + */ + function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) { + if (val !== undefined) { + if (this.options.trimValues && !dontTrim) { + val = val.trim(); + } + if (val.length > 0) { + if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath); + + const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode); + if (newval === null || newval === undefined) { + //don't parse + return val; + } else if (typeof newval !== typeof val || newval !== val) { + //overwrite + return newval; + } else if (this.options.trimValues) { + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + } else { + const trimmedVal = val.trim(); + if (trimmedVal === val) { + return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions); + } else { + return val; + } + } + } + } + } + + function resolveNameSpace(tagname) { + if (this.options.removeNSPrefix) { + const tags = tagname.split(':'); + const prefix = tagname.charAt(0) === '/' ? '/' : ''; + if (tags[0] === 'xmlns') { + return ''; + } + if (tags.length === 2) { + tagname = prefix + tags[1]; + } + } + return tagname; + } + + //TODO: change regex to capture NS + //const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm"); + const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm'); + + function buildAttributesMap(attrStr, jPath, tagName) { + if (this.options.ignoreAttributes !== true && typeof attrStr === 'string') { + // attrStr = attrStr.replace(/\r?\n/g, ' '); + //attrStr = attrStr || attrStr.trim(); + + const matches = util.getAllMatches(attrStr, attrsRegx); + const len = matches.length; //don't make it inline + const attrs = {}; + for (let i = 0; i < len; i++) { + const attrName = this.resolveNameSpace(matches[i][1]); + if (this.ignoreAttributesFn(attrName, jPath)) { + continue + } + let oldVal = matches[i][4]; + let aName = this.options.attributeNamePrefix + attrName; + if (attrName.length) { + if (this.options.transformAttributeName) { + aName = this.options.transformAttributeName(aName); + } + aName = sanitizeName(aName, this.options); + if (oldVal !== undefined) { + if (this.options.trimValues) { + oldVal = oldVal.trim(); + } + oldVal = this.replaceEntitiesValue(oldVal, tagName, jPath); + const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath); + if (newVal === null || newVal === undefined) { + //don't parse + attrs[aName] = oldVal; + } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) { + //overwrite + attrs[aName] = newVal; + } else { + //parse + attrs[aName] = parseValue( + oldVal, + this.options.parseAttributeValue, + this.options.numberParseOptions + ); + } + } else if (this.options.allowBooleanAttributes) { + attrs[aName] = true; + } + } + } + if (!Object.keys(attrs).length) { + return; + } + if (this.options.attributesGroupName) { + const attrCollection = {}; + attrCollection[this.options.attributesGroupName] = attrs; + return attrCollection; + } + return attrs + } + } + + const parseXml = function (xmlData) { + xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line + const xmlObj = new xmlNode('!xml'); + let currentNode = xmlObj; + let textData = ""; + let jPath = ""; + + // Reset entity expansion counters for this document + this.entityExpansionCount = 0; + this.currentExpandedLength = 0; + + const docTypeReader = new DocTypeReader(this.options.processEntities); + for (let i = 0; i < xmlData.length; i++) {//for each char in XML data + const ch = xmlData[i]; + if (ch === '<') { + // const nextIndex = i+1; + // const _2ndChar = xmlData[nextIndex]; + if (xmlData[i + 1] === '/') {//Closing Tag + const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed."); + let tagName = xmlData.substring(i + 2, closeIndex).trim(); + + if (this.options.removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + } + } + + if (this.options.transformTagName) { + tagName = this.options.transformTagName(tagName); + } + + if (currentNode) { + textData = this.saveTextToParentTag(textData, currentNode, jPath); + } + + //check if last tag of nested tag was unpaired tag + const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1); + if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) { + throw new Error(`Unpaired tag can not be used as closing tag: `); + } + let propIndex = 0; + if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) { + propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.') - 1); + this.tagsNodeStack.pop(); + } else { + propIndex = jPath.lastIndexOf("."); + } + jPath = jPath.substring(0, propIndex); + + currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope + textData = ""; + i = closeIndex; + } else if (xmlData[i + 1] === '?') { + + let tagData = readTagExp(xmlData, i, false, "?>"); + if (!tagData) throw new Error("Pi Tag is not closed."); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + if ((this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags) ; else { + + const childNode = new xmlNode(tagData.tagName); + childNode.add(this.options.textNodeName, ""); + + if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + } + this.addChild(currentNode, childNode, jPath, i); + } + + + i = tagData.closeIndex + 1; + } else if (xmlData.substr(i + 1, 3) === '!--') { + const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed."); + if (this.options.commentPropName) { + const comment = xmlData.substring(i + 4, endIndex - 2); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + + currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]); + } + i = endIndex; + } else if (xmlData.substr(i + 1, 2) === '!D') { + const result = docTypeReader.readDocType(xmlData, i); + this.docTypeEntities = result.entities; + i = result.i; + } else if (xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2; + const tagExp = xmlData.substring(i + 9, closeIndex); + + textData = this.saveTextToParentTag(textData, currentNode, jPath); + + let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true); + if (val == undefined) val = ""; + + //cdata should be set even if it is 0 length string + if (this.options.cdataPropName) { + currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); + } else { + currentNode.add(this.options.textNodeName, val); + } + + i = closeIndex + 2; + } else {//Opening tag + let result = readTagExp(xmlData, i, this.options.removeNSPrefix); + let tagName = result.tagName; + const rawTagName = result.rawTagName; + let tagExp = result.tagExp; + let attrExpPresent = result.attrExpPresent; + let closeIndex = result.closeIndex; + + if (this.options.transformTagName) { + //console.log(tagExp, tagName) + const newTagName = this.options.transformTagName(tagName); + if (tagExp === tagName) { + tagExp = newTagName; + } + tagName = newTagName; + } + + if (this.options.strictReservedNames && + (tagName === this.options.commentPropName + || tagName === this.options.cdataPropName + || tagName === this.options.textNodeName + || tagName === this.options.attributesGroupName + )) { + throw new Error(`Invalid tag name: ${tagName}`); + } + + //save text as child node + if (currentNode && textData) { + if (currentNode.tagname !== '!xml') { + //when nested tag is found + textData = this.saveTextToParentTag(textData, currentNode, jPath, false); + } + } + + //check if last tag was unpaired tag + const lastTag = currentNode; + if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) { + currentNode = this.tagsNodeStack.pop(); + jPath = jPath.substring(0, jPath.lastIndexOf(".")); + } + if (tagName !== xmlObj.tagname) { + jPath += jPath ? "." + tagName : tagName; + } + const startIndex = i; + if (this.isItStopNode(this.stopNodesExact, this.stopNodesWildcard, jPath, tagName)) { + let tagContent = ""; + //self-closing tag + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + i = result.closeIndex; + } + //unpaired tag + else if (this.options.unpairedTags.indexOf(tagName) !== -1) { + + i = result.closeIndex; + } + //normal tag + else { + //read until closing tag is found + const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1); + if (!result) throw new Error(`Unexpected end of ${rawTagName}`); + i = result.i; + tagContent = result.tagContent; + } + + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + if (tagContent) { + tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); + } + + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + childNode.add(this.options.textNodeName, tagContent); + + this.addChild(currentNode, childNode, jPath, startIndex); + } else { + //selfClosing tag + if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { + if (tagName[tagName.length - 1] === "/") { //remove trailing '/' + tagName = tagName.substr(0, tagName.length - 1); + jPath = jPath.substr(0, jPath.length - 1); + tagExp = tagName; + } else { + tagExp = tagExp.substr(0, tagExp.length - 1); + } + + if (this.options.transformTagName) { + const newTagName = this.options.transformTagName(tagName); + if (tagExp === tagName) { + tagExp = newTagName; + } + tagName = newTagName; + } + + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath, startIndex); + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + } + else if (this.options.unpairedTags.indexOf(tagName) !== -1) {//unpaired tag + const childNode = new xmlNode(tagName); + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath); + } + this.addChild(currentNode, childNode, jPath, startIndex); + jPath = jPath.substr(0, jPath.lastIndexOf(".")); + i = result.closeIndex; + // Continue to next iteration without changing currentNode + continue; + } + //opening tag + else { + const childNode = new xmlNode(tagName); + if (this.tagsNodeStack.length > this.options.maxNestedTags) { + throw new Error("Maximum nested tags exceeded"); + } + this.tagsNodeStack.push(currentNode); + + if (tagName !== tagExp && attrExpPresent) { + childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + } + this.addChild(currentNode, childNode, jPath); + currentNode = childNode; + } + textData = ""; + i = closeIndex; + } + } + } else { + textData += xmlData[i]; + } + } + return xmlObj.child; + }; + + function addChild(currentNode, childNode, jPath, startIndex) { + // unset startIndex if not requested + if (!this.options.captureMetaData) startIndex = undefined; + const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]); + if (result === false) ; else if (typeof result === "string") { + childNode.tagname = result; + currentNode.addChild(childNode, startIndex); + } else { + currentNode.addChild(childNode, startIndex); + } + } + + const replaceEntitiesValue = function (val, tagName, jPath) { + // Performance optimization: Early return if no entities to replace + if (val.indexOf('&') === -1) { + return val; + } + + const entityConfig = this.options.processEntities; + + if (!entityConfig.enabled) { + return val; + } + + // Check tag-specific filtering + if (entityConfig.allowedTags) { + if (!entityConfig.allowedTags.includes(tagName)) { + return val; // Skip entity replacement for current tag as not set + } + } + + if (entityConfig.tagFilter) { + if (!entityConfig.tagFilter(tagName, jPath)) { + return val; // Skip based on custom filter + } + } + + // Replace DOCTYPE entities + for (let entityName in this.docTypeEntities) { + const entity = this.docTypeEntities[entityName]; + const matches = val.match(entity.regx); + + if (matches) { + // Track expansions + this.entityExpansionCount += matches.length; + + // Check expansion limit + if (entityConfig.maxTotalExpansions && + this.entityExpansionCount > entityConfig.maxTotalExpansions) { + throw new Error( + `Entity expansion limit exceeded: ${this.entityExpansionCount} > ${entityConfig.maxTotalExpansions}` + ); + } + + // Store length before replacement + const lengthBefore = val.length; + val = val.replace(entity.regx, entity.val); + + // Check expanded length immediately after replacement + if (entityConfig.maxExpandedLength) { + this.currentExpandedLength += (val.length - lengthBefore); + + if (this.currentExpandedLength > entityConfig.maxExpandedLength) { + throw new Error( + `Total expanded content size exceeded: ${this.currentExpandedLength} > ${entityConfig.maxExpandedLength}` + ); + } + } + } + } + if (val.indexOf('&') === -1) return val; // Early exit + + // Replace standard entities + for (const entityName of Object.keys(this.lastEntities)) { + const entity = this.lastEntities[entityName]; + const matches = val.match(entity.regex); + if (matches) { + this.entityExpansionCount += matches.length; + if (entityConfig.maxTotalExpansions && + this.entityExpansionCount > entityConfig.maxTotalExpansions) { + throw new Error( + `Entity expansion limit exceeded: ${this.entityExpansionCount} > ${entityConfig.maxTotalExpansions}` + ); + } + } + val = val.replace(entity.regex, entity.val); + } + if (val.indexOf('&') === -1) return val; // Early exit + + // Replace HTML entities if enabled + if (this.options.htmlEntities) { + for (const entityName of Object.keys(this.htmlEntities)) { + const entity = this.htmlEntities[entityName]; + const matches = val.match(entity.regex); + if (matches) { + //console.log(matches); + this.entityExpansionCount += matches.length; + if (entityConfig.maxTotalExpansions && + this.entityExpansionCount > entityConfig.maxTotalExpansions) { + throw new Error( + `Entity expansion limit exceeded: ${this.entityExpansionCount} > ${entityConfig.maxTotalExpansions}` + ); + } + } + val = val.replace(entity.regex, entity.val); + } + } + + // Replace ampersand entity last + val = val.replace(this.ampEntity.regex, this.ampEntity.val); + + return val; + }; + + function saveTextToParentTag(textData, parentNode, jPath, isLeafNode) { + if (textData) { //store previously collected data as textNode + if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0; + + textData = this.parseTextData(textData, + parentNode.tagname, + jPath, + false, + parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, + isLeafNode); + + if (textData !== undefined && textData !== "") + parentNode.add(this.options.textNodeName, textData); + textData = ""; + } + return textData; + } + + //TODO: use jPath to simplify the logic + /** + * @param {Set} stopNodesExact + * @param {Set} stopNodesWildcard + * @param {string} jPath + * @param {string} currentTagName + */ + function isItStopNode(stopNodesExact, stopNodesWildcard, jPath, currentTagName) { + if (stopNodesWildcard && stopNodesWildcard.has(currentTagName)) return true; + if (stopNodesExact && stopNodesExact.has(jPath)) return true; + return false; + } + + /** + * Returns the tag Expression and where it is ending handling single-double quotes situation + * @param {string} xmlData + * @param {number} i starting index + * @returns + */ + function tagExpWithClosingIndex(xmlData, i, closingChar = ">") { + let attrBoundary; + let tagExp = ""; + for (let index = i; index < xmlData.length; index++) { + let ch = xmlData[index]; + if (attrBoundary) { + if (ch === attrBoundary) attrBoundary = "";//reset + } else if (ch === '"' || ch === "'") { + attrBoundary = ch; + } else if (ch === closingChar[0]) { + if (closingChar[1]) { + if (xmlData[index + 1] === closingChar[1]) { + return { + data: tagExp, + index: index + } + } + } else { + return { + data: tagExp, + index: index + } + } + } else if (ch === '\t') { + ch = " "; + } + tagExp += ch; + } + } + + function findClosingIndex(xmlData, str, i, errMsg) { + const closingIndex = xmlData.indexOf(str, i); + if (closingIndex === -1) { + throw new Error(errMsg) + } else { + return closingIndex + str.length - 1; + } + } + + function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { + const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); + if (!result) return; + let tagExp = result.data; + const closeIndex = result.index; + const separatorIndex = tagExp.search(/\s/); + let tagName = tagExp; + let attrExpPresent = true; + if (separatorIndex !== -1) {//separate tag name and attributes expression + tagName = tagExp.substring(0, separatorIndex); + tagExp = tagExp.substring(separatorIndex + 1).trimStart(); + } + + const rawTagName = tagName; + if (removeNSPrefix) { + const colonIndex = tagName.indexOf(":"); + if (colonIndex !== -1) { + tagName = tagName.substr(colonIndex + 1); + attrExpPresent = tagName !== result.data.substr(colonIndex + 1); + } + } + + return { + tagName: tagName, + tagExp: tagExp, + closeIndex: closeIndex, + attrExpPresent: attrExpPresent, + rawTagName: rawTagName, + } + } + /** + * find paired tag for a stop node + * @param {string} xmlData + * @param {string} tagName + * @param {number} i + */ + function readStopNodeData(xmlData, tagName, i) { + const startIndex = i; + // Starting at 1 since we already have an open tag + let openTagCount = 1; + + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "/") {//close tag + const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`); + let closeTagName = xmlData.substring(i + 2, closeIndex).trim(); + if (closeTagName === tagName) { + openTagCount--; + if (openTagCount === 0) { + return { + tagContent: xmlData.substring(startIndex, i), + i: closeIndex + } + } + } + i = closeIndex; + } else if (xmlData[i + 1] === '?') { + const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 3) === '!--') { + const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed."); + i = closeIndex; + } else if (xmlData.substr(i + 1, 2) === '![') { + const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2; + i = closeIndex; + } else { + const tagData = readTagExp(xmlData, i, '>'); + + if (tagData) { + const openTagName = tagData && tagData.tagName; + if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") { + openTagCount++; + } + i = tagData.closeIndex; + } + } + } + }//end for loop + } + + function parseValue(val, shouldParse, options) { + if (shouldParse && typeof val === 'string') { + //console.log(options) + const newval = val.trim(); + if (newval === 'true') return true; + else if (newval === 'false') return false; + else return toNumber(val, options); + } else { + if (util.isExist(val)) { + return val; + } else { + return ''; + } + } + } + + function fromCodePoint(str, base, prefix) { + const codePoint = Number.parseInt(str, base); + + if (codePoint >= 0 && codePoint <= 0x10FFFF) { + return String.fromCodePoint(codePoint); + } else { + return prefix + str + ";"; + } + } + + function sanitizeName(name, options) { + if (util.criticalProperties.includes(name)) { + throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`); + } else if (util.DANGEROUS_PROPERTY_NAMES.includes(name)) { + return options.onDangerousProperty(name); + } + return name; + } + + OrderedObjParser_1 = OrderedObjParser; + return OrderedObjParser_1; +} + +var node2json = {}; + +var hasRequiredNode2json; + +function requireNode2json () { + if (hasRequiredNode2json) return node2json; + hasRequiredNode2json = 1; + + /** + * + * @param {array} node + * @param {any} options + * @returns + */ + function prettify(node, options){ + return compress( node, options); + } + + /** + * + * @param {array} arr + * @param {object} options + * @param {string} jPath + * @returns object + */ + function compress(arr, options, jPath){ + let text; + const compressedObj = {}; + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const property = propName(tagObj); + let newJpath = ""; + if(jPath === undefined) newJpath = property; + else newJpath = jPath + "." + property; + + if(property === options.textNodeName){ + if(text === undefined) text = tagObj[property]; + else text += "" + tagObj[property]; + }else if(property === undefined){ + continue; + }else if(tagObj[property]){ + + let val = compress(tagObj[property], options, newJpath); + const isLeaf = isLeafTag(val, options); + + if(tagObj[":@"]){ + assignAttributes( val, tagObj[":@"], newJpath, options); + }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){ + val = val[options.textNodeName]; + }else if(Object.keys(val).length === 0){ + if(options.alwaysCreateTextNode) val[options.textNodeName] = ""; + else val = ""; + } + + if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) { + if(!Array.isArray(compressedObj[property])) { + compressedObj[property] = [ compressedObj[property] ]; + } + compressedObj[property].push(val); + }else { + //TODO: if a node is not an array, then check if it should be an array + //also determine if it is a leaf node + if (options.isArray(property, newJpath, isLeaf )) { + compressedObj[property] = [val]; + }else { + compressedObj[property] = val; + } + } + } + + } + // if(text && text.length > 0) compressedObj[options.textNodeName] = text; + if(typeof text === "string"){ + if(text.length > 0) compressedObj[options.textNodeName] = text; + }else if(text !== undefined) compressedObj[options.textNodeName] = text; + return compressedObj; + } + + function propName(obj){ + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if(key !== ":@") return key; + } + } + + function assignAttributes(obj, attrMap, jpath, options){ + if (attrMap) { + const keys = Object.keys(attrMap); + const len = keys.length; //don't make it inline + for (let i = 0; i < len; i++) { + const atrrName = keys[i]; + if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) { + obj[atrrName] = [ attrMap[atrrName] ]; + } else { + obj[atrrName] = attrMap[atrrName]; + } + } + } + } + + function isLeafTag(obj, options){ + const { textNodeName } = options; + const propCount = Object.keys(obj).length; + + if (propCount === 0) { + return true; + } + + if ( + propCount === 1 && + (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0) + ) { + return true; + } + + return false; + } + node2json.prettify = prettify; + return node2json; +} + +var XMLParser_1; +var hasRequiredXMLParser; + +function requireXMLParser () { + if (hasRequiredXMLParser) return XMLParser_1; + hasRequiredXMLParser = 1; + const { buildOptions} = requireOptionsBuilder(); + const OrderedObjParser = requireOrderedObjParser(); + const { prettify} = requireNode2json(); + const validator = requireValidator(); + + class XMLParser{ + + constructor(options){ + this.externalEntities = {}; + this.options = buildOptions(options); + + } + /** + * Parse XML dats to JS object + * @param {string|Buffer} xmlData + * @param {boolean|Object} validationOption + */ + parse(xmlData,validationOption){ + if(typeof xmlData === "string");else if( xmlData.toString){ + xmlData = xmlData.toString(); + }else { + throw new Error("XML data is accepted in String or Bytes[] form.") + } + if( validationOption){ + if(validationOption === true) validationOption = {}; //validate with default options + + const result = validator.validate(xmlData, validationOption); + if (result !== true) { + throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` ) + } + } + const orderedObjParser = new OrderedObjParser(this.options); + orderedObjParser.addExternalEntities(this.externalEntities); + const orderedResult = orderedObjParser.parseXml(xmlData); + if(this.options.preserveOrder || orderedResult === undefined) return orderedResult; + else return prettify(orderedResult, this.options); + } + + /** + * Add Entity which is not by default supported by this library + * @param {string} key + * @param {string} value + */ + addEntity(key, value){ + if(value.indexOf("&") !== -1){ + throw new Error("Entity value can't have '&'") + }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){ + throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '") + }else if(value === "&"){ + throw new Error("An entity with value '&' is not permitted"); + }else { + this.externalEntities[key] = value; + } + } + } + + XMLParser_1 = XMLParser; + return XMLParser_1; +} + +var orderedJs2Xml; +var hasRequiredOrderedJs2Xml; + +function requireOrderedJs2Xml () { + if (hasRequiredOrderedJs2Xml) return orderedJs2Xml; + hasRequiredOrderedJs2Xml = 1; + const EOL = "\n"; + + /** + * + * @param {array} jArray + * @param {any} options + * @returns + */ + function toXml(jArray, options) { + let indentation = ""; + if (options.format && options.indentBy.length > 0) { + indentation = EOL; + } + return arrToStr(jArray, options, "", indentation); + } + + function arrToStr(arr, options, jPath, indentation) { + let xmlStr = ""; + let isPreviousElementTag = false; + + + if (!Array.isArray(arr)) { + // Non-array values (e.g. string tag values) should be treated as text content + if (arr !== undefined && arr !== null) { + let text = arr.toString(); + text = replaceEntitiesValue(text, options); + return text; + } + return ""; + } + + for (let i = 0; i < arr.length; i++) { + const tagObj = arr[i]; + const tagName = propName(tagObj); + if (tagName === undefined) continue; + + let newJPath = ""; + if (jPath.length === 0) newJPath = tagName; + else newJPath = `${jPath}.${tagName}`; + + if (tagName === options.textNodeName) { + let tagText = tagObj[tagName]; + if (!isStopNode(newJPath, options)) { + tagText = options.tagValueProcessor(tagName, tagText); + tagText = replaceEntitiesValue(tagText, options); + } + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += tagText; + isPreviousElementTag = false; + continue; + } else if (tagName === options.cdataPropName) { + if (isPreviousElementTag) { + xmlStr += indentation; + } + xmlStr += ``; + isPreviousElementTag = false; + continue; + } else if (tagName === options.commentPropName) { + xmlStr += indentation + ``; + isPreviousElementTag = true; + continue; + } else if (tagName[0] === "?") { + const attStr = attr_to_str(tagObj[":@"], options); + const tempInd = tagName === "?xml" ? "" : indentation; + let piTextNodeName = tagObj[tagName][0][options.textNodeName]; + piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing + xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`; + isPreviousElementTag = true; + continue; + } + let newIdentation = indentation; + if (newIdentation !== "") { + newIdentation += options.indentBy; + } + const attStr = attr_to_str(tagObj[":@"], options); + const tagStart = indentation + `<${tagName}${attStr}`; + const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); + if (options.unpairedTags.indexOf(tagName) !== -1) { + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; + } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { + xmlStr += tagStart + "/>"; + } else if (tagValue && tagValue.endsWith(">")) { + xmlStr += tagStart + `>${tagValue}${indentation}`; + } else { + xmlStr += tagStart + ">"; + if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("`; + } + isPreviousElementTag = true; + } + + return xmlStr; + } + + function propName(obj) { + const keys = Object.keys(obj); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; + if (key !== ":@") return key; + } + } + + function attr_to_str(attrMap, options) { + let attrStr = ""; + if (attrMap && !options.ignoreAttributes) { + for (let attr in attrMap) { + if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue; + let attrVal = options.attributeValueProcessor(attr, attrMap[attr]); + attrVal = replaceEntitiesValue(attrVal, options); + if (attrVal === true && options.suppressBooleanAttributes) { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`; + } else { + attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`; + } + } + } + return attrStr; + } + + function isStopNode(jPath, options) { + jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); + let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); + for (let index in options.stopNodes) { + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; + } + return false; + } + + function replaceEntitiesValue(textValue, options) { + if (textValue && textValue.length > 0 && options.processEntities) { + for (let i = 0; i < options.entities.length; i++) { + const entity = options.entities[i]; + textValue = textValue.replace(entity.regex, entity.val); + } + } + return textValue; + } + orderedJs2Xml = toXml; + return orderedJs2Xml; +} + +var json2xml; +var hasRequiredJson2xml; + +function requireJson2xml () { + if (hasRequiredJson2xml) return json2xml; + hasRequiredJson2xml = 1; + //parse Empty Node as self closing node + const buildFromOrderedJs = requireOrderedJs2Xml(); + const getIgnoreAttributesFn = requireIgnoreAttributes(); + + const defaultOptions = { + attributeNamePrefix: '@_', + attributesGroupName: false, + textNodeName: '#text', + ignoreAttributes: true, + cdataPropName: false, + format: false, + indentBy: ' ', + suppressEmptyNode: false, + suppressUnpairedNode: true, + suppressBooleanAttributes: true, + tagValueProcessor: function(key, a) { + return a; + }, + attributeValueProcessor: function(attrName, a) { + return a; + }, + preserveOrder: false, + commentPropName: false, + unpairedTags: [], + entities: [ + { regex: new RegExp("&", "g"), val: "&" },//it must be on top + { regex: new RegExp(">", "g"), val: ">" }, + { regex: new RegExp("<", "g"), val: "<" }, + { regex: new RegExp("\'", "g"), val: "'" }, + { regex: new RegExp("\"", "g"), val: """ } + ], + processEntities: true, + stopNodes: [], + // transformTagName: false, + // transformAttributeName: false, + oneListGroup: false + }; + + function Builder(options) { + this.options = Object.assign({}, defaultOptions, options); + if (this.options.ignoreAttributes === true || this.options.attributesGroupName) { + this.isAttribute = function(/*a*/) { + return false; + }; + } else { + this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + this.attrPrefixLen = this.options.attributeNamePrefix.length; + this.isAttribute = isAttribute; + } + + this.processTextOrObjNode = processTextOrObjNode; + + if (this.options.format) { + this.indentate = indentate; + this.tagEndChar = '>\n'; + this.newLine = '\n'; + } else { + this.indentate = function() { + return ''; + }; + this.tagEndChar = '>'; + this.newLine = ''; + } + } + + Builder.prototype.build = function(jObj) { + if(this.options.preserveOrder){ + return buildFromOrderedJs(jObj, this.options); + }else { + if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){ + jObj = { + [this.options.arrayNodeName] : jObj + }; + } + return this.j2x(jObj, 0, []).val; + } + }; + + Builder.prototype.j2x = function(jObj, level, ajPath) { + let attrStr = ''; + let val = ''; + const jPath = ajPath.join('.'); + for (let key in jObj) { + if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue; + if (typeof jObj[key] === 'undefined') { + // supress undefined node only if it is not an attribute + if (this.isAttribute(key)) { + val += ''; + } + } else if (jObj[key] === null) { + // null attribute should be ignored by the attribute list, but should not cause the tag closing + if (this.isAttribute(key)) { + val += ''; + } else if (key === this.options.cdataPropName) { + val += ''; + } else if (key[0] === '?') { + val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + } else { + val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (jObj[key] instanceof Date) { + val += this.buildTextValNode(jObj[key], key, '', level); + } else if (typeof jObj[key] !== 'object') { + //premitive type + const attr = this.isAttribute(key); + if (attr && !this.ignoreAttributesFn(attr, jPath)) { + attrStr += this.buildAttrPairStr(attr, '' + jObj[key]); + } else if (!attr) { + //tag value + if (key === this.options.textNodeName) { + let newval = this.options.tagValueProcessor(key, '' + jObj[key]); + val += this.replaceEntitiesValue(newval); + } else { + val += this.buildTextValNode(jObj[key], key, '', level); + } + } + } else if (Array.isArray(jObj[key])) { + //repeated nodes + const arrLen = jObj[key].length; + let listTagVal = ""; + let listTagAttr = ""; + for (let j = 0; j < arrLen; j++) { + const item = jObj[key][j]; + if (typeof item === 'undefined') ; else if (item === null) { + if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar; + else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar; + } else if (typeof item === 'object') { + if(this.options.oneListGroup){ + const result = this.j2x(item, level + 1, ajPath.concat(key)); + listTagVal += result.val; + if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) { + listTagAttr += result.attrStr; + } + }else { + listTagVal += this.processTextOrObjNode(item, key, level, ajPath); + } + } else { + if (this.options.oneListGroup) { + let textValue = this.options.tagValueProcessor(key, item); + textValue = this.replaceEntitiesValue(textValue); + listTagVal += textValue; + } else { + listTagVal += this.buildTextValNode(item, key, '', level); + } + } + } + if(this.options.oneListGroup){ + listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level); + } + val += listTagVal; + } else { + //nested node + if (this.options.attributesGroupName && key === this.options.attributesGroupName) { + const Ks = Object.keys(jObj[key]); + const L = Ks.length; + for (let j = 0; j < L; j++) { + attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]); + } + } else { + val += this.processTextOrObjNode(jObj[key], key, level, ajPath); + } + } + } + return {attrStr: attrStr, val: val}; + }; + + Builder.prototype.buildAttrPairStr = function(attrName, val){ + val = this.options.attributeValueProcessor(attrName, '' + val); + val = this.replaceEntitiesValue(val); + if (this.options.suppressBooleanAttributes && val === "true") { + return ' ' + attrName; + } else return ' ' + attrName + '="' + val + '"'; + }; + + function processTextOrObjNode (object, key, level, ajPath) { + const result = this.j2x(object, level + 1, ajPath.concat(key)); + if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) { + return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level); + } else { + return this.buildObjectNode(result.val, key, result.attrStr, level); + } + } + + Builder.prototype.buildObjectNode = function(val, key, attrStr, level) { + if(val === ""){ + if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + else { + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + } + }else { + + let tagEndExp = '' + val + tagEndExp ); + } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) { + return this.indentate(level) + `` + this.newLine; + }else { + return ( + this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar + + val + + this.indentate(level) + tagEndExp ); + } + } + }; + + Builder.prototype.closeTag = function(key){ + let closeTag = ""; + if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired + if(!this.options.suppressUnpairedNode) closeTag = "/"; + }else if(this.options.suppressEmptyNode){ //empty + closeTag = "/"; + }else { + closeTag = `>` + this.newLine; + }else if (this.options.commentPropName !== false && key === this.options.commentPropName) { + return this.indentate(level) + `` + this.newLine; + }else if(key[0] === "?") {//PI tag + return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar; + }else { + let textValue = this.options.tagValueProcessor(key, val); + textValue = this.replaceEntitiesValue(textValue); + + if( textValue === ''){ + return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar; + }else { + return this.indentate(level) + '<' + key + attrStr + '>' + + textValue + + ' 0 && this.options.processEntities){ + for (let i=0; i XML.platformSpecificXML(args)); + } + static platformSpecificXML(args) { + let result; + let error; + let obj; + try { + if (typeof args[0] === 'string') { + obj = JSON.parse(args[0]); + } + else if (typeof args[0] === 'object') { + obj = args[0]; + } + const parser = new fast_xml_parser_1.XMLBuilder({ + indentBy: ' ', + format: true, + }); + result = `\n${parser.build(obj)}`.trim(); + } + catch (_a) { + error = `${args[0]} is not a valid json`; + } + return { value: result, error: error }; + } + } + xml.XML = XML; + + return xml; +} + +var xpath$1 = {}; + +var xpath = {}; + +/* + * xpath.js + * + * An XPath 1.0 library for JavaScript. + * + * Cameron McCormack + * + * This work is licensed under the MIT License. + * + * Revision 20: April 26, 2011 + * Fixed a typo resulting in FIRST_ORDERED_NODE_TYPE results being wrong, + * thanks to . + * + * Revision 19: November 29, 2005 + * Nodesets now store their nodes in a height balanced tree, increasing + * performance for the common case of selecting nodes in document order, + * thanks to Sébastien Cramatte . + * AVL tree code adapted from Raimund Neumann . + * + * Revision 18: October 27, 2005 + * DOM 3 XPath support. Caveats: + * - namespace prefixes aren't resolved in XPathEvaluator.createExpression, + * but in XPathExpression.evaluate. + * - XPathResult.invalidIteratorState is not implemented. + * + * Revision 17: October 25, 2005 + * Some core XPath function fixes and a patch to avoid crashing certain + * versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to + * Sébastien Cramatte . + * + * Revision 16: September 22, 2005 + * Workarounds for some IE 5.5 deficiencies. + * Fixed problem with prefix node tests on attribute nodes. + * + * Revision 15: May 21, 2005 + * Fixed problem with QName node tests on elements with an xmlns="...". + * + * Revision 14: May 19, 2005 + * Fixed QName node tests on attribute node regression. + * + * Revision 13: May 3, 2005 + * Node tests are case insensitive now if working in an HTML DOM. + * + * Revision 12: April 26, 2005 + * Updated licence. Slight code changes to enable use of Dean + * Edwards' script compression, http://dean.edwards.name/packer/ . + * + * Revision 11: April 23, 2005 + * Fixed bug with 'and' and 'or' operators, fix thanks to + * Sandy McArthur . + * + * Revision 10: April 15, 2005 + * Added support for a virtual root node, supposedly helpful for + * implementing XForms. Fixed problem with QName node tests and + * the parent axis. + * + * Revision 9: March 17, 2005 + * Namespace resolver tweaked so using the document node as the context + * for namespace lookups is equivalent to using the document element. + * + * Revision 8: February 13, 2005 + * Handle implicit declaration of 'xmlns' namespace prefix. + * Fixed bug when comparing nodesets. + * Instance data can now be associated with a FunctionResolver, and + * workaround for MSXML not supporting 'localName' and 'getElementById', + * thanks to Grant Gongaware. + * Fix a few problems when the context node is the root node. + * + * Revision 7: February 11, 2005 + * Default namespace resolver fix from Grant Gongaware + * . + * + * Revision 6: February 10, 2005 + * Fixed bug in 'number' function. + * + * Revision 5: February 9, 2005 + * Fixed bug where text nodes not getting converted to string values. + * + * Revision 4: January 21, 2005 + * Bug in 'name' function, fix thanks to Bill Edney. + * Fixed incorrect processing of namespace nodes. + * Fixed NamespaceResolver to resolve 'xml' namespace. + * Implemented union '|' operator. + * + * Revision 3: January 14, 2005 + * Fixed bug with nodeset comparisons, bug lexing < and >. + * + * Revision 2: October 26, 2004 + * QName node test namespace handling fixed. Few other bug fixes. + * + * Revision 1: August 13, 2004 + * Bug fixes from William J. Edney . + * Added minimal licence. + * + * Initial version: June 14, 2004 + */ + +var hasRequiredXpath$1; + +function requireXpath$1 () { + if (hasRequiredXpath$1) return xpath; + hasRequiredXpath$1 = 1; + (function (exports) { + // non-node wrapper + var xpath = exports; + + (function (exports) { + + // namespace nodes are not part of the DOM spec, so we use a custom nodetype for them. + // should NOT be used externally + var NAMESPACE_NODE_NODETYPE = '__namespace'; + + var isNil = function (x) { + return x === null || x === undefined; + }; + + var isValidNodeType = function (nodeType) { + return nodeType === NAMESPACE_NODE_NODETYPE || + (Number.isInteger(nodeType) + && nodeType >= 1 + && nodeType <= 11 + ); + }; + + var isNodeLike = function (value) { + return value + && isValidNodeType(value.nodeType) + && typeof value.nodeName === "string"; + }; + + // functional helpers + function curry(func) { + var slice = Array.prototype.slice, + totalargs = func.length, + partial = function (args, fn) { + return function () { + return fn.apply(this, args.concat(slice.call(arguments))); + } + }, + fn = function () { + var args = slice.call(arguments); + return (args.length < totalargs) ? + partial(args, fn) : + func.apply(this, slice.apply(arguments, [0, totalargs])); + }; + return fn; + } + + var forEach = function (f, xs) { + for (var i = 0; i < xs.length; i += 1) { + f(xs[i], i, xs); + } + }; + + var reduce = function (f, seed, xs) { + var acc = seed; + + forEach(function (x, i) { acc = f(acc, x, i); }, xs); + + return acc; + }; + + var map = function (f, xs) { + var mapped = new Array(xs.length); + + forEach(function (x, i) { mapped[i] = f(x); }, xs); + + return mapped; + }; + + var filter = function (f, xs) { + var filtered = []; + + forEach(function (x, i) { if (f(x, i)) { filtered.push(x); } }, xs); + + return filtered; + }; + + var includes = function (values, value) { + for (var i = 0; i < values.length; i += 1) { + if (values[i] === value) { + return true; + } + } + + return false; + }; + + function always(value) { return function () { return value; } } + + function toString(x) { return x.toString(); } + var join = function (s, xs) { return xs.join(s); }; + var wrap = function (pref, suf, str) { return pref + str + suf; }; + + var prototypeConcat = Array.prototype.concat; + + var sortNodes = function (nodes, reverse) { + var ns = new XNodeSet(); + + ns.addArray(nodes); + + var sorted = ns.toArray(); + + return reverse ? sorted.reverse() : sorted; + }; + + // .apply() fails above a certain number of arguments - https://github.com/goto100/xpath/pull/98 + var MAX_ARGUMENT_LENGTH = 32767; + + function flatten(arr) { + var result = []; + + for (var start = 0; start < arr.length; start += MAX_ARGUMENT_LENGTH) { + var chunk = arr.slice(start, start + MAX_ARGUMENT_LENGTH); + + result = prototypeConcat.apply(result, chunk); + } + + return result; + } + + function assign(target, varArgs) { // .length of function is 2 + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + + return to; + } + + var NodeTypes = { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NAMESPACE_NODE: NAMESPACE_NODE_NODETYPE, + }; + + // XPathParser /////////////////////////////////////////////////////////////// + + XPathParser.prototype = new Object(); + XPathParser.prototype.constructor = XPathParser; + XPathParser.superclass = Object.prototype; + + function XPathParser() { + this.init(); + } + + XPathParser.prototype.init = function () { + this.reduceActions = []; + + this.reduceActions[3] = function (rhs) { + return new OrOperation(rhs[0], rhs[2]); + }; + this.reduceActions[5] = function (rhs) { + return new AndOperation(rhs[0], rhs[2]); + }; + this.reduceActions[7] = function (rhs) { + return new EqualsOperation(rhs[0], rhs[2]); + }; + this.reduceActions[8] = function (rhs) { + return new NotEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[10] = function (rhs) { + return new LessThanOperation(rhs[0], rhs[2]); + }; + this.reduceActions[11] = function (rhs) { + return new GreaterThanOperation(rhs[0], rhs[2]); + }; + this.reduceActions[12] = function (rhs) { + return new LessThanOrEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[13] = function (rhs) { + return new GreaterThanOrEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[15] = function (rhs) { + return new PlusOperation(rhs[0], rhs[2]); + }; + this.reduceActions[16] = function (rhs) { + return new MinusOperation(rhs[0], rhs[2]); + }; + this.reduceActions[18] = function (rhs) { + return new MultiplyOperation(rhs[0], rhs[2]); + }; + this.reduceActions[19] = function (rhs) { + return new DivOperation(rhs[0], rhs[2]); + }; + this.reduceActions[20] = function (rhs) { + return new ModOperation(rhs[0], rhs[2]); + }; + this.reduceActions[22] = function (rhs) { + return new UnaryMinusOperation(rhs[1]); + }; + this.reduceActions[24] = function (rhs) { + return new BarOperation(rhs[0], rhs[2]); + }; + this.reduceActions[25] = function (rhs) { + return new PathExpr(undefined, undefined, rhs[0]); + }; + this.reduceActions[27] = function (rhs) { + rhs[0].locationPath = rhs[2]; + return rhs[0]; + }; + this.reduceActions[28] = function (rhs) { + rhs[0].locationPath = rhs[2]; + rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + return rhs[0]; + }; + this.reduceActions[29] = function (rhs) { + return new PathExpr(rhs[0], [], undefined); + }; + this.reduceActions[30] = function (rhs) { + if (Utilities.instance_of(rhs[0], PathExpr)) { + if (rhs[0].filterPredicates == undefined) { + rhs[0].filterPredicates = []; + } + rhs[0].filterPredicates.push(rhs[1]); + return rhs[0]; + } else { + return new PathExpr(rhs[0], [rhs[1]], undefined); + } + }; + this.reduceActions[32] = function (rhs) { + return rhs[1]; + }; + this.reduceActions[33] = function (rhs) { + return new XString(rhs[0]); + }; + this.reduceActions[34] = function (rhs) { + return new XNumber(rhs[0]); + }; + this.reduceActions[36] = function (rhs) { + return new FunctionCall(rhs[0], []); + }; + this.reduceActions[37] = function (rhs) { + return new FunctionCall(rhs[0], rhs[2]); + }; + this.reduceActions[38] = function (rhs) { + return [rhs[0]]; + }; + this.reduceActions[39] = function (rhs) { + rhs[2].unshift(rhs[0]); + return rhs[2]; + }; + this.reduceActions[43] = function (rhs) { + return new LocationPath(true, []); + }; + this.reduceActions[44] = function (rhs) { + rhs[1].absolute = true; + return rhs[1]; + }; + this.reduceActions[46] = function (rhs) { + return new LocationPath(false, [rhs[0]]); + }; + this.reduceActions[47] = function (rhs) { + rhs[0].steps.push(rhs[2]); + return rhs[0]; + }; + this.reduceActions[49] = function (rhs) { + return new Step(rhs[0], rhs[1], []); + }; + this.reduceActions[50] = function (rhs) { + return new Step(Step.CHILD, rhs[0], []); + }; + this.reduceActions[51] = function (rhs) { + return new Step(rhs[0], rhs[1], rhs[2]); + }; + this.reduceActions[52] = function (rhs) { + return new Step(Step.CHILD, rhs[0], rhs[1]); + }; + this.reduceActions[54] = function (rhs) { + return [rhs[0]]; + }; + this.reduceActions[55] = function (rhs) { + rhs[1].unshift(rhs[0]); + return rhs[1]; + }; + this.reduceActions[56] = function (rhs) { + if (rhs[0] == "ancestor") { + return Step.ANCESTOR; + } else if (rhs[0] == "ancestor-or-self") { + return Step.ANCESTORORSELF; + } else if (rhs[0] == "attribute") { + return Step.ATTRIBUTE; + } else if (rhs[0] == "child") { + return Step.CHILD; + } else if (rhs[0] == "descendant") { + return Step.DESCENDANT; + } else if (rhs[0] == "descendant-or-self") { + return Step.DESCENDANTORSELF; + } else if (rhs[0] == "following") { + return Step.FOLLOWING; + } else if (rhs[0] == "following-sibling") { + return Step.FOLLOWINGSIBLING; + } else if (rhs[0] == "namespace") { + return Step.NAMESPACE; + } else if (rhs[0] == "parent") { + return Step.PARENT; + } else if (rhs[0] == "preceding") { + return Step.PRECEDING; + } else if (rhs[0] == "preceding-sibling") { + return Step.PRECEDINGSIBLING; + } else if (rhs[0] == "self") { + return Step.SELF; + } + return -1; + }; + this.reduceActions[57] = function (rhs) { + return Step.ATTRIBUTE; + }; + this.reduceActions[59] = function (rhs) { + if (rhs[0] == "comment") { + return NodeTest.commentTest; + } else if (rhs[0] == "text") { + return NodeTest.textTest; + } else if (rhs[0] == "processing-instruction") { + return NodeTest.anyPiTest; + } else if (rhs[0] == "node") { + return NodeTest.nodeTest; + } + return new NodeTest(-1, undefined); + }; + this.reduceActions[60] = function (rhs) { + return new NodeTest.PITest(rhs[2]); + }; + this.reduceActions[61] = function (rhs) { + return rhs[1]; + }; + this.reduceActions[63] = function (rhs) { + rhs[1].absolute = true; + rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + return rhs[1]; + }; + this.reduceActions[64] = function (rhs) { + rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + rhs[0].steps.push(rhs[2]); + return rhs[0]; + }; + this.reduceActions[65] = function (rhs) { + return new Step(Step.SELF, NodeTest.nodeTest, []); + }; + this.reduceActions[66] = function (rhs) { + return new Step(Step.PARENT, NodeTest.nodeTest, []); + }; + this.reduceActions[67] = function (rhs) { + return new VariableReference(rhs[1]); + }; + this.reduceActions[68] = function (rhs) { + return NodeTest.nameTestAny; + }; + this.reduceActions[69] = function (rhs) { + return new NodeTest.NameTestPrefixAny(rhs[0].split(':')[0]); + }; + this.reduceActions[70] = function (rhs) { + return new NodeTest.NameTestQName(rhs[0]); + }; + }; + + XPathParser.actionTable = [ + " s s sssssssss s ss s ss", + " s ", + "r rrrrrrrrr rrrrrrr rr r ", + " rrrrr ", + " s s sssssssss s ss s ss", + "rs rrrrrrrr s sssssrrrrrr rrs rs ", + " s s sssssssss s ss s ss", + " s ", + " s ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + " s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr r ", + "a ", + "r s rr r ", + "r sr rr r ", + "r s rr s rr r ", + "r rssrr rss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrrs rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r srrrrrrrr rrrrrrs rr sr ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + " sssss ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrr rrrrr rr r ", + " s ", + " s ", + " rrrrr ", + " s s sssssssss s sss s ss", + "r srrrrrrrr rrrrrrs rr r ", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss ss s ss", + " s s sssssssss s ss s ss", + " s s sssss s s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s s sssss s s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " rr ", + " s ", + " rs ", + "r sr rr r ", + "r s rr s rr r ", + "r rssrr rss rr r ", + "r rssrr rss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + " r ", + " s ", + "r srrrrrrrr rrrrrrs rr r ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s s sssssssss s ss s ss", + "r rrrrrrrrr rrrrrrr rr rr ", + " r " + ]; + + XPathParser.actionTableNumber = [ + " 1 0 /.-,+*)(' & %$ # \"!", + " J ", + "a aaaaaaaaa aaaaaaa aa a ", + " YYYYY ", + " 1 0 /.-,+*)(' & %$ # \"!", + "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ", + " 1 0 /.-,+*)(' & %$ # \"!", + " N ", + " O ", + "e eeeeeeeee eeeeeee ee ee ", + "f fffffffff fffffff ff ff ", + "d ddddddddd ddddddd dd dd ", + "B BBBBBBBBB BBBBBBB BB BB ", + "A AAAAAAAAA AAAAAAA AA AA ", + " P ", + " Q ", + " 1 . +*)(' # \" ", + "b bbbbbbbbb bbbbbbb bb b ", + " ", + "! S !! ! ", + "\" T\" \"\" \" ", + "$ V $$ U $$ $ ", + "& &ZY&& &XW && & ", + ") ))))) )))\\[ )) ) ", + ". ....._^] ..... .. . ", + "1 11111111 11111 11 1 ", + "5 55555555 55555` 55 5 ", + "7 77777777 777777 77 7 ", + "9 99999999 999999 99 9 ", + ": c:::::::: ::::::b :: a: ", + "I fIIIIIIII IIIIIIe II I ", + "= ========= ======= == == ", + "? ????????? ??????? ?? ?? ", + "C CCCCCCCCC CCCCCCC CC CC ", + "J JJJJJJJJ JJJJJJ JJ J ", + "M MMMMMMMM MMMMMM MM M ", + "N NNNNNNNNN NNNNNNN NN N ", + "P PPPPPPPPP PPPPPPP PP P ", + " +*)(' ", + "R RRRRRRRRR RRRRRRR RR aR ", + "U UUUUUUUUU UUUUUUU UU U ", + "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ", + "c ccccccccc ccccccc cc cc ", + " j ", + "L fLLLLLLLL LLLLLLe LL L ", + "6 66666666 66666 66 6 ", + " k ", + " l ", + " XXXXX ", + " 1 0 /.-,+*)(' & %$m # \"!", + "_ f________ ______e __ _ ", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 . +*)(' # \" ", + " 1 . +*)(' # \" ", + "> >>>>>>>>> >>>>>>> >> >> ", + " 1 . +*)(' # \" ", + " 1 . +*)(' # \" ", + "Q QQQQQQQQQ QQQQQQQ QQ aQ ", + "V VVVVVVVVV VVVVVVV VV aV ", + "T TTTTTTTTT TTTTTTT TT T ", + "@ @@@@@@@@@ @@@@@@@ @@ @@ ", + " \x87 ", + "[ [[[[[[[[[ [[[[[[[ [[ [[ ", + "D DDDDDDDDD DDDDDDD DD DD ", + " HH ", + " \x88 ", + " F\x89 ", + "# T# ## # ", + "% V %% U %% % ", + "' 'ZY'' 'XW '' ' ", + "( (ZY(( (XW (( ( ", + "+ +++++ +++\\[ ++ + ", + "* ***** ***\\[ ** * ", + "- ----- ---\\[ -- - ", + ", ,,,,, ,,,\\[ ,, , ", + "0 00000_^] 00000 00 0 ", + "/ /////_^] ///// // / ", + "2 22222222 22222 22 2 ", + "3 33333333 33333 33 3 ", + "4 44444444 44444 44 4 ", + "8 88888888 888888 88 8 ", + " ^ ", + " \x8a ", + "; f;;;;;;;; ;;;;;;e ;; ; ", + "< f<<<<<<<< <<<<<?@ AB CDEFGH IJ ", + " ", + " ", + " ", + "L456789:;<=>?@ AB CDEFGH IJ ", + " M EFGH IJ ", + " N;<=>?@ AB CDEFGH IJ ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " S EFGH IJ ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " e ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " h J ", + " i j ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + "o456789:;<=>?@ ABpqCDEFGH IJ ", + " ", + " r6789:;<=>?@ AB CDEFGH IJ ", + " s789:;<=>?@ AB CDEFGH IJ ", + " t89:;<=>?@ AB CDEFGH IJ ", + " u89:;<=>?@ AB CDEFGH IJ ", + " v9:;<=>?@ AB CDEFGH IJ ", + " w9:;<=>?@ AB CDEFGH IJ ", + " x9:;<=>?@ AB CDEFGH IJ ", + " y9:;<=>?@ AB CDEFGH IJ ", + " z:;<=>?@ AB CDEFGH IJ ", + " {:;<=>?@ AB CDEFGH IJ ", + " |;<=>?@ AB CDEFGH IJ ", + " };<=>?@ AB CDEFGH IJ ", + " ~;<=>?@ AB CDEFGH IJ ", + " \x7f=>?@ AB CDEFGH IJ ", + "\x80456789:;<=>?@ AB CDEFGH IJ\x81", + " \x82 EFGH IJ ", + " \x83 EFGH IJ ", + " ", + " \x84 GH IJ ", + " \x85 GH IJ ", + " i \x86 ", + " i \x87 ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + "o456789:;<=>?@ AB\x8cqCDEFGH IJ ", + " ", + " " + ]; + + XPathParser.productions = [ + [1, 1, 2], + [2, 1, 3], + [3, 1, 4], + [3, 3, 3, -9, 4], + [4, 1, 5], + [4, 3, 4, -8, 5], + [5, 1, 6], + [5, 3, 5, -22, 6], + [5, 3, 5, -5, 6], + [6, 1, 7], + [6, 3, 6, -23, 7], + [6, 3, 6, -24, 7], + [6, 3, 6, -6, 7], + [6, 3, 6, -7, 7], + [7, 1, 8], + [7, 3, 7, -25, 8], + [7, 3, 7, -26, 8], + [8, 1, 9], + [8, 3, 8, -12, 9], + [8, 3, 8, -11, 9], + [8, 3, 8, -10, 9], + [9, 1, 10], + [9, 2, -26, 9], + [10, 1, 11], + [10, 3, 10, -27, 11], + [11, 1, 12], + [11, 1, 13], + [11, 3, 13, -28, 14], + [11, 3, 13, -4, 14], + [13, 1, 15], + [13, 2, 13, 16], + [15, 1, 17], + [15, 3, -29, 2, -30], + [15, 1, -15], + [15, 1, -16], + [15, 1, 18], + [18, 3, -13, -29, -30], + [18, 4, -13, -29, 19, -30], + [19, 1, 20], + [19, 3, 20, -31, 19], + [20, 1, 2], + [12, 1, 14], + [12, 1, 21], + [21, 1, -28], + [21, 2, -28, 14], + [21, 1, 22], + [14, 1, 23], + [14, 3, 14, -28, 23], + [14, 1, 24], + [23, 2, 25, 26], + [23, 1, 26], + [23, 3, 25, 26, 27], + [23, 2, 26, 27], + [23, 1, 28], + [27, 1, 16], + [27, 2, 16, 27], + [25, 2, -14, -3], + [25, 1, -32], + [26, 1, 29], + [26, 3, -20, -29, -30], + [26, 4, -21, -29, -15, -30], + [16, 3, -33, 30, -34], + [30, 1, 2], + [22, 2, -4, 14], + [24, 3, 14, -4, 23], + [28, 1, -35], + [28, 1, -2], + [17, 2, -36, -18], + [29, 1, -17], + [29, 1, -19], + [29, 1, -18] + ]; + + XPathParser.DOUBLEDOT = 2; + XPathParser.DOUBLECOLON = 3; + XPathParser.DOUBLESLASH = 4; + XPathParser.NOTEQUAL = 5; + XPathParser.LESSTHANOREQUAL = 6; + XPathParser.GREATERTHANOREQUAL = 7; + XPathParser.AND = 8; + XPathParser.OR = 9; + XPathParser.MOD = 10; + XPathParser.DIV = 11; + XPathParser.MULTIPLYOPERATOR = 12; + XPathParser.FUNCTIONNAME = 13; + XPathParser.AXISNAME = 14; + XPathParser.LITERAL = 15; + XPathParser.NUMBER = 16; + XPathParser.ASTERISKNAMETEST = 17; + XPathParser.QNAME = 18; + XPathParser.NCNAMECOLONASTERISK = 19; + XPathParser.NODETYPE = 20; + XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21; + XPathParser.EQUALS = 22; + XPathParser.LESSTHAN = 23; + XPathParser.GREATERTHAN = 24; + XPathParser.PLUS = 25; + XPathParser.MINUS = 26; + XPathParser.BAR = 27; + XPathParser.SLASH = 28; + XPathParser.LEFTPARENTHESIS = 29; + XPathParser.RIGHTPARENTHESIS = 30; + XPathParser.COMMA = 31; + XPathParser.AT = 32; + XPathParser.LEFTBRACKET = 33; + XPathParser.RIGHTBRACKET = 34; + XPathParser.DOT = 35; + XPathParser.DOLLAR = 36; + + XPathParser.prototype.tokenize = function (s1) { + var types = []; + var values = []; + var s = s1 + '\0'; + + var pos = 0; + var c = s.charAt(pos++); + while (1) { + while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { + c = s.charAt(pos++); + } + if (c == '\0' || pos >= s.length) { + break; + } + + if (c == '(') { + types.push(XPathParser.LEFTPARENTHESIS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ')') { + types.push(XPathParser.RIGHTPARENTHESIS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '[') { + types.push(XPathParser.LEFTBRACKET); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ']') { + types.push(XPathParser.RIGHTBRACKET); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '@') { + types.push(XPathParser.AT); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ',') { + types.push(XPathParser.COMMA); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '|') { + types.push(XPathParser.BAR); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '+') { + types.push(XPathParser.PLUS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '-') { + types.push(XPathParser.MINUS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '=') { + types.push(XPathParser.EQUALS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '$') { + types.push(XPathParser.DOLLAR); + values.push(c); + c = s.charAt(pos++); + continue; + } + + if (c == '.') { + c = s.charAt(pos++); + if (c == '.') { + types.push(XPathParser.DOUBLEDOT); + values.push(".."); + c = s.charAt(pos++); + continue; + } + if (c >= '0' && c <= '9') { + var number = "." + c; + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + types.push(XPathParser.NUMBER); + values.push(number); + continue; + } + types.push(XPathParser.DOT); + values.push('.'); + continue; + } + + if (c == '\'' || c == '"') { + var delimiter = c; + var literal = ""; + while (pos < s.length && (c = s.charAt(pos)) !== delimiter) { + literal += c; + pos += 1; + } + if (c !== delimiter) { + throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal); + } + pos += 1; + types.push(XPathParser.LITERAL); + values.push(literal); + c = s.charAt(pos++); + continue; + } + + if (c >= '0' && c <= '9') { + var number = c; + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + if (c == '.') { + if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { + number += c; + number += s.charAt(pos++); + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + } + } + types.push(XPathParser.NUMBER); + values.push(number); + continue; + } + + if (c == '*') { + if (types.length > 0) { + var last = types[types.length - 1]; + if (last != XPathParser.AT + && last != XPathParser.DOUBLECOLON + && last != XPathParser.LEFTPARENTHESIS + && last != XPathParser.LEFTBRACKET + && last != XPathParser.AND + && last != XPathParser.OR + && last != XPathParser.MOD + && last != XPathParser.DIV + && last != XPathParser.MULTIPLYOPERATOR + && last != XPathParser.SLASH + && last != XPathParser.DOUBLESLASH + && last != XPathParser.BAR + && last != XPathParser.PLUS + && last != XPathParser.MINUS + && last != XPathParser.EQUALS + && last != XPathParser.NOTEQUAL + && last != XPathParser.LESSTHAN + && last != XPathParser.LESSTHANOREQUAL + && last != XPathParser.GREATERTHAN + && last != XPathParser.GREATERTHANOREQUAL) { + types.push(XPathParser.MULTIPLYOPERATOR); + values.push(c); + c = s.charAt(pos++); + continue; + } + } + types.push(XPathParser.ASTERISKNAMETEST); + values.push(c); + c = s.charAt(pos++); + continue; + } + + if (c == ':') { + if (s.charAt(pos) == ':') { + types.push(XPathParser.DOUBLECOLON); + values.push("::"); + pos++; + c = s.charAt(pos++); + continue; + } + } + + if (c == '/') { + c = s.charAt(pos++); + if (c == '/') { + types.push(XPathParser.DOUBLESLASH); + values.push("//"); + c = s.charAt(pos++); + continue; + } + types.push(XPathParser.SLASH); + values.push('/'); + continue; + } + + if (c == '!') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.NOTEQUAL); + values.push("!="); + pos++; + c = s.charAt(pos++); + continue; + } + } + + if (c == '<') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.LESSTHANOREQUAL); + values.push("<="); + pos++; + c = s.charAt(pos++); + continue; + } + types.push(XPathParser.LESSTHAN); + values.push('<'); + c = s.charAt(pos++); + continue; + } + + if (c == '>') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.GREATERTHANOREQUAL); + values.push(">="); + pos++; + c = s.charAt(pos++); + continue; + } + types.push(XPathParser.GREATERTHAN); + values.push('>'); + c = s.charAt(pos++); + continue; + } + + if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) { + var name = c; + c = s.charAt(pos++); + while (Utilities.isNCNameChar(c.charCodeAt(0))) { + name += c; + c = s.charAt(pos++); + } + if (types.length > 0) { + var last = types[types.length - 1]; + if (last != XPathParser.AT + && last != XPathParser.DOUBLECOLON + && last != XPathParser.LEFTPARENTHESIS + && last != XPathParser.LEFTBRACKET + && last != XPathParser.AND + && last != XPathParser.OR + && last != XPathParser.MOD + && last != XPathParser.DIV + && last != XPathParser.MULTIPLYOPERATOR + && last != XPathParser.SLASH + && last != XPathParser.DOUBLESLASH + && last != XPathParser.BAR + && last != XPathParser.PLUS + && last != XPathParser.MINUS + && last != XPathParser.EQUALS + && last != XPathParser.NOTEQUAL + && last != XPathParser.LESSTHAN + && last != XPathParser.LESSTHANOREQUAL + && last != XPathParser.GREATERTHAN + && last != XPathParser.GREATERTHANOREQUAL) { + if (name == "and") { + types.push(XPathParser.AND); + values.push(name); + continue; + } + if (name == "or") { + types.push(XPathParser.OR); + values.push(name); + continue; + } + if (name == "mod") { + types.push(XPathParser.MOD); + values.push(name); + continue; + } + if (name == "div") { + types.push(XPathParser.DIV); + values.push(name); + continue; + } + } + } + if (c == ':') { + if (s.charAt(pos) == '*') { + types.push(XPathParser.NCNAMECOLONASTERISK); + values.push(name + ":*"); + pos++; + c = s.charAt(pos++); + continue; + } + if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) { + name += ':'; + c = s.charAt(pos++); + while (Utilities.isNCNameChar(c.charCodeAt(0))) { + name += c; + c = s.charAt(pos++); + } + if (c == '(') { + types.push(XPathParser.FUNCTIONNAME); + values.push(name); + continue; + } + types.push(XPathParser.QNAME); + values.push(name); + continue; + } + if (s.charAt(pos) == ':') { + types.push(XPathParser.AXISNAME); + values.push(name); + continue; + } + } + if (c == '(') { + if (name == "comment" || name == "text" || name == "node") { + types.push(XPathParser.NODETYPE); + values.push(name); + continue; + } + if (name == "processing-instruction") { + if (s.charAt(pos) == ')') { + types.push(XPathParser.NODETYPE); + } else { + types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL); + } + values.push(name); + continue; + } + types.push(XPathParser.FUNCTIONNAME); + values.push(name); + continue; + } + types.push(XPathParser.QNAME); + values.push(name); + continue; + } + + throw new Error("Unexpected character " + c); + } + types.push(1); + values.push("[EOF]"); + return [types, values]; + }; + + XPathParser.SHIFT = 's'; + XPathParser.REDUCE = 'r'; + XPathParser.ACCEPT = 'a'; + + XPathParser.prototype.parse = function (s) { + if (!s) { + throw new Error('XPath expression unspecified.'); + } + if (typeof s !== 'string'){ + throw new Error('XPath expression must be a string.'); + } + + var types; + var values; + var res = this.tokenize(s); + if (res == undefined) { + return undefined; + } + types = res[0]; + values = res[1]; + var tokenPos = 0; + var state = []; + var tokenType = []; + var tokenValue = []; + var s; + var a; + var t; + + state.push(0); + tokenType.push(1); + tokenValue.push("_S"); + + a = types[tokenPos]; + t = values[tokenPos++]; + while (1) { + s = state[state.length - 1]; + switch (XPathParser.actionTable[s].charAt(a - 1)) { + case XPathParser.SHIFT: + tokenType.push(-a); + tokenValue.push(t); + state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32); + a = types[tokenPos]; + t = values[tokenPos++]; + break; + case XPathParser.REDUCE: + var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1]; + var rhs = []; + for (var i = 0; i < num; i++) { + tokenType.pop(); + rhs.unshift(tokenValue.pop()); + state.pop(); + } + var s_ = state[state.length - 1]; + tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]); + if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) { + tokenValue.push(rhs[0]); + } else { + tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs)); + } + state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33); + break; + case XPathParser.ACCEPT: + return new XPath(tokenValue.pop()); + default: + throw new Error("XPath parse error"); + } + } + }; + + // XPath ///////////////////////////////////////////////////////////////////// + + XPath.prototype = new Object(); + XPath.prototype.constructor = XPath; + XPath.superclass = Object.prototype; + + function XPath(e) { + this.expression = e; + } + + XPath.prototype.toString = function () { + return this.expression.toString(); + }; + + function setIfUnset(obj, prop, value) { + if (!(prop in obj)) { + obj[prop] = value; + } + } + + XPath.prototype.evaluate = function (c) { + var node = c.expressionContextNode; + + if (!(isNil(node) || isNodeLike(node))) { + throw new Error("Context node does not appear to be a valid DOM node."); + } + + c.contextNode = c.expressionContextNode; + c.contextSize = 1; + c.contextPosition = 1; + + // [2017-11-25] Removed usage of .implementation.hasFeature() since it does + // not reliably detect HTML DOMs (always returns false in xmldom and true in browsers) + if (c.isHtml) { + setIfUnset(c, 'caseInsensitive', true); + setIfUnset(c, 'allowAnyNamespaceForNoPrefix', true); + } + + setIfUnset(c, 'caseInsensitive', false); + + return this.expression.evaluate(c); + }; + + XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; + XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; + + // Expression //////////////////////////////////////////////////////////////// + + Expression.prototype = new Object(); + Expression.prototype.constructor = Expression; + Expression.superclass = Object.prototype; + + function Expression() { + } + + Expression.prototype.init = function () { + }; + + Expression.prototype.toString = function () { + return ""; + }; + + Expression.prototype.evaluate = function (c) { + throw new Error("Could not evaluate expression."); + }; + + // UnaryOperation //////////////////////////////////////////////////////////// + + UnaryOperation.prototype = new Expression(); + UnaryOperation.prototype.constructor = UnaryOperation; + UnaryOperation.superclass = Expression.prototype; + + function UnaryOperation(rhs) { + if (arguments.length > 0) { + this.init(rhs); + } + } + + UnaryOperation.prototype.init = function (rhs) { + this.rhs = rhs; + }; + + // UnaryMinusOperation /////////////////////////////////////////////////////// + + UnaryMinusOperation.prototype = new UnaryOperation(); + UnaryMinusOperation.prototype.constructor = UnaryMinusOperation; + UnaryMinusOperation.superclass = UnaryOperation.prototype; + + function UnaryMinusOperation(rhs) { + if (arguments.length > 0) { + this.init(rhs); + } + } + + UnaryMinusOperation.prototype.init = function (rhs) { + UnaryMinusOperation.superclass.init.call(this, rhs); + }; + + UnaryMinusOperation.prototype.evaluate = function (c) { + return this.rhs.evaluate(c).number().negate(); + }; + + UnaryMinusOperation.prototype.toString = function () { + return "-" + this.rhs.toString(); + }; + + // BinaryOperation /////////////////////////////////////////////////////////// + + BinaryOperation.prototype = new Expression(); + BinaryOperation.prototype.constructor = BinaryOperation; + BinaryOperation.superclass = Expression.prototype; + + function BinaryOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + BinaryOperation.prototype.init = function (lhs, rhs) { + this.lhs = lhs; + this.rhs = rhs; + }; + + // OrOperation /////////////////////////////////////////////////////////////// + + OrOperation.prototype = new BinaryOperation(); + OrOperation.prototype.constructor = OrOperation; + OrOperation.superclass = BinaryOperation.prototype; + + function OrOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + OrOperation.prototype.init = function (lhs, rhs) { + OrOperation.superclass.init.call(this, lhs, rhs); + }; + + OrOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")"; + }; + + OrOperation.prototype.evaluate = function (c) { + var b = this.lhs.evaluate(c).bool(); + if (b.booleanValue()) { + return b; + } + return this.rhs.evaluate(c).bool(); + }; + + // AndOperation ////////////////////////////////////////////////////////////// + + AndOperation.prototype = new BinaryOperation(); + AndOperation.prototype.constructor = AndOperation; + AndOperation.superclass = BinaryOperation.prototype; + + function AndOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + AndOperation.prototype.init = function (lhs, rhs) { + AndOperation.superclass.init.call(this, lhs, rhs); + }; + + AndOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")"; + }; + + AndOperation.prototype.evaluate = function (c) { + var b = this.lhs.evaluate(c).bool(); + if (!b.booleanValue()) { + return b; + } + return this.rhs.evaluate(c).bool(); + }; + + // EqualsOperation /////////////////////////////////////////////////////////// + + EqualsOperation.prototype = new BinaryOperation(); + EqualsOperation.prototype.constructor = EqualsOperation; + EqualsOperation.superclass = BinaryOperation.prototype; + + function EqualsOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + EqualsOperation.prototype.init = function (lhs, rhs) { + EqualsOperation.superclass.init.call(this, lhs, rhs); + }; + + EqualsOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")"; + }; + + EqualsOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).equals(this.rhs.evaluate(c)); + }; + + // NotEqualOperation ///////////////////////////////////////////////////////// + + NotEqualOperation.prototype = new BinaryOperation(); + NotEqualOperation.prototype.constructor = NotEqualOperation; + NotEqualOperation.superclass = BinaryOperation.prototype; + + function NotEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + NotEqualOperation.prototype.init = function (lhs, rhs) { + NotEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + NotEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")"; + }; + + NotEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c)); + }; + + // LessThanOperation ///////////////////////////////////////////////////////// + + LessThanOperation.prototype = new BinaryOperation(); + LessThanOperation.prototype.constructor = LessThanOperation; + LessThanOperation.superclass = BinaryOperation.prototype; + + function LessThanOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + LessThanOperation.prototype.init = function (lhs, rhs) { + LessThanOperation.superclass.init.call(this, lhs, rhs); + }; + + LessThanOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c)); + }; + + LessThanOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")"; + }; + + // GreaterThanOperation ////////////////////////////////////////////////////// + + GreaterThanOperation.prototype = new BinaryOperation(); + GreaterThanOperation.prototype.constructor = GreaterThanOperation; + GreaterThanOperation.superclass = BinaryOperation.prototype; + + function GreaterThanOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + GreaterThanOperation.prototype.init = function (lhs, rhs) { + GreaterThanOperation.superclass.init.call(this, lhs, rhs); + }; + + GreaterThanOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c)); + }; + + GreaterThanOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")"; + }; + + // LessThanOrEqualOperation ////////////////////////////////////////////////// + + LessThanOrEqualOperation.prototype = new BinaryOperation(); + LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation; + LessThanOrEqualOperation.superclass = BinaryOperation.prototype; + + function LessThanOrEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + LessThanOrEqualOperation.prototype.init = function (lhs, rhs) { + LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + LessThanOrEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c)); + }; + + LessThanOrEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")"; + }; + + // GreaterThanOrEqualOperation /////////////////////////////////////////////// + + GreaterThanOrEqualOperation.prototype = new BinaryOperation(); + GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation; + GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype; + + function GreaterThanOrEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + GreaterThanOrEqualOperation.prototype.init = function (lhs, rhs) { + GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + GreaterThanOrEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c)); + }; + + GreaterThanOrEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")"; + }; + + // PlusOperation ///////////////////////////////////////////////////////////// + + PlusOperation.prototype = new BinaryOperation(); + PlusOperation.prototype.constructor = PlusOperation; + PlusOperation.superclass = BinaryOperation.prototype; + + function PlusOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + PlusOperation.prototype.init = function (lhs, rhs) { + PlusOperation.superclass.init.call(this, lhs, rhs); + }; + + PlusOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number()); + }; + + PlusOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")"; + }; + + // MinusOperation //////////////////////////////////////////////////////////// + + MinusOperation.prototype = new BinaryOperation(); + MinusOperation.prototype.constructor = MinusOperation; + MinusOperation.superclass = BinaryOperation.prototype; + + function MinusOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + MinusOperation.prototype.init = function (lhs, rhs) { + MinusOperation.superclass.init.call(this, lhs, rhs); + }; + + MinusOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number()); + }; + + MinusOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")"; + }; + + // MultiplyOperation ///////////////////////////////////////////////////////// + + MultiplyOperation.prototype = new BinaryOperation(); + MultiplyOperation.prototype.constructor = MultiplyOperation; + MultiplyOperation.superclass = BinaryOperation.prototype; + + function MultiplyOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + MultiplyOperation.prototype.init = function (lhs, rhs) { + MultiplyOperation.superclass.init.call(this, lhs, rhs); + }; + + MultiplyOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number()); + }; + + MultiplyOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")"; + }; + + // DivOperation ////////////////////////////////////////////////////////////// + + DivOperation.prototype = new BinaryOperation(); + DivOperation.prototype.constructor = DivOperation; + DivOperation.superclass = BinaryOperation.prototype; + + function DivOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + DivOperation.prototype.init = function (lhs, rhs) { + DivOperation.superclass.init.call(this, lhs, rhs); + }; + + DivOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number()); + }; + + DivOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")"; + }; + + // ModOperation ////////////////////////////////////////////////////////////// + + ModOperation.prototype = new BinaryOperation(); + ModOperation.prototype.constructor = ModOperation; + ModOperation.superclass = BinaryOperation.prototype; + + function ModOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + ModOperation.prototype.init = function (lhs, rhs) { + ModOperation.superclass.init.call(this, lhs, rhs); + }; + + ModOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number()); + }; + + ModOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")"; + }; + + // BarOperation ////////////////////////////////////////////////////////////// + + BarOperation.prototype = new BinaryOperation(); + BarOperation.prototype.constructor = BarOperation; + BarOperation.superclass = BinaryOperation.prototype; + + function BarOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + BarOperation.prototype.init = function (lhs, rhs) { + BarOperation.superclass.init.call(this, lhs, rhs); + }; + + BarOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset()); + }; + + BarOperation.prototype.toString = function () { + return map(toString, [this.lhs, this.rhs]).join(' | '); + }; + + // PathExpr ////////////////////////////////////////////////////////////////// + + PathExpr.prototype = new Expression(); + PathExpr.prototype.constructor = PathExpr; + PathExpr.superclass = Expression.prototype; + + function PathExpr(filter, filterPreds, locpath) { + if (arguments.length > 0) { + this.init(filter, filterPreds, locpath); + } + } + + PathExpr.prototype.init = function (filter, filterPreds, locpath) { + PathExpr.superclass.init.call(this); + this.filter = filter; + this.filterPredicates = filterPreds; + this.locationPath = locpath; + }; + + /** + * Returns the topmost node of the tree containing node + */ + function findRoot(node) { + while (node && node.parentNode) { + node = node.parentNode; + } + + return node; + } + + var applyPredicates = function (predicates, c, nodes, reverse) { + if (predicates.length === 0) { + return nodes; + } + + var ctx = c.extend({}); + + return reduce( + function (inNodes, pred) { + ctx.contextSize = inNodes.length; + + return filter( + function (node, i) { + ctx.contextNode = node; + ctx.contextPosition = i + 1; + + return PathExpr.predicateMatches(pred, ctx); + }, + inNodes + ); + }, + sortNodes(nodes, reverse), + predicates + ); + }; + + PathExpr.getRoot = function (xpc, nodes) { + var firstNode = nodes[0]; + + // xpc.virtualRoot could possibly provide a root even if firstNode is null, + // so using a guard here instead of throwing. + if (firstNode && firstNode.nodeType === NodeTypes.DOCUMENT_NODE) { + return firstNode; + } + + if (xpc.virtualRoot) { + return xpc.virtualRoot; + } + + if (!firstNode) { + throw new Error('Context node not found when determining document root.'); + } + + var ownerDoc = firstNode.ownerDocument; + + if (ownerDoc) { + return ownerDoc; + } + + // IE 5.5 doesn't have ownerDocument? + var n = firstNode; + while (n.parentNode != null) { + n = n.parentNode; + } + return n; + }; + + var getPrefixForNamespaceNode = function (attrNode) { + var nm = String(attrNode.name); + + if (nm === "xmlns") { + return ""; + } + + if (nm.substring(0, 6) === "xmlns:") { + return nm.substring(6, nm.length); + } + + return null; + }; + + PathExpr.applyStep = function (step, xpc, node) { + if (!node) { + throw new Error('Context node not found when evaluating XPath step: ' + step); + } + + var newNodes = []; + xpc.contextNode = node; + + switch (step.axis) { + case Step.ANCESTOR: + // look at all the ancestor nodes + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + var m; + if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) { + m = PathExpr.getOwnerElement(xpc.contextNode); + } else { + m = xpc.contextNode.parentNode; + } + while (m != null) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m === xpc.virtualRoot) { + break; + } + m = m.parentNode; + } + break; + + case Step.ANCESTORORSELF: + // look at all the ancestor nodes and the current node + for (var m = xpc.contextNode; m != null; m = m.nodeType == NodeTypes.ATTRIBUTE_NODE ? PathExpr.getOwnerElement(m) : m.parentNode) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m === xpc.virtualRoot) { + break; + } + } + break; + + case Step.ATTRIBUTE: + // look at the attributes + var nnm = xpc.contextNode.attributes; + if (nnm != null) { + for (var k = 0; k < nnm.length; k++) { + var m = nnm.item(k); + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + } + break; + + case Step.CHILD: + // look at all child elements + for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.DESCENDANT: + // look at all descendant nodes + var st = [xpc.contextNode.firstChild]; + while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.DESCENDANTORSELF: + // look at self + if (step.nodeTest.matches(xpc.contextNode, xpc)) { + newNodes.push(xpc.contextNode); + } + // look at all descendant nodes + var st = [xpc.contextNode.firstChild]; + while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.FOLLOWING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + var st = []; + if (xpc.contextNode.firstChild != null) { + st.unshift(xpc.contextNode.firstChild); + } else { + st.unshift(xpc.contextNode.nextSibling); + } + for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != NodeTypes.DOCUMENT_NODE && m !== xpc.virtualRoot; m = m.parentNode) { + st.unshift(m.nextSibling); + } + do { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } while (st.length > 0); + break; + + case Step.FOLLOWINGSIBLING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.NAMESPACE: + var nodes = {}; + + if (xpc.contextNode.nodeType == NodeTypes.ELEMENT_NODE) { + // BUG: This only collects the namespaces on the current node, but seemingly + // it should collect all those in scope + nodes["xml"] = new XPathNamespace("xml", null, XPath.XML_NAMESPACE_URI, xpc.contextNode); + + for (var m = xpc.contextNode; m != null && m.nodeType == NodeTypes.ELEMENT_NODE; m = m.parentNode) { + for (var k = 0; k < m.attributes.length; k++) { + var attr = m.attributes.item(k); + + var pre = getPrefixForNamespaceNode(attr); + + if (pre != null && nodes[pre] == undefined) { + nodes[pre] = new XPathNamespace(pre, attr, attr.value, xpc.contextNode); + } + } + } + + for (var pre in nodes) { + var node = nodes[pre]; + + if (step.nodeTest.matches(node, xpc)) { + newNodes.push(node); + } + } + } + break; + + case Step.PARENT: + m = null; + if (xpc.contextNode !== xpc.virtualRoot) { + if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) { + m = PathExpr.getOwnerElement(xpc.contextNode); + } else { + m = xpc.contextNode.parentNode; + } + } + if (m != null && step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + break; + + case Step.PRECEDING: + var st; + if (xpc.virtualRoot != null) { + st = [xpc.virtualRoot]; + } else { + // cannot rely on .ownerDocument because the node may be in a document fragment + st = [findRoot(xpc.contextNode)]; + } + outer: while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (m == xpc.contextNode) { + break outer; + } + if (step.nodeTest.matches(m, xpc)) { + newNodes.unshift(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.PRECEDINGSIBLING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.SELF: + if (step.nodeTest.matches(xpc.contextNode, xpc)) { + newNodes.push(xpc.contextNode); + } + break; + } + + return newNodes; + }; + + function applyStepWithPredicates(step, xpc, node) { + return applyPredicates( + step.predicates, + xpc, + PathExpr.applyStep(step, xpc, node), + includes(REVERSE_AXES, step.axis) + ); + } + + function applyStepToNodes(context, nodes, step) { + return flatten( + map( + applyStepWithPredicates.bind(null, step, context), + nodes + ) + ); + } + + PathExpr.applySteps = function (steps, xpc, nodes) { + return reduce( + applyStepToNodes.bind(null, xpc), + nodes, + steps + ); + }; + + PathExpr.prototype.applyFilter = function (c, xpc) { + if (!this.filter) { + return { nodes: [c.contextNode] }; + } + + var ns = this.filter.evaluate(c); + + if (!Utilities.instance_of(ns, XNodeSet)) { + if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) { + throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used"); + } + + return { nonNodes: ns }; + } + + return { + nodes: applyPredicates( + this.filterPredicates || [], + xpc, + ns.toUnsortedArray(), + false // reverse + ) + }; + }; + + PathExpr.applyLocationPath = function (locationPath, xpc, nodes) { + if (!locationPath) { + return nodes; + } + + var startNodes = locationPath.absolute ? [PathExpr.getRoot(xpc, nodes)] : nodes; + + return PathExpr.applySteps(locationPath.steps, xpc, startNodes); + }; + + PathExpr.prototype.evaluate = function (c) { + var xpc = assign(new XPathContext(), c); + + var filterResult = this.applyFilter(c, xpc); + + if ('nonNodes' in filterResult) { + return filterResult.nonNodes; + } + + var ns = new XNodeSet(); + ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes)); + return ns; + }; + + PathExpr.predicateMatches = function (pred, c) { + var res = pred.evaluate(c); + + return Utilities.instance_of(res, XNumber) + ? c.contextPosition === res.numberValue() + : res.booleanValue(); + }; + + PathExpr.predicateString = function (predicate) { + return wrap('[', ']', predicate.toString()); + }; + + PathExpr.predicatesString = function (predicates) { + return join( + '', + map(PathExpr.predicateString, predicates) + ); + }; + + PathExpr.prototype.toString = function () { + if (this.filter != undefined) { + var filterStr = toString(this.filter); + + if (Utilities.instance_of(this.filter, XString)) { + return wrap("'", "'", filterStr); + } + if (this.filterPredicates != undefined && this.filterPredicates.length) { + return wrap('(', ')', filterStr) + + PathExpr.predicatesString(this.filterPredicates); + } + if (this.locationPath != undefined) { + return filterStr + + (this.locationPath.absolute ? '' : '/') + + toString(this.locationPath); + } + + return filterStr; + } + + return toString(this.locationPath); + }; + + PathExpr.getOwnerElement = function (n) { + // DOM 2 has ownerElement + if (n.ownerElement) { + return n.ownerElement; + } + // DOM 1 Internet Explorer can use selectSingleNode (ironically) + try { + if (n.selectSingleNode) { + return n.selectSingleNode(".."); + } + } catch (e) { + } + // Other DOM 1 implementations must use this egregious search + var doc = n.nodeType == NodeTypes.DOCUMENT_NODE + ? n + : n.ownerDocument; + var elts = doc.getElementsByTagName("*"); + for (var i = 0; i < elts.length; i++) { + var elt = elts.item(i); + var nnm = elt.attributes; + for (var j = 0; j < nnm.length; j++) { + var an = nnm.item(j); + if (an === n) { + return elt; + } + } + } + return null; + }; + + // LocationPath ////////////////////////////////////////////////////////////// + + LocationPath.prototype = new Object(); + LocationPath.prototype.constructor = LocationPath; + LocationPath.superclass = Object.prototype; + + function LocationPath(abs, steps) { + if (arguments.length > 0) { + this.init(abs, steps); + } + } + + LocationPath.prototype.init = function (abs, steps) { + this.absolute = abs; + this.steps = steps; + }; + + LocationPath.prototype.toString = function () { + return ( + (this.absolute ? '/' : '') + + map(toString, this.steps).join('/') + ); + }; + + // Step ////////////////////////////////////////////////////////////////////// + + Step.prototype = new Object(); + Step.prototype.constructor = Step; + Step.superclass = Object.prototype; + + function Step(axis, nodetest, preds) { + if (arguments.length > 0) { + this.init(axis, nodetest, preds); + } + } + + Step.prototype.init = function (axis, nodetest, preds) { + this.axis = axis; + this.nodeTest = nodetest; + this.predicates = preds; + }; + + Step.prototype.toString = function () { + return Step.STEPNAMES[this.axis] + + "::" + + this.nodeTest.toString() + + PathExpr.predicatesString(this.predicates); + }; + + + Step.ANCESTOR = 0; + Step.ANCESTORORSELF = 1; + Step.ATTRIBUTE = 2; + Step.CHILD = 3; + Step.DESCENDANT = 4; + Step.DESCENDANTORSELF = 5; + Step.FOLLOWING = 6; + Step.FOLLOWINGSIBLING = 7; + Step.NAMESPACE = 8; + Step.PARENT = 9; + Step.PRECEDING = 10; + Step.PRECEDINGSIBLING = 11; + Step.SELF = 12; + + Step.STEPNAMES = reduce(function (acc, x) { return acc[x[0]] = x[1], acc; }, {}, [ + [Step.ANCESTOR, 'ancestor'], + [Step.ANCESTORORSELF, 'ancestor-or-self'], + [Step.ATTRIBUTE, 'attribute'], + [Step.CHILD, 'child'], + [Step.DESCENDANT, 'descendant'], + [Step.DESCENDANTORSELF, 'descendant-or-self'], + [Step.FOLLOWING, 'following'], + [Step.FOLLOWINGSIBLING, 'following-sibling'], + [Step.NAMESPACE, 'namespace'], + [Step.PARENT, 'parent'], + [Step.PRECEDING, 'preceding'], + [Step.PRECEDINGSIBLING, 'preceding-sibling'], + [Step.SELF, 'self'] + ]); + + var REVERSE_AXES = [ + Step.ANCESTOR, + Step.ANCESTORORSELF, + Step.PARENT, + Step.PRECEDING, + Step.PRECEDINGSIBLING + ]; + + // NodeTest ////////////////////////////////////////////////////////////////// + + NodeTest.prototype = new Object(); + NodeTest.prototype.constructor = NodeTest; + NodeTest.superclass = Object.prototype; + + function NodeTest(type, value) { + if (arguments.length > 0) { + this.init(type, value); + } + } + + NodeTest.prototype.init = function (type, value) { + this.type = type; + this.value = value; + }; + + NodeTest.prototype.toString = function () { + return ""; + }; + + NodeTest.prototype.matches = function (n, xpc) { + console.warn('unknown node test type'); + }; + + NodeTest.NAMETESTANY = 0; + NodeTest.NAMETESTPREFIXANY = 1; + NodeTest.NAMETESTQNAME = 2; + NodeTest.COMMENT = 3; + NodeTest.TEXT = 4; + NodeTest.PI = 5; + NodeTest.NODE = 6; + + NodeTest.isNodeType = function (types) { + return function (node) { + return includes(types, node.nodeType); + }; + }; + + NodeTest.makeNodeTestType = function (type, members, ctor) { + var newType = ctor || function () { }; + + newType.prototype = new NodeTest(type); + newType.prototype.constructor = newType; + + assign(newType.prototype, members); + + return newType; + }; + // create invariant node test for certain node types + NodeTest.makeNodeTypeTest = function (type, nodeTypes, stringVal) { + return new (NodeTest.makeNodeTestType(type, { + matches: NodeTest.isNodeType(nodeTypes), + toString: always(stringVal) + }))(); + }; + + NodeTest.hasPrefix = function (node) { + return node.prefix || (node.nodeName || node.tagName).indexOf(':') !== -1; + }; + + NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]); + NodeTest.nameSpaceMatches = function (prefix, xpc, n) { + var nNamespace = (n.namespaceURI || ''); + + if (!prefix) { + return !nNamespace || (xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n)); + } + + var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode); + + if (ns == null) { + throw new Error("Cannot resolve QName " + prefix); + } + + return ns === nNamespace; + }; + NodeTest.localNameMatches = function (localName, xpc, n) { + var nLocalName = (n.localName || n.nodeName); + + return xpc.caseInsensitive + ? localName.toLowerCase() === nLocalName.toLowerCase() + : localName === nLocalName; + }; + + NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType( + NodeTest.NAMETESTPREFIXANY, + { + matches: function (n, xpc) { + return NodeTest.isElementOrAttribute(n) && + NodeTest.nameSpaceMatches(this.prefix, xpc, n); + }, + toString: function () { + return this.prefix + ":*"; + } + }, + function NameTestPrefixAny(prefix) { this.prefix = prefix; } + ); + + NodeTest.NameTestQName = NodeTest.makeNodeTestType( + NodeTest.NAMETESTQNAME, + { + matches: function (n, xpc) { + return NodeTest.isNodeType( + [ + NodeTypes.ELEMENT_NODE, + NodeTypes.ATTRIBUTE_NODE, + NodeTypes.NAMESPACE_NODE, + ] + )(n) && + NodeTest.nameSpaceMatches(this.prefix, xpc, n) && + NodeTest.localNameMatches(this.localName, xpc, n); + }, + toString: function () { + return this.name; + } + }, + function NameTestQName(name) { + var nameParts = name.split(':'); + + this.name = name; + this.prefix = nameParts.length > 1 ? nameParts[0] : null; + this.localName = nameParts[nameParts.length > 1 ? 1 : 0]; + } + ); + + NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, { + matches: function (n, xpc) { + return NodeTest.isNodeType( + [NodeTypes.PROCESSING_INSTRUCTION_NODE] + )(n) && + (n.target || n.nodeName) === this.name; + }, + toString: function () { + return wrap('processing-instruction("', '")', this.name); + } + }, function (name) { this.name = name; }); + + // singletons + + // elements, attributes, namespaces + NodeTest.nameTestAny = NodeTest.makeNodeTypeTest( + NodeTest.NAMETESTANY, + [ + NodeTypes.ELEMENT_NODE, + NodeTypes.ATTRIBUTE_NODE, + NodeTypes.NAMESPACE_NODE, + ], + '*' + ); + // text, cdata + NodeTest.textTest = NodeTest.makeNodeTypeTest( + NodeTest.TEXT, + [ + NodeTypes.TEXT_NODE, + NodeTypes.CDATA_SECTION_NODE, + ], + 'text()' + ); + NodeTest.commentTest = NodeTest.makeNodeTypeTest( + NodeTest.COMMENT, + [NodeTypes.COMMENT_NODE], + 'comment()' + ); + // elements, attributes, text, cdata, PIs, comments, document nodes + NodeTest.nodeTest = NodeTest.makeNodeTypeTest( + NodeTest.NODE, + [ + NodeTypes.ELEMENT_NODE, + NodeTypes.ATTRIBUTE_NODE, + NodeTypes.TEXT_NODE, + NodeTypes.CDATA_SECTION_NODE, + NodeTypes.PROCESSING_INSTRUCTION_NODE, + NodeTypes.COMMENT_NODE, + NodeTypes.DOCUMENT_NODE, + ], + 'node()' + ); + NodeTest.anyPiTest = NodeTest.makeNodeTypeTest( + NodeTest.PI, + [NodeTypes.PROCESSING_INSTRUCTION_NODE], + 'processing-instruction()' + ); + + // VariableReference ///////////////////////////////////////////////////////// + + VariableReference.prototype = new Expression(); + VariableReference.prototype.constructor = VariableReference; + VariableReference.superclass = Expression.prototype; + + function VariableReference(v) { + if (arguments.length > 0) { + this.init(v); + } + } + + VariableReference.prototype.init = function (v) { + this.variable = v; + }; + + VariableReference.prototype.toString = function () { + return "$" + this.variable; + }; + + VariableReference.prototype.evaluate = function (c) { + var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false); + + if (parts[0] == null) { + throw new Error("Cannot resolve QName " + fn); + } + var result = c.variableResolver.getVariable(parts[1], parts[0]); + if (!result) { + throw XPathException.fromMessage("Undeclared variable: " + this.toString()); + } + return result; + }; + + // FunctionCall ////////////////////////////////////////////////////////////// + + FunctionCall.prototype = new Expression(); + FunctionCall.prototype.constructor = FunctionCall; + FunctionCall.superclass = Expression.prototype; + + function FunctionCall(fn, args) { + if (arguments.length > 0) { + this.init(fn, args); + } + } + + FunctionCall.prototype.init = function (fn, args) { + this.functionName = fn; + this.arguments = args; + }; + + FunctionCall.prototype.toString = function () { + var s = this.functionName + "("; + for (var i = 0; i < this.arguments.length; i++) { + if (i > 0) { + s += ", "; + } + s += this.arguments[i].toString(); + } + return s + ")"; + }; + + FunctionCall.prototype.evaluate = function (c) { + var f = FunctionResolver.getFunctionFromContext(this.functionName, c); + + if (!f) { + throw new Error("Unknown function " + this.functionName); + } + + var a = [c].concat(this.arguments); + return f.apply(c.functionResolver.thisArg, a); + }; + + // Operators ///////////////////////////////////////////////////////////////// + + var Operators = new Object(); + + Operators.equals = function (l, r) { + return l.equals(r); + }; + + Operators.notequal = function (l, r) { + return l.notequal(r); + }; + + Operators.lessthan = function (l, r) { + return l.lessthan(r); + }; + + Operators.greaterthan = function (l, r) { + return l.greaterthan(r); + }; + + Operators.lessthanorequal = function (l, r) { + return l.lessthanorequal(r); + }; + + Operators.greaterthanorequal = function (l, r) { + return l.greaterthanorequal(r); + }; + + // XString /////////////////////////////////////////////////////////////////// + + XString.prototype = new Expression(); + XString.prototype.constructor = XString; + XString.superclass = Expression.prototype; + + function XString(s) { + if (arguments.length > 0) { + this.init(s); + } + } + + XString.prototype.init = function (s) { + this.str = String(s); + }; + + XString.prototype.toString = function () { + return this.str; + }; + + XString.prototype.evaluate = function (c) { + return this; + }; + + XString.prototype.string = function () { + return this; + }; + + XString.prototype.number = function () { + return new XNumber(this.str); + }; + + XString.prototype.bool = function () { + return new XBoolean(this.str); + }; + + XString.prototype.nodeset = function () { + throw new Error("Cannot convert string to nodeset"); + }; + + XString.prototype.stringValue = function () { + return this.str; + }; + + XString.prototype.numberValue = function () { + return this.number().numberValue(); + }; + + XString.prototype.booleanValue = function () { + return this.bool().booleanValue(); + }; + + XString.prototype.equals = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().equals(r); + } + if (Utilities.instance_of(r, XNumber)) { + return this.number().equals(r); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithString(this, Operators.equals); + } + return new XBoolean(this.str == r.str); + }; + + XString.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().notequal(r); + } + if (Utilities.instance_of(r, XNumber)) { + return this.number().notequal(r); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithString(this, Operators.notequal); + } + return new XBoolean(this.str != r.str); + }; + + XString.prototype.lessthan = function (r) { + return this.number().lessthan(r); + }; + + XString.prototype.greaterthan = function (r) { + return this.number().greaterthan(r); + }; + + XString.prototype.lessthanorequal = function (r) { + return this.number().lessthanorequal(r); + }; + + XString.prototype.greaterthanorequal = function (r) { + return this.number().greaterthanorequal(r); + }; + + // XNumber /////////////////////////////////////////////////////////////////// + + XNumber.prototype = new Expression(); + XNumber.prototype.constructor = XNumber; + XNumber.superclass = Expression.prototype; + + function XNumber(n) { + if (arguments.length > 0) { + this.init(n); + } + } + + XNumber.prototype.init = function (n) { + this.num = typeof n === "string" ? this.parse(n) : Number(n); + }; + + XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/; + + XNumber.prototype.parse = function (s) { + // XPath representation of numbers is more restrictive than what Number() or parseFloat() allow + return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN; + }; + + function padSmallNumber(numberStr) { + var parts = numberStr.split('e-'); + var base = parts[0].replace('.', ''); + var exponent = Number(parts[1]); + + for (var i = 0; i < exponent - 1; i += 1) { + base = '0' + base; + } + + return '0.' + base; + } + + function padLargeNumber(numberStr) { + var parts = numberStr.split('e'); + var base = parts[0].replace('.', ''); + var exponent = Number(parts[1]); + var zerosToAppend = exponent + 1 - base.length; + + for (var i = 0; i < zerosToAppend; i += 1) { + base += '0'; + } + + return base; + } + + XNumber.prototype.toString = function () { + var strValue = this.num.toString(); + + if (strValue.indexOf('e-') !== -1) { + return padSmallNumber(strValue); + } + + if (strValue.indexOf('e') !== -1) { + return padLargeNumber(strValue); + } + + return strValue; + }; + + XNumber.prototype.evaluate = function (c) { + return this; + }; + + XNumber.prototype.string = function () { + + + return new XString(this.toString()); + }; + + XNumber.prototype.number = function () { + return this; + }; + + XNumber.prototype.bool = function () { + return new XBoolean(this.num); + }; + + XNumber.prototype.nodeset = function () { + throw new Error("Cannot convert number to nodeset"); + }; + + XNumber.prototype.stringValue = function () { + return this.string().stringValue(); + }; + + XNumber.prototype.numberValue = function () { + return this.num; + }; + + XNumber.prototype.booleanValue = function () { + return this.bool().booleanValue(); + }; + + XNumber.prototype.negate = function () { + return new XNumber(-this.num); + }; + + XNumber.prototype.equals = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().equals(r); + } + if (Utilities.instance_of(r, XString)) { + return this.equals(r.number()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.equals); + } + return new XBoolean(this.num == r.num); + }; + + XNumber.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().notequal(r); + } + if (Utilities.instance_of(r, XString)) { + return this.notequal(r.number()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.notequal); + } + return new XBoolean(this.num != r.num); + }; + + XNumber.prototype.lessthan = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.greaterthan); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.lessthan(r.number()); + } + return new XBoolean(this.num < r.num); + }; + + XNumber.prototype.greaterthan = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.lessthan); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.greaterthan(r.number()); + } + return new XBoolean(this.num > r.num); + }; + + XNumber.prototype.lessthanorequal = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.greaterthanorequal); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.lessthanorequal(r.number()); + } + return new XBoolean(this.num <= r.num); + }; + + XNumber.prototype.greaterthanorequal = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.lessthanorequal); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.greaterthanorequal(r.number()); + } + return new XBoolean(this.num >= r.num); + }; + + XNumber.prototype.plus = function (r) { + return new XNumber(this.num + r.num); + }; + + XNumber.prototype.minus = function (r) { + return new XNumber(this.num - r.num); + }; + + XNumber.prototype.multiply = function (r) { + return new XNumber(this.num * r.num); + }; + + XNumber.prototype.div = function (r) { + return new XNumber(this.num / r.num); + }; + + XNumber.prototype.mod = function (r) { + return new XNumber(this.num % r.num); + }; + + // XBoolean ////////////////////////////////////////////////////////////////// + + XBoolean.prototype = new Expression(); + XBoolean.prototype.constructor = XBoolean; + XBoolean.superclass = Expression.prototype; + + function XBoolean(b) { + if (arguments.length > 0) { + this.init(b); + } + } + + XBoolean.prototype.init = function (b) { + this.b = Boolean(b); + }; + + XBoolean.prototype.toString = function () { + return this.b.toString(); + }; + + XBoolean.prototype.evaluate = function (c) { + return this; + }; + + XBoolean.prototype.string = function () { + return new XString(this.b); + }; + + XBoolean.prototype.number = function () { + return new XNumber(this.b); + }; + + XBoolean.prototype.bool = function () { + return this; + }; + + XBoolean.prototype.nodeset = function () { + throw new Error("Cannot convert boolean to nodeset"); + }; + + XBoolean.prototype.stringValue = function () { + return this.string().stringValue(); + }; + + XBoolean.prototype.numberValue = function () { + return this.number().numberValue(); + }; + + XBoolean.prototype.booleanValue = function () { + return this.b; + }; + + XBoolean.prototype.not = function () { + return new XBoolean(!this.b); + }; + + XBoolean.prototype.equals = function (r) { + if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { + return this.equals(r.bool()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithBoolean(this, Operators.equals); + } + return new XBoolean(this.b == r.b); + }; + + XBoolean.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { + return this.notequal(r.bool()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithBoolean(this, Operators.notequal); + } + return new XBoolean(this.b != r.b); + }; + + XBoolean.prototype.lessthan = function (r) { + return this.number().lessthan(r); + }; + + XBoolean.prototype.greaterthan = function (r) { + return this.number().greaterthan(r); + }; + + XBoolean.prototype.lessthanorequal = function (r) { + return this.number().lessthanorequal(r); + }; + + XBoolean.prototype.greaterthanorequal = function (r) { + return this.number().greaterthanorequal(r); + }; + + XBoolean.true_ = new XBoolean(true); + XBoolean.false_ = new XBoolean(false); + + // AVLTree /////////////////////////////////////////////////////////////////// + + AVLTree.prototype = new Object(); + AVLTree.prototype.constructor = AVLTree; + AVLTree.superclass = Object.prototype; + + function AVLTree(n) { + this.init(n); + } + + AVLTree.prototype.init = function (n) { + this.left = null; + this.right = null; + this.node = n; + this.depth = 1; + }; + + AVLTree.prototype.balance = function () { + var ldepth = this.left == null ? 0 : this.left.depth; + var rdepth = this.right == null ? 0 : this.right.depth; + + if (ldepth > rdepth + 1) { + // LR or LL rotation + var lldepth = this.left.left == null ? 0 : this.left.left.depth; + var lrdepth = this.left.right == null ? 0 : this.left.right.depth; + + if (lldepth < lrdepth) { + // LR rotation consists of a RR rotation of the left child + this.left.rotateRR(); + // plus a LL rotation of this node, which happens anyway + } + this.rotateLL(); + } else if (ldepth + 1 < rdepth) { + // RR or RL rorarion + var rrdepth = this.right.right == null ? 0 : this.right.right.depth; + var rldepth = this.right.left == null ? 0 : this.right.left.depth; + + if (rldepth > rrdepth) { + // RR rotation consists of a LL rotation of the right child + this.right.rotateLL(); + // plus a RR rotation of this node, which happens anyway + } + this.rotateRR(); + } + }; + + AVLTree.prototype.rotateLL = function () { + // the left side is too long => rotate from the left (_not_ leftwards) + var nodeBefore = this.node; + var rightBefore = this.right; + this.node = this.left.node; + this.right = this.left; + this.left = this.left.left; + this.right.left = this.right.right; + this.right.right = rightBefore; + this.right.node = nodeBefore; + this.right.updateInNewLocation(); + this.updateInNewLocation(); + }; + + AVLTree.prototype.rotateRR = function () { + // the right side is too long => rotate from the right (_not_ rightwards) + var nodeBefore = this.node; + var leftBefore = this.left; + this.node = this.right.node; + this.left = this.right; + this.right = this.right.right; + this.left.right = this.left.left; + this.left.left = leftBefore; + this.left.node = nodeBefore; + this.left.updateInNewLocation(); + this.updateInNewLocation(); + }; + + AVLTree.prototype.updateInNewLocation = function () { + this.getDepthFromChildren(); + }; + + AVLTree.prototype.getDepthFromChildren = function () { + this.depth = this.node == null ? 0 : 1; + if (this.left != null) { + this.depth = this.left.depth + 1; + } + if (this.right != null && this.depth <= this.right.depth) { + this.depth = this.right.depth + 1; + } + }; + + function nodeOrder(n1, n2) { + if (n1 === n2) { + return 0; + } + + if (n1.compareDocumentPosition) { + var cpos = n1.compareDocumentPosition(n2); + + if (cpos & 0x01) { + // not in the same document; return an arbitrary result (is there a better way to do this) + return 1; + } + if (cpos & 0x0A) { + // n2 precedes or contains n1 + return 1; + } + if (cpos & 0x14) { + // n2 follows or is contained by n1 + return -1; + } + + return 0; + } + + var d1 = 0, + d2 = 0; + for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) { + d1++; + } + for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) { + d2++; + } + + // step up to same depth + if (d1 > d2) { + while (d1 > d2) { + n1 = n1.parentNode || n1.ownerElement; + d1--; + } + if (n1 === n2) { + return 1; + } + } else if (d2 > d1) { + while (d2 > d1) { + n2 = n2.parentNode || n2.ownerElement; + d2--; + } + if (n1 === n2) { + return -1; + } + } + + var n1Par = n1.parentNode || n1.ownerElement, + n2Par = n2.parentNode || n2.ownerElement; + + // find common parent + while (n1Par !== n2Par) { + n1 = n1Par; + n2 = n2Par; + n1Par = n1.parentNode || n1.ownerElement; + n2Par = n2.parentNode || n2.ownerElement; + } + + var n1isAttr = isAttributeLike(n1); + var n2isAttr = isAttributeLike(n2); + + if (n1isAttr && !n2isAttr) { + return -1; + } + if (!n1isAttr && n2isAttr) { + return 1; + } + + // xml namespace node comes before others. namespace nodes before non-namespace nodes + if (n1.isXPathNamespace) { + if (n1.nodeValue === XPath.XML_NAMESPACE_URI) { + return -1; + } + + if (!n2.isXPathNamespace) { + return -1; + } + + if (n2.nodeValue === XPath.XML_NAMESPACE_URI) { + return 1; + } + } else if (n2.isXPathNamespace) { + return 1; + } + + if (n1Par) { + var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes; + var len = cn.length; + var n1Compare = n1.baseNode || n1; + var n2Compare = n2.baseNode || n2; + + for (var i = 0; i < len; i += 1) { + var n = cn[i]; + if (n === n1Compare) { + return -1; + } + if (n === n2Compare) { + return 1; + } + } + } + + throw new Error('Unexpected: could not determine node order'); + } + + AVLTree.prototype.add = function (n) { + if (n === this.node) { + return false; + } + + var o = nodeOrder(n, this.node); + + var ret = false; + if (o == -1) { + if (this.left == null) { + this.left = new AVLTree(n); + ret = true; + } else { + ret = this.left.add(n); + if (ret) { + this.balance(); + } + } + } else if (o == 1) { + if (this.right == null) { + this.right = new AVLTree(n); + ret = true; + } else { + ret = this.right.add(n); + if (ret) { + this.balance(); + } + } + } + + if (ret) { + this.getDepthFromChildren(); + } + return ret; + }; + + // XNodeSet ////////////////////////////////////////////////////////////////// + + XNodeSet.prototype = new Expression(); + XNodeSet.prototype.constructor = XNodeSet; + XNodeSet.superclass = Expression.prototype; + + function XNodeSet() { + this.init(); + } + + XNodeSet.prototype.init = function () { + this.tree = null; + this.nodes = []; + this.size = 0; + }; + + XNodeSet.prototype.toString = function () { + var p = this.first(); + if (p == null) { + return ""; + } + return this.stringForNode(p); + }; + + XNodeSet.prototype.evaluate = function (c) { + return this; + }; + + XNodeSet.prototype.string = function () { + return new XString(this.toString()); + }; + + XNodeSet.prototype.stringValue = function () { + return this.toString(); + }; + + XNodeSet.prototype.number = function () { + return new XNumber(this.string()); + }; + + XNodeSet.prototype.numberValue = function () { + return Number(this.string()); + }; + + XNodeSet.prototype.bool = function () { + return new XBoolean(this.booleanValue()); + }; + + XNodeSet.prototype.booleanValue = function () { + return !!this.size; + }; + + XNodeSet.prototype.nodeset = function () { + return this; + }; + + XNodeSet.prototype.stringForNode = function (n) { + if (n.nodeType == NodeTypes.DOCUMENT_NODE || + n.nodeType == NodeTypes.ELEMENT_NODE || + n.nodeType === NodeTypes.DOCUMENT_FRAGMENT_NODE) { + return this.stringForContainerNode(n); + } + if (n.nodeType === NodeTypes.ATTRIBUTE_NODE) { + return n.value || n.nodeValue; + } + if (n.isNamespaceNode) { + return n.namespace; + } + return n.nodeValue; + }; + + XNodeSet.prototype.stringForContainerNode = function (n) { + var s = ""; + for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) { + var nt = n2.nodeType; + // Element, Text, CDATA, Document, Document Fragment + if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) { + s += this.stringForNode(n2); + } + } + return s; + }; + + XNodeSet.prototype.buildTree = function () { + if (!this.tree && this.nodes.length) { + this.tree = new AVLTree(this.nodes[0]); + for (var i = 1; i < this.nodes.length; i += 1) { + this.tree.add(this.nodes[i]); + } + } + + return this.tree; + }; + + XNodeSet.prototype.first = function () { + var p = this.buildTree(); + if (p == null) { + return null; + } + while (p.left != null) { + p = p.left; + } + return p.node; + }; + + XNodeSet.prototype.add = function (n) { + for (var i = 0; i < this.nodes.length; i += 1) { + if (n === this.nodes[i]) { + return; + } + } + + this.tree = null; + this.nodes.push(n); + this.size += 1; + }; + + XNodeSet.prototype.addArray = function (ns) { + var self = this; + + forEach(function (x) { self.add(x); }, ns); + }; + + /** + * Returns an array of the node set's contents in document order + */ + XNodeSet.prototype.toArray = function () { + var a = []; + this.toArrayRec(this.buildTree(), a); + return a; + }; + + XNodeSet.prototype.toArrayRec = function (t, a) { + if (t != null) { + this.toArrayRec(t.left, a); + a.push(t.node); + this.toArrayRec(t.right, a); + } + }; + + /** + * Returns an array of the node set's contents in arbitrary order + */ + XNodeSet.prototype.toUnsortedArray = function () { + return this.nodes.slice(); + }; + + XNodeSet.prototype.compareWithString = function (r, o) { + var a = this.toUnsortedArray(); + for (var i = 0; i < a.length; i++) { + var n = a[i]; + var l = new XString(this.stringForNode(n)); + var res = o(l, r); + if (res.booleanValue()) { + return res; + } + } + return new XBoolean(false); + }; + + XNodeSet.prototype.compareWithNumber = function (r, o) { + var a = this.toUnsortedArray(); + for (var i = 0; i < a.length; i++) { + var n = a[i]; + var l = new XNumber(this.stringForNode(n)); + var res = o(l, r); + if (res.booleanValue()) { + return res; + } + } + return new XBoolean(false); + }; + + XNodeSet.prototype.compareWithBoolean = function (r, o) { + return o(this.bool(), r); + }; + + XNodeSet.prototype.compareWithNodeSet = function (r, o) { + var arr = this.toUnsortedArray(); + var oInvert = function (lop, rop) { return o(rop, lop); }; + + for (var i = 0; i < arr.length; i++) { + var l = new XString(this.stringForNode(arr[i])); + + var res = r.compareWithString(l, oInvert); + if (res.booleanValue()) { + return res; + } + } + + return new XBoolean(false); + }; + + XNodeSet.compareWith = curry(function (o, r) { + if (Utilities.instance_of(r, XString)) { + return this.compareWithString(r, o); + } + if (Utilities.instance_of(r, XNumber)) { + return this.compareWithNumber(r, o); + } + if (Utilities.instance_of(r, XBoolean)) { + return this.compareWithBoolean(r, o); + } + return this.compareWithNodeSet(r, o); + }); + + XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals); + XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal); + XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan); + XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan); + XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal); + XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal); + + XNodeSet.prototype.union = function (r) { + var ns = new XNodeSet(); + ns.addArray(this.toUnsortedArray()); + ns.addArray(r.toUnsortedArray()); + return ns; + }; + + // XPathNamespace //////////////////////////////////////////////////////////// + + XPathNamespace.prototype = new Object(); + XPathNamespace.prototype.constructor = XPathNamespace; + XPathNamespace.superclass = Object.prototype; + + function XPathNamespace(pre, node, uri, p) { + this.isXPathNamespace = true; + this.baseNode = node; + this.ownerDocument = p.ownerDocument; + this.nodeName = pre; + this.prefix = pre; + this.localName = pre; + this.namespaceURI = null; + this.nodeValue = uri; + this.ownerElement = p; + this.nodeType = NodeTypes.NAMESPACE_NODE; + } + + XPathNamespace.prototype.toString = function () { + return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }"; + }; + + // XPathContext ////////////////////////////////////////////////////////////// + + XPathContext.prototype = new Object(); + XPathContext.prototype.constructor = XPathContext; + XPathContext.superclass = Object.prototype; + + function XPathContext(vr, nr, fr) { + this.variableResolver = vr != null ? vr : new VariableResolver(); + this.namespaceResolver = nr != null ? nr : new NamespaceResolver(); + this.functionResolver = fr != null ? fr : new FunctionResolver(); + } + + XPathContext.prototype.extend = function (newProps) { + return assign(new XPathContext(), this, newProps); + }; + + // VariableResolver ////////////////////////////////////////////////////////// + + VariableResolver.prototype = new Object(); + VariableResolver.prototype.constructor = VariableResolver; + VariableResolver.superclass = Object.prototype; + + function VariableResolver() { + } + + VariableResolver.prototype.getVariable = function (ln, ns) { + return null; + }; + + // FunctionResolver ////////////////////////////////////////////////////////// + + FunctionResolver.prototype = new Object(); + FunctionResolver.prototype.constructor = FunctionResolver; + FunctionResolver.superclass = Object.prototype; + + function FunctionResolver(thisArg) { + this.thisArg = thisArg != null ? thisArg : Functions; + this.functions = new Object(); + this.addStandardFunctions(); + } + + FunctionResolver.prototype.addStandardFunctions = function () { + this.functions["{}last"] = Functions.last; + this.functions["{}position"] = Functions.position; + this.functions["{}count"] = Functions.count; + this.functions["{}id"] = Functions.id; + this.functions["{}local-name"] = Functions.localName; + this.functions["{}namespace-uri"] = Functions.namespaceURI; + this.functions["{}name"] = Functions.name; + this.functions["{}string"] = Functions.string; + this.functions["{}concat"] = Functions.concat; + this.functions["{}starts-with"] = Functions.startsWith; + this.functions["{}contains"] = Functions.contains; + this.functions["{}substring-before"] = Functions.substringBefore; + this.functions["{}substring-after"] = Functions.substringAfter; + this.functions["{}substring"] = Functions.substring; + this.functions["{}string-length"] = Functions.stringLength; + this.functions["{}normalize-space"] = Functions.normalizeSpace; + this.functions["{}translate"] = Functions.translate; + this.functions["{}boolean"] = Functions.boolean_; + this.functions["{}not"] = Functions.not; + this.functions["{}true"] = Functions.true_; + this.functions["{}false"] = Functions.false_; + this.functions["{}lang"] = Functions.lang; + this.functions["{}number"] = Functions.number; + this.functions["{}sum"] = Functions.sum; + this.functions["{}floor"] = Functions.floor; + this.functions["{}ceiling"] = Functions.ceiling; + this.functions["{}round"] = Functions.round; + }; + + FunctionResolver.prototype.addFunction = function (ns, ln, f) { + this.functions["{" + ns + "}" + ln] = f; + }; + + FunctionResolver.getFunctionFromContext = function (qName, context) { + var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false); + + if (parts[0] === null) { + throw new Error("Cannot resolve QName " + name); + } + + return context.functionResolver.getFunction(parts[1], parts[0]); + }; + + FunctionResolver.prototype.getFunction = function (localName, namespace) { + return this.functions["{" + namespace + "}" + localName]; + }; + + // NamespaceResolver ///////////////////////////////////////////////////////// + + NamespaceResolver.prototype = new Object(); + NamespaceResolver.prototype.constructor = NamespaceResolver; + NamespaceResolver.superclass = Object.prototype; + + function NamespaceResolver() { + } + + NamespaceResolver.prototype.getNamespace = function (prefix, n) { + if (prefix == "xml") { + return XPath.XML_NAMESPACE_URI; + } else if (prefix == "xmlns") { + return XPath.XMLNS_NAMESPACE_URI; + } + if (n.nodeType == NodeTypes.DOCUMENT_NODE) { + n = n.documentElement; + } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) { + n = PathExpr.getOwnerElement(n); + } else if (n.nodeType != NodeTypes.ELEMENT_NODE) { + n = n.parentNode; + } + while (n != null && n.nodeType == NodeTypes.ELEMENT_NODE) { + var nnm = n.attributes; + for (var i = 0; i < nnm.length; i++) { + var a = nnm.item(i); + var aname = a.name || a.nodeName; + if ((aname === "xmlns" && prefix === "") + || aname === "xmlns:" + prefix) { + return String(a.value || a.nodeValue); + } + } + n = n.parentNode; + } + return null; + }; + + // Functions ///////////////////////////////////////////////////////////////// + + var Functions = new Object(); + + Functions.last = function (c) { + if (arguments.length != 1) { + throw new Error("Function last expects ()"); + } + + return new XNumber(c.contextSize); + }; + + Functions.position = function (c) { + if (arguments.length != 1) { + throw new Error("Function position expects ()"); + } + + return new XNumber(c.contextPosition); + }; + + Functions.count = function () { + var c = arguments[0]; + var ns; + if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) { + throw new Error("Function count expects (node-set)"); + } + return new XNumber(ns.size); + }; + + Functions.id = function () { + var c = arguments[0]; + var id; + if (arguments.length != 2) { + throw new Error("Function id expects (object)"); + } + id = arguments[1].evaluate(c); + if (Utilities.instance_of(id, XNodeSet)) { + id = id.toArray().join(" "); + } else { + id = id.stringValue(); + } + var ids = id.split(/[\x0d\x0a\x09\x20]+/); + var ns = new XNodeSet(); + var doc = c.contextNode.nodeType == NodeTypes.DOCUMENT_NODE + ? c.contextNode + : c.contextNode.ownerDocument; + for (var i = 0; i < ids.length; i++) { + var n; + if (doc.getElementById) { + n = doc.getElementById(ids[i]); + } else { + n = Utilities.getElementById(doc, ids[i]); + } + if (n != null) { + ns.add(n); + } + } + return ns; + }; + + Functions.localName = function (c, eNode) { + var n; + + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = eNode.evaluate(c).first(); + } else { + throw new Error("Function local-name expects (node-set?)"); + } + + if (n == null) { + return new XString(""); + } + + return new XString( + n.localName || // standard elements and attributes + n.baseName || // IE + n.target || // processing instructions + n.nodeName || // DOM1 elements + "" // fallback + ); + }; + + Functions.namespaceURI = function () { + var c = arguments[0]; + var n; + + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = arguments[1].evaluate(c).first(); + } else { + throw new Error("Function namespace-uri expects (node-set?)"); + } + + if (n == null) { + return new XString(""); + } + return new XString(n.namespaceURI || ''); + }; + + Functions.name = function () { + var c = arguments[0]; + var n; + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = arguments[1].evaluate(c).first(); + } else { + throw new Error("Function name expects (node-set?)"); + } + if (n == null) { + return new XString(""); + } + if (n.nodeType == NodeTypes.ELEMENT_NODE) { + return new XString(n.nodeName); + } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) { + return new XString(n.name || n.nodeName); + } else if (n.nodeType === NodeTypes.PROCESSING_INSTRUCTION_NODE) { + return new XString(n.target || n.nodeName); + } else if (n.localName == null) { + return new XString(""); + } else { + return new XString(n.localName); + } + }; + + Functions.string = function () { + var c = arguments[0]; + if (arguments.length == 1) { + return new XString(XNodeSet.prototype.stringForNode(c.contextNode)); + } else if (arguments.length == 2) { + return arguments[1].evaluate(c).string(); + } + throw new Error("Function string expects (object?)"); + }; + + Functions.concat = function (c) { + if (arguments.length < 3) { + throw new Error("Function concat expects (string, string[, string]*)"); + } + var s = ""; + for (var i = 1; i < arguments.length; i++) { + s += arguments[i].evaluate(c).stringValue(); + } + return new XString(s); + }; + + Functions.startsWith = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function startsWith expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XBoolean(s1.substring(0, s2.length) == s2); + }; + + Functions.contains = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function contains expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XBoolean(s1.indexOf(s2) !== -1); + }; + + Functions.substringBefore = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function substring-before expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XString(s1.substring(0, s1.indexOf(s2))); + }; + + Functions.substringAfter = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function substring-after expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + if (s2.length == 0) { + return new XString(s1); + } + var i = s1.indexOf(s2); + if (i == -1) { + return new XString(""); + } + return new XString(s1.substring(i + s2.length)); + }; + + Functions.substring = function () { + var c = arguments[0]; + if (!(arguments.length == 3 || arguments.length == 4)) { + throw new Error("Function substring expects (string, number, number?)"); + } + var s = arguments[1].evaluate(c).stringValue(); + var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1; + var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined; + return new XString(s.substring(n1, n2)); + }; + + Functions.stringLength = function () { + var c = arguments[0]; + var s; + if (arguments.length == 1) { + s = XNodeSet.prototype.stringForNode(c.contextNode); + } else if (arguments.length == 2) { + s = arguments[1].evaluate(c).stringValue(); + } else { + throw new Error("Function string-length expects (string?)"); + } + return new XNumber(s.length); + }; + + Functions.normalizeSpace = function () { + var c = arguments[0]; + var s; + if (arguments.length == 1) { + s = XNodeSet.prototype.stringForNode(c.contextNode); + } else if (arguments.length == 2) { + s = arguments[1].evaluate(c).stringValue(); + } else { + throw new Error("Function normalize-space expects (string?)"); + } + var i = 0; + var j = s.length - 1; + while (Utilities.isSpace(s.charCodeAt(j))) { + j--; + } + var t = ""; + while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { + i++; + } + while (i <= j) { + if (Utilities.isSpace(s.charCodeAt(i))) { + t += " "; + while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { + i++; + } + } else { + t += s.charAt(i); + i++; + } + } + return new XString(t); + }; + + Functions.translate = function (c, eValue, eFrom, eTo) { + if (arguments.length != 4) { + throw new Error("Function translate expects (string, string, string)"); + } + + var value = eValue.evaluate(c).stringValue(); + var from = eFrom.evaluate(c).stringValue(); + var to = eTo.evaluate(c).stringValue(); + + var cMap = reduce(function (acc, ch, i) { + if (!(ch in acc)) { + acc[ch] = i > to.length ? '' : to[i]; + } + return acc; + }, {}, from); + + var t = join( + '', + map(function (ch) { + return ch in cMap ? cMap[ch] : ch; + }, value) + ); + + return new XString(t); + }; + + Functions.boolean_ = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function boolean expects (object)"); + } + return arguments[1].evaluate(c).bool(); + }; + + Functions.not = function (c, eValue) { + if (arguments.length != 2) { + throw new Error("Function not expects (object)"); + } + return eValue.evaluate(c).bool().not(); + }; + + Functions.true_ = function () { + if (arguments.length != 1) { + throw new Error("Function true expects ()"); + } + return XBoolean.true_; + }; + + Functions.false_ = function () { + if (arguments.length != 1) { + throw new Error("Function false expects ()"); + } + return XBoolean.false_; + }; + + Functions.lang = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function lang expects (string)"); + } + var lang; + for (var n = c.contextNode; n != null && n.nodeType != NodeTypes.DOCUMENT_NODE; n = n.parentNode) { + var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang"); + if (a != null) { + lang = String(a); + break; + } + } + if (lang == null) { + return XBoolean.false_; + } + var s = arguments[1].evaluate(c).stringValue(); + return new XBoolean(lang.substring(0, s.length) == s + && (lang.length == s.length || lang.charAt(s.length) == '-')); + }; + + Functions.number = function () { + var c = arguments[0]; + if (!(arguments.length == 1 || arguments.length == 2)) { + throw new Error("Function number expects (object?)"); + } + if (arguments.length == 1) { + return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode)); + } + return arguments[1].evaluate(c).number(); + }; + + Functions.sum = function () { + var c = arguments[0]; + var ns; + if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) { + throw new Error("Function sum expects (node-set)"); + } + ns = ns.toUnsortedArray(); + var n = 0; + for (var i = 0; i < ns.length; i++) { + n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue(); + } + return new XNumber(n); + }; + + Functions.floor = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function floor expects (number)"); + } + return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue())); + }; + + Functions.ceiling = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function ceiling expects (number)"); + } + return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue())); + }; + + Functions.round = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function round expects (number)"); + } + return new XNumber(Math.round(arguments[1].evaluate(c).numberValue())); + }; + + // Utilities ///////////////////////////////////////////////////////////////// + + var Utilities = new Object(); + + // Returns true if the node is an attribute node or namespace node + var isAttributeLike = function (val) { + return val && ( + val.nodeType === NodeTypes.ATTRIBUTE_NODE || + val.ownerElement || + val.isXPathNamespace + ); + }; + + Utilities.splitQName = function (qn) { + var i = qn.indexOf(":"); + if (i == -1) { + return [null, qn]; + } + return [qn.substring(0, i), qn.substring(i + 1)]; + }; + + Utilities.resolveQName = function (qn, nr, n, useDefault) { + var parts = Utilities.splitQName(qn); + if (parts[0] != null) { + parts[0] = nr.getNamespace(parts[0], n); + } else { + if (useDefault) { + parts[0] = nr.getNamespace("", n); + if (parts[0] == null) { + parts[0] = ""; + } + } else { + parts[0] = ""; + } + } + return parts; + }; + + Utilities.isSpace = function (c) { + return c == 0x9 || c == 0xd || c == 0xa || c == 0x20; + }; + + Utilities.isLetter = function (c) { + return c >= 0x0041 && c <= 0x005A || + c >= 0x0061 && c <= 0x007A || + c >= 0x00C0 && c <= 0x00D6 || + c >= 0x00D8 && c <= 0x00F6 || + c >= 0x00F8 && c <= 0x00FF || + c >= 0x0100 && c <= 0x0131 || + c >= 0x0134 && c <= 0x013E || + c >= 0x0141 && c <= 0x0148 || + c >= 0x014A && c <= 0x017E || + c >= 0x0180 && c <= 0x01C3 || + c >= 0x01CD && c <= 0x01F0 || + c >= 0x01F4 && c <= 0x01F5 || + c >= 0x01FA && c <= 0x0217 || + c >= 0x0250 && c <= 0x02A8 || + c >= 0x02BB && c <= 0x02C1 || + c == 0x0386 || + c >= 0x0388 && c <= 0x038A || + c == 0x038C || + c >= 0x038E && c <= 0x03A1 || + c >= 0x03A3 && c <= 0x03CE || + c >= 0x03D0 && c <= 0x03D6 || + c == 0x03DA || + c == 0x03DC || + c == 0x03DE || + c == 0x03E0 || + c >= 0x03E2 && c <= 0x03F3 || + c >= 0x0401 && c <= 0x040C || + c >= 0x040E && c <= 0x044F || + c >= 0x0451 && c <= 0x045C || + c >= 0x045E && c <= 0x0481 || + c >= 0x0490 && c <= 0x04C4 || + c >= 0x04C7 && c <= 0x04C8 || + c >= 0x04CB && c <= 0x04CC || + c >= 0x04D0 && c <= 0x04EB || + c >= 0x04EE && c <= 0x04F5 || + c >= 0x04F8 && c <= 0x04F9 || + c >= 0x0531 && c <= 0x0556 || + c == 0x0559 || + c >= 0x0561 && c <= 0x0586 || + c >= 0x05D0 && c <= 0x05EA || + c >= 0x05F0 && c <= 0x05F2 || + c >= 0x0621 && c <= 0x063A || + c >= 0x0641 && c <= 0x064A || + c >= 0x0671 && c <= 0x06B7 || + c >= 0x06BA && c <= 0x06BE || + c >= 0x06C0 && c <= 0x06CE || + c >= 0x06D0 && c <= 0x06D3 || + c == 0x06D5 || + c >= 0x06E5 && c <= 0x06E6 || + c >= 0x0905 && c <= 0x0939 || + c == 0x093D || + c >= 0x0958 && c <= 0x0961 || + c >= 0x0985 && c <= 0x098C || + c >= 0x098F && c <= 0x0990 || + c >= 0x0993 && c <= 0x09A8 || + c >= 0x09AA && c <= 0x09B0 || + c == 0x09B2 || + c >= 0x09B6 && c <= 0x09B9 || + c >= 0x09DC && c <= 0x09DD || + c >= 0x09DF && c <= 0x09E1 || + c >= 0x09F0 && c <= 0x09F1 || + c >= 0x0A05 && c <= 0x0A0A || + c >= 0x0A0F && c <= 0x0A10 || + c >= 0x0A13 && c <= 0x0A28 || + c >= 0x0A2A && c <= 0x0A30 || + c >= 0x0A32 && c <= 0x0A33 || + c >= 0x0A35 && c <= 0x0A36 || + c >= 0x0A38 && c <= 0x0A39 || + c >= 0x0A59 && c <= 0x0A5C || + c == 0x0A5E || + c >= 0x0A72 && c <= 0x0A74 || + c >= 0x0A85 && c <= 0x0A8B || + c == 0x0A8D || + c >= 0x0A8F && c <= 0x0A91 || + c >= 0x0A93 && c <= 0x0AA8 || + c >= 0x0AAA && c <= 0x0AB0 || + c >= 0x0AB2 && c <= 0x0AB3 || + c >= 0x0AB5 && c <= 0x0AB9 || + c == 0x0ABD || + c == 0x0AE0 || + c >= 0x0B05 && c <= 0x0B0C || + c >= 0x0B0F && c <= 0x0B10 || + c >= 0x0B13 && c <= 0x0B28 || + c >= 0x0B2A && c <= 0x0B30 || + c >= 0x0B32 && c <= 0x0B33 || + c >= 0x0B36 && c <= 0x0B39 || + c == 0x0B3D || + c >= 0x0B5C && c <= 0x0B5D || + c >= 0x0B5F && c <= 0x0B61 || + c >= 0x0B85 && c <= 0x0B8A || + c >= 0x0B8E && c <= 0x0B90 || + c >= 0x0B92 && c <= 0x0B95 || + c >= 0x0B99 && c <= 0x0B9A || + c == 0x0B9C || + c >= 0x0B9E && c <= 0x0B9F || + c >= 0x0BA3 && c <= 0x0BA4 || + c >= 0x0BA8 && c <= 0x0BAA || + c >= 0x0BAE && c <= 0x0BB5 || + c >= 0x0BB7 && c <= 0x0BB9 || + c >= 0x0C05 && c <= 0x0C0C || + c >= 0x0C0E && c <= 0x0C10 || + c >= 0x0C12 && c <= 0x0C28 || + c >= 0x0C2A && c <= 0x0C33 || + c >= 0x0C35 && c <= 0x0C39 || + c >= 0x0C60 && c <= 0x0C61 || + c >= 0x0C85 && c <= 0x0C8C || + c >= 0x0C8E && c <= 0x0C90 || + c >= 0x0C92 && c <= 0x0CA8 || + c >= 0x0CAA && c <= 0x0CB3 || + c >= 0x0CB5 && c <= 0x0CB9 || + c == 0x0CDE || + c >= 0x0CE0 && c <= 0x0CE1 || + c >= 0x0D05 && c <= 0x0D0C || + c >= 0x0D0E && c <= 0x0D10 || + c >= 0x0D12 && c <= 0x0D28 || + c >= 0x0D2A && c <= 0x0D39 || + c >= 0x0D60 && c <= 0x0D61 || + c >= 0x0E01 && c <= 0x0E2E || + c == 0x0E30 || + c >= 0x0E32 && c <= 0x0E33 || + c >= 0x0E40 && c <= 0x0E45 || + c >= 0x0E81 && c <= 0x0E82 || + c == 0x0E84 || + c >= 0x0E87 && c <= 0x0E88 || + c == 0x0E8A || + c == 0x0E8D || + c >= 0x0E94 && c <= 0x0E97 || + c >= 0x0E99 && c <= 0x0E9F || + c >= 0x0EA1 && c <= 0x0EA3 || + c == 0x0EA5 || + c == 0x0EA7 || + c >= 0x0EAA && c <= 0x0EAB || + c >= 0x0EAD && c <= 0x0EAE || + c == 0x0EB0 || + c >= 0x0EB2 && c <= 0x0EB3 || + c == 0x0EBD || + c >= 0x0EC0 && c <= 0x0EC4 || + c >= 0x0F40 && c <= 0x0F47 || + c >= 0x0F49 && c <= 0x0F69 || + c >= 0x10A0 && c <= 0x10C5 || + c >= 0x10D0 && c <= 0x10F6 || + c == 0x1100 || + c >= 0x1102 && c <= 0x1103 || + c >= 0x1105 && c <= 0x1107 || + c == 0x1109 || + c >= 0x110B && c <= 0x110C || + c >= 0x110E && c <= 0x1112 || + c == 0x113C || + c == 0x113E || + c == 0x1140 || + c == 0x114C || + c == 0x114E || + c == 0x1150 || + c >= 0x1154 && c <= 0x1155 || + c == 0x1159 || + c >= 0x115F && c <= 0x1161 || + c == 0x1163 || + c == 0x1165 || + c == 0x1167 || + c == 0x1169 || + c >= 0x116D && c <= 0x116E || + c >= 0x1172 && c <= 0x1173 || + c == 0x1175 || + c == 0x119E || + c == 0x11A8 || + c == 0x11AB || + c >= 0x11AE && c <= 0x11AF || + c >= 0x11B7 && c <= 0x11B8 || + c == 0x11BA || + c >= 0x11BC && c <= 0x11C2 || + c == 0x11EB || + c == 0x11F0 || + c == 0x11F9 || + c >= 0x1E00 && c <= 0x1E9B || + c >= 0x1EA0 && c <= 0x1EF9 || + c >= 0x1F00 && c <= 0x1F15 || + c >= 0x1F18 && c <= 0x1F1D || + c >= 0x1F20 && c <= 0x1F45 || + c >= 0x1F48 && c <= 0x1F4D || + c >= 0x1F50 && c <= 0x1F57 || + c == 0x1F59 || + c == 0x1F5B || + c == 0x1F5D || + c >= 0x1F5F && c <= 0x1F7D || + c >= 0x1F80 && c <= 0x1FB4 || + c >= 0x1FB6 && c <= 0x1FBC || + c == 0x1FBE || + c >= 0x1FC2 && c <= 0x1FC4 || + c >= 0x1FC6 && c <= 0x1FCC || + c >= 0x1FD0 && c <= 0x1FD3 || + c >= 0x1FD6 && c <= 0x1FDB || + c >= 0x1FE0 && c <= 0x1FEC || + c >= 0x1FF2 && c <= 0x1FF4 || + c >= 0x1FF6 && c <= 0x1FFC || + c == 0x2126 || + c >= 0x212A && c <= 0x212B || + c == 0x212E || + c >= 0x2180 && c <= 0x2182 || + c >= 0x3041 && c <= 0x3094 || + c >= 0x30A1 && c <= 0x30FA || + c >= 0x3105 && c <= 0x312C || + c >= 0xAC00 && c <= 0xD7A3 || + c >= 0x4E00 && c <= 0x9FA5 || + c == 0x3007 || + c >= 0x3021 && c <= 0x3029; + }; + + Utilities.isNCNameChar = function (c) { + return c >= 0x0030 && c <= 0x0039 + || c >= 0x0660 && c <= 0x0669 + || c >= 0x06F0 && c <= 0x06F9 + || c >= 0x0966 && c <= 0x096F + || c >= 0x09E6 && c <= 0x09EF + || c >= 0x0A66 && c <= 0x0A6F + || c >= 0x0AE6 && c <= 0x0AEF + || c >= 0x0B66 && c <= 0x0B6F + || c >= 0x0BE7 && c <= 0x0BEF + || c >= 0x0C66 && c <= 0x0C6F + || c >= 0x0CE6 && c <= 0x0CEF + || c >= 0x0D66 && c <= 0x0D6F + || c >= 0x0E50 && c <= 0x0E59 + || c >= 0x0ED0 && c <= 0x0ED9 + || c >= 0x0F20 && c <= 0x0F29 + || c == 0x002E + || c == 0x002D + || c == 0x005F + || Utilities.isLetter(c) + || c >= 0x0300 && c <= 0x0345 + || c >= 0x0360 && c <= 0x0361 + || c >= 0x0483 && c <= 0x0486 + || c >= 0x0591 && c <= 0x05A1 + || c >= 0x05A3 && c <= 0x05B9 + || c >= 0x05BB && c <= 0x05BD + || c == 0x05BF + || c >= 0x05C1 && c <= 0x05C2 + || c == 0x05C4 + || c >= 0x064B && c <= 0x0652 + || c == 0x0670 + || c >= 0x06D6 && c <= 0x06DC + || c >= 0x06DD && c <= 0x06DF + || c >= 0x06E0 && c <= 0x06E4 + || c >= 0x06E7 && c <= 0x06E8 + || c >= 0x06EA && c <= 0x06ED + || c >= 0x0901 && c <= 0x0903 + || c == 0x093C + || c >= 0x093E && c <= 0x094C + || c == 0x094D + || c >= 0x0951 && c <= 0x0954 + || c >= 0x0962 && c <= 0x0963 + || c >= 0x0981 && c <= 0x0983 + || c == 0x09BC + || c == 0x09BE + || c == 0x09BF + || c >= 0x09C0 && c <= 0x09C4 + || c >= 0x09C7 && c <= 0x09C8 + || c >= 0x09CB && c <= 0x09CD + || c == 0x09D7 + || c >= 0x09E2 && c <= 0x09E3 + || c == 0x0A02 + || c == 0x0A3C + || c == 0x0A3E + || c == 0x0A3F + || c >= 0x0A40 && c <= 0x0A42 + || c >= 0x0A47 && c <= 0x0A48 + || c >= 0x0A4B && c <= 0x0A4D + || c >= 0x0A70 && c <= 0x0A71 + || c >= 0x0A81 && c <= 0x0A83 + || c == 0x0ABC + || c >= 0x0ABE && c <= 0x0AC5 + || c >= 0x0AC7 && c <= 0x0AC9 + || c >= 0x0ACB && c <= 0x0ACD + || c >= 0x0B01 && c <= 0x0B03 + || c == 0x0B3C + || c >= 0x0B3E && c <= 0x0B43 + || c >= 0x0B47 && c <= 0x0B48 + || c >= 0x0B4B && c <= 0x0B4D + || c >= 0x0B56 && c <= 0x0B57 + || c >= 0x0B82 && c <= 0x0B83 + || c >= 0x0BBE && c <= 0x0BC2 + || c >= 0x0BC6 && c <= 0x0BC8 + || c >= 0x0BCA && c <= 0x0BCD + || c == 0x0BD7 + || c >= 0x0C01 && c <= 0x0C03 + || c >= 0x0C3E && c <= 0x0C44 + || c >= 0x0C46 && c <= 0x0C48 + || c >= 0x0C4A && c <= 0x0C4D + || c >= 0x0C55 && c <= 0x0C56 + || c >= 0x0C82 && c <= 0x0C83 + || c >= 0x0CBE && c <= 0x0CC4 + || c >= 0x0CC6 && c <= 0x0CC8 + || c >= 0x0CCA && c <= 0x0CCD + || c >= 0x0CD5 && c <= 0x0CD6 + || c >= 0x0D02 && c <= 0x0D03 + || c >= 0x0D3E && c <= 0x0D43 + || c >= 0x0D46 && c <= 0x0D48 + || c >= 0x0D4A && c <= 0x0D4D + || c == 0x0D57 + || c == 0x0E31 + || c >= 0x0E34 && c <= 0x0E3A + || c >= 0x0E47 && c <= 0x0E4E + || c == 0x0EB1 + || c >= 0x0EB4 && c <= 0x0EB9 + || c >= 0x0EBB && c <= 0x0EBC + || c >= 0x0EC8 && c <= 0x0ECD + || c >= 0x0F18 && c <= 0x0F19 + || c == 0x0F35 + || c == 0x0F37 + || c == 0x0F39 + || c == 0x0F3E + || c == 0x0F3F + || c >= 0x0F71 && c <= 0x0F84 + || c >= 0x0F86 && c <= 0x0F8B + || c >= 0x0F90 && c <= 0x0F95 + || c == 0x0F97 + || c >= 0x0F99 && c <= 0x0FAD + || c >= 0x0FB1 && c <= 0x0FB7 + || c == 0x0FB9 + || c >= 0x20D0 && c <= 0x20DC + || c == 0x20E1 + || c >= 0x302A && c <= 0x302F + || c == 0x3099 + || c == 0x309A + || c == 0x00B7 + || c == 0x02D0 + || c == 0x02D1 + || c == 0x0387 + || c == 0x0640 + || c == 0x0E46 + || c == 0x0EC6 + || c == 0x3005 + || c >= 0x3031 && c <= 0x3035 + || c >= 0x309D && c <= 0x309E + || c >= 0x30FC && c <= 0x30FE; + }; + + Utilities.coalesceText = function (n) { + for (var m = n.firstChild; m != null; m = m.nextSibling) { + if (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE) { + var s = m.nodeValue; + var first = m; + m = m.nextSibling; + while (m != null && (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE)) { + s += m.nodeValue; + var del = m; + m = m.nextSibling; + del.parentNode.removeChild(del); + } + if (first.nodeType == NodeTypes.CDATA_SECTION_NODE) { + var p = first.parentNode; + if (first.nextSibling == null) { + p.removeChild(first); + p.appendChild(p.ownerDocument.createTextNode(s)); + } else { + var next = first.nextSibling; + p.removeChild(first); + p.insertBefore(p.ownerDocument.createTextNode(s), next); + } + } else { + first.nodeValue = s; + } + if (m == null) { + break; + } + } else if (m.nodeType == NodeTypes.ELEMENT_NODE) { + Utilities.coalesceText(m); + } + } + }; + + Utilities.instance_of = function (o, c) { + while (o != null) { + if (o.constructor === c) { + return true; + } + if (o === Object) { + return false; + } + o = o.constructor.superclass; + } + return false; + }; + + Utilities.getElementById = function (n, id) { + // Note that this does not check the DTD to check for actual + // attributes of type ID, so this may be a bit wrong. + if (n.nodeType == NodeTypes.ELEMENT_NODE) { + if (n.getAttribute("id") == id + || n.getAttributeNS(null, "id") == id) { + return n; + } + } + for (var m = n.firstChild; m != null; m = m.nextSibling) { + var res = Utilities.getElementById(m, id); + if (res != null) { + return res; + } + } + return null; + }; + + // XPathException //////////////////////////////////////////////////////////// + + var XPathException = (function () { + function getMessage(code, exception) { + var msg = exception ? ": " + exception.toString() : ""; + switch (code) { + case XPathException.INVALID_EXPRESSION_ERR: + return "Invalid expression" + msg; + case XPathException.TYPE_ERR: + return "Type error" + msg; + } + return null; + } + + function XPathException(code, error, message) { + var err = Error.call(this, getMessage(code, error) || message); + + err.code = code; + err.exception = error; + + return err; + } + + XPathException.prototype = Object.create(Error.prototype); + XPathException.prototype.constructor = XPathException; + XPathException.superclass = Error; + + XPathException.prototype.toString = function () { + return this.message; + }; + + XPathException.fromMessage = function (message, error) { + return new XPathException(null, error, message); + }; + + XPathException.INVALID_EXPRESSION_ERR = 51; + XPathException.TYPE_ERR = 52; + + return XPathException; + })(); + + // XPathExpression /////////////////////////////////////////////////////////// + + XPathExpression.prototype = {}; + XPathExpression.prototype.constructor = XPathExpression; + XPathExpression.superclass = Object.prototype; + + function XPathExpression(e, r, p) { + this.xpath = p.parse(e); + this.context = new XPathContext(); + this.context.namespaceResolver = new XPathNSResolverWrapper(r); + } + + XPathExpression.getOwnerDocument = function (n) { + return n.nodeType === NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument; + }; + + XPathExpression.detectHtmlDom = function (n) { + if (!n) { return false; } + + var doc = XPathExpression.getOwnerDocument(n); + + try { + return doc.implementation.hasFeature("HTML", "2.0"); + } catch (e) { + return true; + } + }; + + XPathExpression.prototype.evaluate = function (n, t, res) { + this.context.expressionContextNode = n; + // backward compatibility - no reliable way to detect whether the DOM is HTML, but + // this library has been using this method up until now, so we will continue to use it + // ONLY when using an XPathExpression + this.context.caseInsensitive = XPathExpression.detectHtmlDom(n); + + var result = this.xpath.evaluate(this.context); + + return new XPathResult(result, t); + }; + + // XPathNSResolverWrapper //////////////////////////////////////////////////// + + XPathNSResolverWrapper.prototype = {}; + XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper; + XPathNSResolverWrapper.superclass = Object.prototype; + + function XPathNSResolverWrapper(r) { + this.xpathNSResolver = r; + } + + XPathNSResolverWrapper.prototype.getNamespace = function (prefix, n) { + if (this.xpathNSResolver == null) { + return null; + } + return this.xpathNSResolver.lookupNamespaceURI(prefix); + }; + + // NodeXPathNSResolver /////////////////////////////////////////////////////// + + NodeXPathNSResolver.prototype = {}; + NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver; + NodeXPathNSResolver.superclass = Object.prototype; + + function NodeXPathNSResolver(n) { + this.node = n; + this.namespaceResolver = new NamespaceResolver(); + } + + NodeXPathNSResolver.prototype.lookupNamespaceURI = function (prefix) { + return this.namespaceResolver.getNamespace(prefix, this.node); + }; + + // XPathResult /////////////////////////////////////////////////////////////// + + XPathResult.prototype = {}; + XPathResult.prototype.constructor = XPathResult; + XPathResult.superclass = Object.prototype; + + function XPathResult(v, t) { + if (t == XPathResult.ANY_TYPE) { + if (v.constructor === XString) { + t = XPathResult.STRING_TYPE; + } else if (v.constructor === XNumber) { + t = XPathResult.NUMBER_TYPE; + } else if (v.constructor === XBoolean) { + t = XPathResult.BOOLEAN_TYPE; + } else if (v.constructor === XNodeSet) { + t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE; + } + } + this.resultType = t; + switch (t) { + case XPathResult.NUMBER_TYPE: + this.numberValue = v.numberValue(); + return; + case XPathResult.STRING_TYPE: + this.stringValue = v.stringValue(); + return; + case XPathResult.BOOLEAN_TYPE: + this.booleanValue = v.booleanValue(); + return; + case XPathResult.ANY_UNORDERED_NODE_TYPE: + case XPathResult.FIRST_ORDERED_NODE_TYPE: + if (v.constructor === XNodeSet) { + this.singleNodeValue = v.first(); + return; + } + break; + case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: + case XPathResult.ORDERED_NODE_ITERATOR_TYPE: + if (v.constructor === XNodeSet) { + this.invalidIteratorState = false; + this.nodes = v.toArray(); + this.iteratorIndex = 0; + return; + } + break; + case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE: + case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE: + if (v.constructor === XNodeSet) { + this.nodes = v.toArray(); + this.snapshotLength = this.nodes.length; + return; + } + break; + } + throw new XPathException(XPathException.TYPE_ERR); + } + XPathResult.prototype.iterateNext = function () { + if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE + && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) { + throw new XPathException(XPathException.TYPE_ERR); + } + return this.nodes[this.iteratorIndex++]; + }; + + XPathResult.prototype.snapshotItem = function (i) { + if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE + && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { + throw new XPathException(XPathException.TYPE_ERR); + } + return this.nodes[i]; + }; + + XPathResult.ANY_TYPE = 0; + XPathResult.NUMBER_TYPE = 1; + XPathResult.STRING_TYPE = 2; + XPathResult.BOOLEAN_TYPE = 3; + XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; + XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; + XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; + XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; + XPathResult.ANY_UNORDERED_NODE_TYPE = 8; + XPathResult.FIRST_ORDERED_NODE_TYPE = 9; + + // DOM 3 XPath support /////////////////////////////////////////////////////// + + function installDOM3XPathSupport(doc, p) { + doc.createExpression = function (e, r) { + try { + return new XPathExpression(e, r, p); + } catch (e) { + throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e); + } + }; + doc.createNSResolver = function (n) { + return new NodeXPathNSResolver(n); + }; + doc.evaluate = function (e, cn, r, t, res) { + if (t < 0 || t > 9) { + throw { code: 0, toString: function () { return "Request type not supported"; } }; + } + return doc.createExpression(e, r, p).evaluate(cn, t, res); + }; + } + // --------------------------------------------------------------------------- + + // Install DOM 3 XPath support for the current document. + try { + var shouldInstall = true; + try { + if (document.implementation + && document.implementation.hasFeature + && document.implementation.hasFeature("XPath", null)) { + shouldInstall = false; + } + } catch (e) { + } + if (shouldInstall) { + installDOM3XPathSupport(document, new XPathParser()); + } + } catch (e) { + } + + // --------------------------------------------------------------------------- + // exports for node.js + + installDOM3XPathSupport(exports, new XPathParser()); + + (function () { + var parser = new XPathParser(); + + var defaultNSResolver = new NamespaceResolver(); + var defaultFunctionResolver = new FunctionResolver(); + var defaultVariableResolver = new VariableResolver(); + + function makeNSResolverFromFunction(func) { + return { + getNamespace: function (prefix, node) { + var ns = func(prefix, node); + + return ns || defaultNSResolver.getNamespace(prefix, node); + } + }; + } + + function makeNSResolverFromObject(obj) { + return makeNSResolverFromFunction(obj.getNamespace.bind(obj)); + } + + function makeNSResolverFromMap(map) { + return makeNSResolverFromFunction(function (prefix) { + return map[prefix]; + }); + } + + function makeNSResolver(resolver) { + if (resolver && typeof resolver.getNamespace === "function") { + return makeNSResolverFromObject(resolver); + } + + if (typeof resolver === "function") { + return makeNSResolverFromFunction(resolver); + } + + // assume prefix -> uri mapping + if (typeof resolver === "object") { + return makeNSResolverFromMap(resolver); + } + + return defaultNSResolver; + } + + /** Converts native JavaScript types to their XPath library equivalent */ + function convertValue(value) { + if (value === null || + typeof value === "undefined" || + value instanceof XString || + value instanceof XBoolean || + value instanceof XNumber || + value instanceof XNodeSet) { + return value; + } + + switch (typeof value) { + case "string": return new XString(value); + case "boolean": return new XBoolean(value); + case "number": return new XNumber(value); + } + + // assume node(s) + var ns = new XNodeSet(); + ns.addArray([].concat(value)); + return ns; + } + + function makeEvaluator(func) { + return function (context) { + var args = Array.prototype.slice.call(arguments, 1).map(function (arg) { + return arg.evaluate(context); + }); + var result = func.apply(this, [].concat(context, args)); + return convertValue(result); + }; + } + + function makeFunctionResolverFromFunction(func) { + return { + getFunction: function (name, namespace) { + var found = func(name, namespace); + if (found) { + return makeEvaluator(found); + } + return defaultFunctionResolver.getFunction(name, namespace); + } + }; + } + + function makeFunctionResolverFromObject(obj) { + return makeFunctionResolverFromFunction(obj.getFunction.bind(obj)); + } + + function makeFunctionResolverFromMap(map) { + return makeFunctionResolverFromFunction(function (name) { + return map[name]; + }); + } + + function makeFunctionResolver(resolver) { + if (resolver && typeof resolver.getFunction === "function") { + return makeFunctionResolverFromObject(resolver); + } + + if (typeof resolver === "function") { + return makeFunctionResolverFromFunction(resolver); + } + + // assume map + if (typeof resolver === "object") { + return makeFunctionResolverFromMap(resolver); + } + + return defaultFunctionResolver; + } + + function makeVariableResolverFromFunction(func) { + return { + getVariable: function (name, namespace) { + var value = func(name, namespace); + return convertValue(value); + } + }; + } + + function makeVariableResolver(resolver) { + if (resolver) { + if (typeof resolver.getVariable === "function") { + return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver)); + } + + if (typeof resolver === "function") { + return makeVariableResolverFromFunction(resolver); + } + + // assume map + if (typeof resolver === "object") { + return makeVariableResolverFromFunction(function (name) { + return resolver[name]; + }); + } + } + + return defaultVariableResolver; + } + + function copyIfPresent(prop, dest, source) { + if (prop in source) { dest[prop] = source[prop]; } + } + + function makeContext(options) { + var context = new XPathContext(); + + if (options) { + context.namespaceResolver = makeNSResolver(options.namespaces); + context.functionResolver = makeFunctionResolver(options.functions); + context.variableResolver = makeVariableResolver(options.variables); + context.expressionContextNode = options.node; + copyIfPresent('allowAnyNamespaceForNoPrefix', context, options); + copyIfPresent('isHtml', context, options); + } else { + context.namespaceResolver = defaultNSResolver; + } + + return context; + } + + function evaluate(parsedExpression, options) { + var context = makeContext(options); + + return parsedExpression.evaluate(context); + } + + var evaluatorPrototype = { + evaluate: function (options) { + return evaluate(this.expression, options); + } + + , evaluateNumber: function (options) { + return this.evaluate(options).numberValue(); + } + + , evaluateString: function (options) { + return this.evaluate(options).stringValue(); + } + + , evaluateBoolean: function (options) { + return this.evaluate(options).booleanValue(); + } + + , evaluateNodeSet: function (options) { + return this.evaluate(options).nodeset(); + } + + , select: function (options) { + return this.evaluateNodeSet(options).toArray() + } + + , select1: function (options) { + return this.select(options)[0]; + } + }; + + function parse(xpath) { + var parsed = parser.parse(xpath); + + return Object.create(evaluatorPrototype, { + expression: { + value: parsed + } + }); + } + + exports.parse = parse; + })(); + + assign( + exports, + { + XPath: XPath, + XPathParser: XPathParser, + XPathResult: XPathResult, + + Step: Step, + PathExpr: PathExpr, + NodeTest: NodeTest, + LocationPath: LocationPath, + + OrOperation: OrOperation, + AndOperation: AndOperation, + + BarOperation: BarOperation, + + EqualsOperation: EqualsOperation, + NotEqualOperation: NotEqualOperation, + LessThanOperation: LessThanOperation, + GreaterThanOperation: GreaterThanOperation, + LessThanOrEqualOperation: LessThanOrEqualOperation, + GreaterThanOrEqualOperation: GreaterThanOrEqualOperation, + + PlusOperation: PlusOperation, + MinusOperation: MinusOperation, + MultiplyOperation: MultiplyOperation, + DivOperation: DivOperation, + ModOperation: ModOperation, + UnaryMinusOperation: UnaryMinusOperation, + + FunctionCall: FunctionCall, + VariableReference: VariableReference, + + XPathContext: XPathContext, + + XNodeSet: XNodeSet, + XBoolean: XBoolean, + XString: XString, + XNumber: XNumber, + + NamespaceResolver: NamespaceResolver, + FunctionResolver: FunctionResolver, + VariableResolver: VariableResolver, + + Utilities: Utilities, + } + ); + + // helper + exports.select = function (e, doc, single) { + return exports.selectWithResolver(e, doc, null, single); + }; + + exports.useNamespaces = function (mappings) { + var resolver = { + mappings: mappings || {}, + lookupNamespaceURI: function (prefix) { + return this.mappings[prefix]; + } + }; + + return function (e, doc, single) { + return exports.selectWithResolver(e, doc, resolver, single); + }; + }; + + exports.selectWithResolver = function (e, doc, resolver, single) { + var expression = new XPathExpression(e, resolver, new XPathParser()); + var type = XPathResult.ANY_TYPE; + + var result = expression.evaluate(doc, type, null); + + if (result.resultType == XPathResult.STRING_TYPE) { + result = result.stringValue; + } + else if (result.resultType == XPathResult.NUMBER_TYPE) { + result = result.numberValue; + } + else if (result.resultType == XPathResult.BOOLEAN_TYPE) { + result = result.booleanValue; + } + else { + result = result.nodes; + if (single) { + result = result[0]; + } + } + + return result; + }; + + exports.select1 = function (e, doc) { + return exports.select(e, doc, true); + }; + + var isArrayOfNodes = function (value) { + return Array.isArray(value) && value.every(isNodeLike); + }; + + var isNodeOfType = function (type) { + return function (value) { + return isNodeLike(value) && value.nodeType === type; + }; + }; + + assign( + exports, + { + isNodeLike: isNodeLike, + isArrayOfNodes: isArrayOfNodes, + isElement: isNodeOfType(NodeTypes.ELEMENT_NODE), + isAttribute: isNodeOfType(NodeTypes.ATTRIBUTE_NODE), + isTextNode: isNodeOfType(NodeTypes.TEXT_NODE), + isCDATASection: isNodeOfType(NodeTypes.CDATA_SECTION_NODE), + isProcessingInstruction: isNodeOfType(NodeTypes.PROCESSING_INSTRUCTION_NODE), + isComment: isNodeOfType(NodeTypes.COMMENT_NODE), + isDocumentNode: isNodeOfType(NodeTypes.DOCUMENT_NODE), + isDocumentTypeNode: isNodeOfType(NodeTypes.DOCUMENT_TYPE_NODE), + isDocumentFragment: isNodeOfType(NodeTypes.DOCUMENT_FRAGMENT_NODE), + } + ); + // end non-node wrapper + })(xpath); + } (xpath)); + return xpath; +} + +var lib = {}; + +var dom = {}; + +var conventions = {}; + +var hasRequiredConventions; + +function requireConventions () { + if (hasRequiredConventions) return conventions; + hasRequiredConventions = 1; + + /** + * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes. + * + * Works with anything that has a `length` property and index access properties, including NodeList. + * + * @template {unknown} T + * @param {Array | ({length:number, [number]: T})} list + * @param {function (item: T, index: number, list:Array | ({length:number, [number]: T})):boolean} predicate + * @param {Partial>?} ac `Array.prototype` by default, + * allows injecting a custom implementation in tests + * @returns {T | undefined} + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find + * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find + */ + function find(list, predicate, ac) { + if (ac === undefined) { + ac = Array.prototype; + } + if (list && typeof ac.find === 'function') { + return ac.find.call(list, predicate); + } + for (var i = 0; i < list.length; i++) { + if (Object.prototype.hasOwnProperty.call(list, i)) { + var item = list[i]; + if (predicate.call(undefined, item, i, list)) { + return item; + } + } + } + } + + /** + * "Shallow freezes" an object to render it immutable. + * Uses `Object.freeze` if available, + * otherwise the immutability is only in the type. + * + * Is used to create "enum like" objects. + * + * @template T + * @param {T} object the object to freeze + * @param {Pick = Object} oc `Object` by default, + * allows to inject custom object constructor for tests + * @returns {Readonly} + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze + */ + function freeze(object, oc) { + if (oc === undefined) { + oc = Object; + } + return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object + } + + /** + * Since we can not rely on `Object.assign` we provide a simplified version + * that is sufficient for our needs. + * + * @param {Object} target + * @param {Object | null | undefined} source + * + * @returns {Object} target + * @throws TypeError if target is not an object + * + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign + */ + function assign(target, source) { + if (target === null || typeof target !== 'object') { + throw new TypeError('target is not an object') + } + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + return target + } + + /** + * All mime types that are allowed as input to `DOMParser.parseFromString` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec + * @see DOMParser.prototype.parseFromString + */ + var MIME_TYPE = freeze({ + /** + * `text/html`, the only mime type that triggers treating an XML document as HTML. + * + * @see DOMParser.SupportedType.isHTML + * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration + * @see https://en.wikipedia.org/wiki/HTML Wikipedia + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec + */ + HTML: 'text/html', + + /** + * Helper method to check a mime type if it indicates an HTML document + * + * @param {string} [value] + * @returns {boolean} + * + * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration + * @see https://en.wikipedia.org/wiki/HTML Wikipedia + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN + * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ + isHTML: function (value) { + return value === MIME_TYPE.HTML + }, + + /** + * `application/xml`, the standard mime type for XML documents. + * + * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration + * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 + * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia + */ + XML_APPLICATION: 'application/xml', + + /** + * `text/html`, an alias for `application/xml`. + * + * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 + * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration + * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia + */ + XML_TEXT: 'text/xml', + + /** + * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, + * but is parsed as an XML document. + * + * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec + * @see https://en.wikipedia.org/wiki/XHTML Wikipedia + */ + XML_XHTML_APPLICATION: 'application/xhtml+xml', + + /** + * `image/svg+xml`, + * + * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration + * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 + * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia + */ + XML_SVG_IMAGE: 'image/svg+xml', + }); + + /** + * Namespaces that are used in this code base. + * + * @see http://www.w3.org/TR/REC-xml-names + */ + var NAMESPACE = freeze({ + /** + * The XHTML namespace. + * + * @see http://www.w3.org/1999/xhtml + */ + HTML: 'http://www.w3.org/1999/xhtml', + + /** + * Checks if `uri` equals `NAMESPACE.HTML`. + * + * @param {string} [uri] + * + * @see NAMESPACE.HTML + */ + isHTML: function (uri) { + return uri === NAMESPACE.HTML + }, + + /** + * The SVG namespace. + * + * @see http://www.w3.org/2000/svg + */ + SVG: 'http://www.w3.org/2000/svg', + + /** + * The `xml:` namespace. + * + * @see http://www.w3.org/XML/1998/namespace + */ + XML: 'http://www.w3.org/XML/1998/namespace', + + /** + * The `xmlns:` namespace + * + * @see https://www.w3.org/2000/xmlns/ + */ + XMLNS: 'http://www.w3.org/2000/xmlns/', + }); + + conventions.assign = assign; + conventions.find = find; + conventions.freeze = freeze; + conventions.MIME_TYPE = MIME_TYPE; + conventions.NAMESPACE = NAMESPACE; + return conventions; +} + +var hasRequiredDom; + +function requireDom () { + if (hasRequiredDom) return dom; + hasRequiredDom = 1; + var conventions = requireConventions(); + + var find = conventions.find; + var NAMESPACE = conventions.NAMESPACE; + + /** + * A prerequisite for `[].filter`, to drop elements that are empty + * @param {string} input + * @returns {boolean} + */ + function notEmptyString (input) { + return input !== '' + } + /** + * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * + * @param {string} input + * @returns {string[]} (can be empty) + */ + function splitOnASCIIWhitespace(input) { + // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE + return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [] + } + + /** + * Adds element as a key to current if it is not already present. + * + * @param {Record} current + * @param {string} element + * @returns {Record} + */ + function orderedSetReducer (current, element) { + if (!current.hasOwnProperty(element)) { + current[element] = true; + } + return current; + } + + /** + * @see https://infra.spec.whatwg.org/#ordered-set + * @param {string} input + * @returns {string[]} + */ + function toOrderedSet(input) { + if (!input) return []; + var list = splitOnASCIIWhitespace(input); + return Object.keys(list.reduce(orderedSetReducer, {})) + } + + /** + * Uses `list.indexOf` to implement something like `Array.prototype.includes`, + * which we can not rely on being available. + * + * @param {any[]} list + * @returns {function(any): boolean} + */ + function arrayIncludes (list) { + return function(element) { + return list && list.indexOf(element) !== -1; + } + } + + function copy(src,dest){ + for(var p in src){ + if (Object.prototype.hasOwnProperty.call(src, p)) { + dest[p] = src[p]; + } + } + } + + /** + ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? + ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? + */ + function _extends(Class,Super){ + var pt = Class.prototype; + if(!(pt instanceof Super)){ + function t(){} t.prototype = Super.prototype; + t = new t(); + copy(pt,t); + Class.prototype = pt = t; + } + if(pt.constructor != Class){ + if(typeof Class != 'function'){ + console.error("unknown Class:"+Class); + } + pt.constructor = Class; + } + } + + // Node Types + var NodeType = {}; + var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; + var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; + var TEXT_NODE = NodeType.TEXT_NODE = 3; + var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; + var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; + var ENTITY_NODE = NodeType.ENTITY_NODE = 6; + var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; + var COMMENT_NODE = NodeType.COMMENT_NODE = 8; + var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; + var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; + var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; + var NOTATION_NODE = NodeType.NOTATION_NODE = 12; + + // ExceptionCode + var ExceptionCode = {}; + var ExceptionMessage = {}; + ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); + ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); + var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); + ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); + var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); + ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); + ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); + var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); + ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); + var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); + //level2 + var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); + ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); + ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); + ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); + ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); + + /** + * DOM Level 2 + * Object DOMException + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html + * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html + */ + function DOMException(code, message) { + if(message instanceof Error){ + var error = message; + }else { + error = this; + Error.call(this, ExceptionMessage[code]); + this.message = ExceptionMessage[code]; + if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); + } + error.code = code; + if(message) this.message = this.message + ": " + message; + return error; + } DOMException.prototype = Error.prototype; + copy(ExceptionCode,DOMException); + + /** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 + * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. + * The items in the NodeList are accessible via an integral index, starting from 0. + */ + function NodeList() { + } NodeList.prototype = { + /** + * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. + * @standard level1 + */ + length:0, + /** + * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. + * @standard level1 + * @param index unsigned long + * Index into the collection. + * @return Node + * The node at the indexth position in the NodeList, or null if that is not a valid index. + */ + item: function(index) { + return index >= 0 && index < this.length ? this[index] : null; + }, + toString:function(isHTML,nodeFilter,options){ + var requireWellFormed = !!options && !!options.requireWellFormed; + for(var buf = [], i = 0;i=0){ + var lastIndex = list.length-1; + while(i0 || key == 'xmlns'){ + // return null; + // } + //console.log() + var i = this.length; + while(i--){ + var attr = this[i]; + //console.log(attr.nodeName,key) + if(attr.nodeName == key){ + return attr; + } + } + }, + setNamedItem: function(attr) { + var el = attr.ownerElement; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + var oldAttr = this.getNamedItem(attr.nodeName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; + }, + /* returns Node */ + setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR + var el = attr.ownerElement, oldAttr; + if(el && el!=this._ownerElement){ + throw new DOMException(INUSE_ATTRIBUTE_ERR); + } + oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); + _addNamedNode(this._ownerElement,this,attr,oldAttr); + return oldAttr; + }, + + /* returns Node */ + removeNamedItem: function(key) { + var attr = this.getNamedItem(key); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + + + },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR + + //for level2 + removeNamedItemNS:function(namespaceURI,localName){ + var attr = this.getNamedItemNS(namespaceURI,localName); + _removeNamedNode(this._ownerElement,this,attr); + return attr; + }, + getNamedItemNS: function(namespaceURI, localName) { + var i = this.length; + while(i--){ + var node = this[i]; + if(node.localName == localName && node.namespaceURI == namespaceURI){ + return node; + } + } + return null; + } + }; + + /** + * The DOMImplementation interface represents an object providing methods + * which are not dependent on any particular document. + * Such an object is returned by the `Document.implementation` property. + * + * __The individual methods describe the differences compared to the specs.__ + * + * @constructor + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN + * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial) + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core + * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core + * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard + */ + function DOMImplementation() { + } + + DOMImplementation.prototype = { + /** + * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported. + * The different implementations fairly diverged in what kind of features were reported. + * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use. + * + * @deprecated It is deprecated and modern browsers return true in all cases. + * + * @param {string} feature + * @param {string} [version] + * @returns {boolean} always true + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN + * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core + * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard + */ + hasFeature: function(feature, version) { + return true; + }, + /** + * Creates an XML Document object of the specified type with its document element. + * + * __It behaves slightly different from the description in the living standard__: + * - There is no interface/class `XMLDocument`, it returns a `Document` instance. + * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared. + * - this implementation is not validating names or qualified names + * (when parsing XML strings, the SAX parser takes care of that) + * + * @param {string|null} namespaceURI + * @param {string} qualifiedName + * @param {DocumentType=null} doctype + * @returns {Document} + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial) + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core + * + * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract + * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names + * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names + */ + createDocument: function(namespaceURI, qualifiedName, doctype){ + var doc = new Document(); + doc.implementation = this; + doc.childNodes = new NodeList(); + doc.doctype = doctype || null; + if (doctype){ + doc.appendChild(doctype); + } + if (qualifiedName){ + var root = doc.createElementNS(namespaceURI, qualifiedName); + doc.appendChild(root); + } + return doc; + }, + /** + * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`. + * + * __This implementation differs from the specification:__ + * - this implementation is not validating names or qualified names + * (when parsing XML strings, the SAX parser takes care of that) + * + * Note: `internalSubset` can only be introduced via a direct property write to `node.internalSubset` after creation. + * Creation-time validation of `publicId`, `systemId` is not enforced. + * The serializer-level check covers all mutation vectors, including direct property writes. + * `internalSubset` is only serialized as `[ ... ]` when both `publicId` and `systemId` are + * absent (empty or `'.'`) — if either external identifier is present, `internalSubset` is + * silently omitted from the serialized output. + * + * @param {string} qualifiedName + * @param {string} [publicId] + * The external subset public identifier. Stored verbatim including surrounding quotes. + * When serialized with `requireWellFormed: true` (via the 4th-parameter options object), + * throws `DOMException` with code `INVALID_STATE_ERR` if the value is non-empty and does + * not match the XML `PubidLiteral` production (W3C DOM Parsing §3.2.1.3; XML 1.0 [12]). + * @param {string} [systemId] + * The external subset system identifier. Stored verbatim including surrounding quotes. + * When serialized with `requireWellFormed: true`, throws `DOMException` with code + * `INVALID_STATE_ERR` if the value is non-empty and does not match the XML `SystemLiteral` + * production (W3C DOM Parsing §3.2.1.3; XML 1.0 [11]). + * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation + * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()` + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN + * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core + * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard + * + * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract + * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names + * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names + */ + createDocumentType: function(qualifiedName, publicId, systemId){ + var node = new DocumentType(); + node.name = qualifiedName; + node.nodeName = qualifiedName; + node.publicId = publicId || ''; + node.systemId = systemId || ''; + + return node; + } + }; + + + /** + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 + */ + + function Node() { + } + Node.prototype = { + firstChild : null, + lastChild : null, + previousSibling : null, + nextSibling : null, + attributes : null, + parentNode : null, + childNodes : null, + ownerDocument : null, + nodeValue : null, + namespaceURI : null, + prefix : null, + localName : null, + // Modified in DOM Level 2: + insertBefore:function(newChild, refChild){//raises + return _insertBefore(this,newChild,refChild); + }, + replaceChild:function(newChild, oldChild){//raises + _insertBefore(this, newChild,oldChild, assertPreReplacementValidityInDocument); + if(oldChild){ + this.removeChild(oldChild); + } + }, + removeChild:function(oldChild){ + return _removeChild(this,oldChild); + }, + appendChild:function(newChild){ + return this.insertBefore(newChild,null); + }, + hasChildNodes:function(){ + return this.firstChild != null; + }, + cloneNode:function(deep){ + return cloneNode(this.ownerDocument||this,this,deep); + }, + // Modified in DOM Level 2: + /** + * Puts the specified node and all of its subtree into a "normalized" form. In a normalized + * subtree, no text nodes in the subtree are empty and there are no adjacent text nodes. + * + * Specifically, this method merges any adjacent text nodes (i.e., nodes for which `nodeType` + * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text + * nodes. + * + * This method iteratively traverses all child nodes to normalize all descendant nodes within + * the subtree. + * + * @throws {DOMException} + * May throw a DOMException if operations within removeChild or appendData (which are + * potentially invoked in this method) do not meet their specific constraints. + * @see {@link Node.removeChild} + * @see {@link CharacterData.appendData} + * @see ../docs/walk-dom.md. + */ + normalize: function () { + walkDOM(this, null, { + enter: function (node) { + // Merge adjacent text children of node before walkDOM schedules them. + // walkDOM reads lastChild/previousSibling after enter returns, so the + // surviving post-merge children are what it descends into. + var child = node.firstChild; + while (child) { + var next = child.nextSibling; + if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) { + node.removeChild(next); + child.appendData(next.data); + // Do not advance child: re-check new nextSibling for another text run + } else { + child = next; + } + } + return true; // descend into surviving children + }, + }); + }, + // Introduced in DOM Level 2: + isSupported:function(feature, version){ + return this.ownerDocument.implementation.hasFeature(feature,version); + }, + // Introduced in DOM Level 2: + hasAttributes:function(){ + return this.attributes.length>0; + }, + /** + * Look up the prefix associated to the given namespace URI, starting from this node. + * **The default namespace declarations are ignored by this method.** + * See Namespace Prefix Lookup for details on the algorithm used by this method. + * + * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._ + * + * @param {string | null} namespaceURI + * @returns {string | null} + * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix + * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo + * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix + * @see https://github.com/xmldom/xmldom/issues/322 + */ + lookupPrefix:function(namespaceURI){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + for(var n in map){ + if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) { + return n; + } + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + lookupNamespaceURI:function(prefix){ + var el = this; + while(el){ + var map = el._nsMap; + //console.dir(map) + if(map){ + if(Object.prototype.hasOwnProperty.call(map, prefix)){ + return map[prefix] ; + } + } + el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; + } + return null; + }, + // Introduced in DOM Level 3: + isDefaultNamespace:function(namespaceURI){ + var prefix = this.lookupPrefix(namespaceURI); + return prefix == null; + } + }; + + + function _xmlEncoder(c){ + return c == '<' && '<' || + c == '>' && '>' || + c == '&' && '&' || + c == '"' && '"' || + '&#'+c.charCodeAt()+';' + } + + + copy(NodeType,Node); + copy(NodeType,Node.prototype); + + /** + * @param {Node} node + * Root of the subtree to visit. + * @param {function(Node): boolean} callback + * Called for each node in depth-first pre-order. Return a truthy value to stop traversal early. + * @return {boolean} `true` if traversal was aborted by the callback, `false` otherwise. + */ + function _visitNode(node, callback) { + return walkDOM(node, null, { enter: function (n) { return callback(n) ? walkDOM.STOP : true; } }) === walkDOM.STOP; + } + + /** + * Depth-first pre/post-order DOM tree walker. + * + * Visits every node in the subtree rooted at `node`. For each node: + * + * 1. Calls `callbacks.enter(node, context)` before descending into the node's children. The + * return value becomes the `context` passed to each child's `enter` call and to the matching + * `exit` call. + * 2. If `enter` returns `null` or `undefined`, the node's children are skipped; + * sibling traversal continues normally. + * 3. If `enter` returns `walkDOM.STOP`, the entire traversal is aborted immediately — no + * further `enter` or `exit` calls are made. + * 4. `lastChild` and `previousSibling` are read **after** `enter` returns, so `enter` may + * safely modify the node's own child list before the walker descends. Modifying siblings of + * the current node or any other part of the tree produces unpredictable results: nodes already + * queued on the stack are visited regardless of DOM changes, and newly inserted nodes outside + * the current child list are never visited. + * 5. Calls `callbacks.exit(node, context)` (if provided) after all of a node's children have + * been visited, passing the same `context` that `enter` + * returned for that node. + * + * This implementation uses an explicit stack and does not recurse — it is safe on arbitrarily + * deep trees. + * + * @param {Node} node + * Root of the subtree to walk. + * @param {*} context + * Initial context value passed to the root node's `enter`. + * @param {{ enter: function(Node, *): *, exit?: function(Node, *): void }} callbacks + * @returns {void | walkDOM.STOP} + * @see ../docs/walk-dom.md. + */ + function walkDOM(node, context, callbacks) { + // Each stack frame is {node, context, phase}: + // walkDOM.ENTER — call enter, then push children + // walkDOM.EXIT — call exit + var stack = [{ node: node, context: context, phase: walkDOM.ENTER }]; + while (stack.length > 0) { + var frame = stack.pop(); + if (frame.phase === walkDOM.ENTER) { + var childContext = callbacks.enter(frame.node, frame.context); + if (childContext === walkDOM.STOP) { + return walkDOM.STOP; + } + // Push exit frame before children so it fires after all children are processed (Last In First Out) + stack.push({ node: frame.node, context: childContext, phase: walkDOM.EXIT }); + if (childContext === null || childContext === undefined) { + continue; // skip children + } + // lastChild is read after enter returns, so enter may modify the child list. + var child = frame.node.lastChild; + // Traverse from lastChild backwards so that pushing onto the stack + // naturally yields firstChild on top (processed first). + while (child) { + stack.push({ node: child, context: childContext, phase: walkDOM.ENTER }); + child = child.previousSibling; + } + } else { + // frame.phase === walkDOM.EXIT + if (callbacks.exit) { + callbacks.exit(frame.node, frame.context); + } + } + } + } + + /** + * Sentinel value returned from a `walkDOM` `enter` callback to abort the entire traversal + * immediately. + * + * @type {symbol} + */ + walkDOM.STOP = Symbol('walkDOM.STOP'); + /** + * Phase constant for a stack frame that has not yet been visited. + * The `enter` callback is called and children are scheduled. + * + * @type {number} + */ + walkDOM.ENTER = 0; + /** + * Phase constant for a stack frame whose subtree has been fully visited. + * The `exit` callback is called. + * + * @type {number} + */ + walkDOM.EXIT = 1; + + function Document(){ + this.ownerDocument = this; + } + + function _onAddAttribute(doc,el,newAttr){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns === NAMESPACE.XMLNS){ + //update namespace + el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value; + } + } + + function _onRemoveAttribute(doc,el,newAttr,remove){ + doc && doc._inc++; + var ns = newAttr.namespaceURI ; + if(ns === NAMESPACE.XMLNS){ + //update namespace + delete el._nsMap[newAttr.prefix?newAttr.localName:'']; + } + } + + /** + * Updates `el.childNodes`, updating the indexed items and it's `length`. + * Passing `newChild` means it will be appended. + * Otherwise it's assumed that an item has been removed, + * and `el.firstNode` and it's `.nextSibling` are used + * to walk the current list of child nodes. + * + * @param {Document} doc + * @param {Node} el + * @param {Node} [newChild] + * @private + */ + function _onUpdateChild (doc, el, newChild) { + if(doc && doc._inc){ + doc._inc++; + //update childNodes + var cs = el.childNodes; + if (newChild) { + cs[cs.length++] = newChild; + } else { + var child = el.firstChild; + var i = 0; + while (child) { + cs[i++] = child; + child = child.nextSibling; + } + cs.length = i; + delete cs[cs.length]; + } + } + } + + /** + * Removes the connections between `parentNode` and `child` + * and any existing `child.previousSibling` or `child.nextSibling`. + * + * @see https://github.com/xmldom/xmldom/issues/135 + * @see https://github.com/xmldom/xmldom/issues/145 + * + * @param {Node} parentNode + * @param {Node} child + * @returns {Node} the child that was removed. + * @private + */ + function _removeChild (parentNode, child) { + var previous = child.previousSibling; + var next = child.nextSibling; + if (previous) { + previous.nextSibling = next; + } else { + parentNode.firstChild = next; + } + if (next) { + next.previousSibling = previous; + } else { + parentNode.lastChild = previous; + } + child.parentNode = null; + child.previousSibling = null; + child.nextSibling = null; + _onUpdateChild(parentNode.ownerDocument, parentNode); + return child; + } + + /** + * Returns `true` if `node` can be a parent for insertion. + * @param {Node} node + * @returns {boolean} + */ + function hasValidParentNodeType(node) { + return ( + node && + (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE) + ); + } + + /** + * Returns `true` if `node` can be inserted according to it's `nodeType`. + * @param {Node} node + * @returns {boolean} + */ + function hasInsertableNodeType(node) { + return ( + node && + (isElementNode(node) || + isTextNode(node) || + isDocTypeNode(node) || + node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || + node.nodeType === Node.COMMENT_NODE || + node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) + ); + } + + /** + * Returns true if `node` is a DOCTYPE node + * @param {Node} node + * @returns {boolean} + */ + function isDocTypeNode(node) { + return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; + } + + /** + * Returns true if the node is an element + * @param {Node} node + * @returns {boolean} + */ + function isElementNode(node) { + return node && node.nodeType === Node.ELEMENT_NODE; + } + /** + * Returns true if `node` is a text node + * @param {Node} node + * @returns {boolean} + */ + function isTextNode(node) { + return node && node.nodeType === Node.TEXT_NODE; + } + + /** + * Check if en element node can be inserted before `child`, or at the end if child is falsy, + * according to the presence and position of a doctype node on the same level. + * + * @param {Document} doc The document node + * @param {Node} child the node that would become the nextSibling if the element would be inserted + * @returns {boolean} `true` if an element can be inserted before child + * @private + * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ + function isElementInsertionPossible(doc, child) { + var parentChildNodes = doc.childNodes || []; + if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { + return false; + } + var docTypeNode = find(parentChildNodes, isDocTypeNode); + return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); + } + + /** + * Check if en element node can be inserted before `child`, or at the end if child is falsy, + * according to the presence and position of a doctype node on the same level. + * + * @param {Node} doc The document node + * @param {Node} child the node that would become the nextSibling if the element would be inserted + * @returns {boolean} `true` if an element can be inserted before child + * @private + * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ + function isElementReplacementPossible(doc, child) { + var parentChildNodes = doc.childNodes || []; + + function hasElementChildThatIsNotChild(node) { + return isElementNode(node) && node !== child; + } + + if (find(parentChildNodes, hasElementChildThatIsNotChild)) { + return false; + } + var docTypeNode = find(parentChildNodes, isDocTypeNode); + return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); + } + + /** + * @private + * Steps 1-5 of the checks before inserting and before replacing a child are the same. + * + * @param {Node} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node=} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ + function assertPreInsertionValidity1to5(parent, node, child) { + // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException. + if (!hasValidParentNodeType(parent)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType); + } + // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException. + // not implemented! + // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException. + if (child && child.parentNode !== parent) { + throw new DOMException(NOT_FOUND_ERR, 'child not in parent'); + } + if ( + // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. + !hasInsertableNodeType(node) || + // 5. If either `node` is a Text node and `parent` is a document, + // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 + // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) + // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. + (isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) + ) { + throw new DOMException( + HIERARCHY_REQUEST_ERR, + 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType + ); + } + } + + /** + * @private + * Step 6 of the checks before inserting and before replacing a child are different. + * + * @param {Document} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node | undefined} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ + function assertPreInsertionValidityInDocument(parent, node, child) { + var parentChildNodes = parent.childNodes || []; + var nodeChildNodes = node.childNodes || []; + + // DocumentFragment + if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + var nodeChildElements = nodeChildNodes.filter(isElementNode); + // If node has more than one element child or has a Text node child. + if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); + } + // Otherwise, if `node` has one element child and either `parent` has an element child, + // `child` is a doctype, or `child` is non-null and a doctype is following `child`. + if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); + } + } + // Element + if (isElementNode(node)) { + // `parent` has an element child, `child` is a doctype, + // or `child` is non-null and a doctype is following `child`. + if (!isElementInsertionPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); + } + } + // DocumentType + if (isDocTypeNode(node)) { + // `parent` has a doctype child, + if (find(parentChildNodes, isDocTypeNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); + } + var parentElementChild = find(parentChildNodes, isElementNode); + // `child` is non-null and an element is preceding `child`, + if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); + } + // or `child` is null and `parent` has an element child. + if (!child && parentElementChild) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present'); + } + } + } + + /** + * @private + * Step 6 of the checks before inserting and before replacing a child are different. + * + * @param {Document} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node | undefined} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + * @see https://dom.spec.whatwg.org/#concept-node-replace + */ + function assertPreReplacementValidityInDocument(parent, node, child) { + var parentChildNodes = parent.childNodes || []; + var nodeChildNodes = node.childNodes || []; + + // DocumentFragment + if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + var nodeChildElements = nodeChildNodes.filter(isElementNode); + // If `node` has more than one element child or has a Text node child. + if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); + } + // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`. + if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); + } + } + // Element + if (isElementNode(node)) { + // `parent` has an element child that is not `child` or a doctype is following `child`. + if (!isElementReplacementPossible(parent, child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); + } + } + // DocumentType + if (isDocTypeNode(node)) { + function hasDoctypeChildThatIsNotChild(node) { + return isDocTypeNode(node) && node !== child; + } + + // `parent` has a doctype child that is not `child`, + if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); + } + var parentElementChild = find(parentChildNodes, isElementNode); + // or an element is preceding `child`. + if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { + throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); + } + } + } + + /** + * @private + * @param {Node} parent the parent node to insert `node` into + * @param {Node} node the node to insert + * @param {Node=} child the node that should become the `nextSibling` of `node` + * @returns {Node} + * @throws DOMException for several node combinations that would create a DOM that is not well-formed. + * @throws DOMException if `child` is provided but is not a child of `parent`. + * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity + */ + function _insertBefore(parent, node, child, _inDocumentAssertion) { + // To ensure pre-insertion validity of a node into a parent before a child, run these steps: + assertPreInsertionValidity1to5(parent, node, child); + + // If parent is a document, and any of the statements below, switched on the interface node implements, + // are true, then throw a "HierarchyRequestError" DOMException. + if (parent.nodeType === Node.DOCUMENT_NODE) { + (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); + } + + var cp = node.parentNode; + if(cp){ + cp.removeChild(node);//remove and update + } + if(node.nodeType === DOCUMENT_FRAGMENT_NODE){ + var newFirst = node.firstChild; + if (newFirst == null) { + return node; + } + var newLast = node.lastChild; + }else { + newFirst = newLast = node; + } + var pre = child ? child.previousSibling : parent.lastChild; + + newFirst.previousSibling = pre; + newLast.nextSibling = child; + + + if(pre){ + pre.nextSibling = newFirst; + }else { + parent.firstChild = newFirst; + } + if(child == null){ + parent.lastChild = newLast; + }else { + child.previousSibling = newLast; + } + do{ + newFirst.parentNode = parent; + // Update ownerDocument for each node being inserted + var targetDoc = parent.ownerDocument || parent; + _updateOwnerDocument(newFirst, targetDoc); + }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) + _onUpdateChild(parent.ownerDocument||parent, parent); + //console.log(parent.lastChild.nextSibling == null) + if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { + node.firstChild = node.lastChild = null; + } + return node; + } + + /** + * Recursively updates the ownerDocument property for a node and all its descendants + * @param {Node} node + * @param {Document} newOwnerDocument + * @private + */ + function _updateOwnerDocument(node, newOwnerDocument) { + if (node.ownerDocument === newOwnerDocument) { + return; + } + + node.ownerDocument = newOwnerDocument; + + // Update attributes if this is an element + if (node.nodeType === ELEMENT_NODE && node.attributes) { + for (var i = 0; i < node.attributes.length; i++) { + var attr = node.attributes.item(i); + if (attr) { + attr.ownerDocument = newOwnerDocument; + } + } + } + + // Recursively update child nodes + var child = node.firstChild; + while (child) { + _updateOwnerDocument(child, newOwnerDocument); + child = child.nextSibling; + } + } + + /** + * Appends `newChild` to `parentNode`. + * If `newChild` is already connected to a `parentNode` it is first removed from it. + * + * @see https://github.com/xmldom/xmldom/issues/135 + * @see https://github.com/xmldom/xmldom/issues/145 + * @param {Node} parentNode + * @param {Node} newChild + * @returns {Node} + * @private + */ + function _appendSingleChild (parentNode, newChild) { + if (newChild.parentNode) { + newChild.parentNode.removeChild(newChild); + } + newChild.parentNode = parentNode; + newChild.previousSibling = parentNode.lastChild; + newChild.nextSibling = null; + if (newChild.previousSibling) { + newChild.previousSibling.nextSibling = newChild; + } else { + parentNode.firstChild = newChild; + } + parentNode.lastChild = newChild; + _onUpdateChild(parentNode.ownerDocument, parentNode, newChild); + + // Update ownerDocument for the new child and all its descendants + var targetDoc = parentNode.ownerDocument || parentNode; + _updateOwnerDocument(newChild, targetDoc); + + return newChild; + } + + Document.prototype = { + //implementation : null, + nodeName : '#document', + nodeType : DOCUMENT_NODE, + /** + * The DocumentType node of the document. + * + * @readonly + * @type DocumentType + */ + doctype : null, + documentElement : null, + _inc : 1, + + insertBefore : function(newChild, refChild){//raises + if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ + var child = newChild.firstChild; + while(child){ + var next = child.nextSibling; + this.insertBefore(child,refChild); + child = next; + } + return newChild; + } + _insertBefore(this, newChild, refChild); + _updateOwnerDocument(newChild, this); + if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { + this.documentElement = newChild; + } + + return newChild; + }, + removeChild : function(oldChild){ + if(this.documentElement == oldChild){ + this.documentElement = null; + } + return _removeChild(this,oldChild); + }, + replaceChild: function (newChild, oldChild) { + //raises + _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); + _updateOwnerDocument(newChild, this); + if (oldChild) { + this.removeChild(oldChild); + } + if (isElementNode(newChild)) { + this.documentElement = newChild; + } + }, + // Introduced in DOM Level 2: + importNode : function(importedNode,deep){ + return importNode(this,importedNode,deep); + }, + // Introduced in DOM Level 2: + getElementById : function(id){ + var rtv = null; + _visitNode(this.documentElement,function(node){ + if(node.nodeType == ELEMENT_NODE){ + if(node.getAttribute('id') == id){ + rtv = node; + return true; + } + } + }); + return rtv; + }, + + /** + * The `getElementsByClassName` method of `Document` interface returns an array-like object + * of all child elements which have **all** of the given class name(s). + * + * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters. + * + * + * Warning: This is a live LiveNodeList. + * Changes in the DOM will reflect in the array as the changes occur. + * If an element selected by this array no longer qualifies for the selector, + * it will automatically be removed. Be aware of this for iteration purposes. + * + * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName + * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname + */ + getElementsByClassName: function(classNames) { + var classNamesSet = toOrderedSet(classNames); + return new LiveNodeList(this, function(base) { + var ls = []; + if (classNamesSet.length > 0) { + _visitNode(base.documentElement, function(node) { + if(node !== base && node.nodeType === ELEMENT_NODE) { + var nodeClassNames = node.getAttribute('class'); + // can be null if the attribute does not exist + if (nodeClassNames) { + // before splitting and iterating just compare them for the most common case + var matches = classNames === nodeClassNames; + if (!matches) { + var nodeClassNamesSet = toOrderedSet(nodeClassNames); + matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)); + } + if(matches) { + ls.push(node); + } + } + } + }); + } + return ls; + }); + }, + + //document factory method: + createElement : function(tagName){ + var node = new Element(); + node.ownerDocument = this; + node.nodeName = tagName; + node.tagName = tagName; + node.localName = tagName; + node.childNodes = new NodeList(); + var attrs = node.attributes = new NamedNodeMap(); + attrs._ownerElement = node; + return node; + }, + createDocumentFragment : function(){ + var node = new DocumentFragment(); + node.ownerDocument = this; + node.childNodes = new NodeList(); + return node; + }, + createTextNode : function(data){ + var node = new Text(); + node.ownerDocument = this; + node.appendData(data); + return node; + }, + createComment : function(data){ + var node = new Comment(); + node.ownerDocument = this; + node.appendData(data); + return node; + }, + /** + * Returns a new CDATASection node whose data is `data`. + * + * __This implementation differs from the specification:__ + * - calling this method on an HTML document does not throw `NotSupportedError`. + * + * @param {string} data + * @returns {CDATASection} + * @throws DOMException with code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection + * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection + */ + createCDATASection : function(data){ + if (data.indexOf(']]>') !== -1) { + throw new DOMException(INVALID_CHARACTER_ERR, 'data contains "]]>"'); + } + var node = new CDATASection(); + node.ownerDocument = this; + node.appendData(data); + return node; + }, + /** + * Returns a ProcessingInstruction node whose target is target and data is data. + * + * __This implementation differs from the specification:__ + * - it does not do any input validation on the arguments and doesn't throw "InvalidCharacterError". + * + * Note: When the resulting document is serialized with `requireWellFormed: true`, the + * serializer throws with code `INVALID_STATE_ERR` if `.data` contains `?>` (W3C DOM Parsing + * §3.2.1.7). Without that option the data is emitted verbatim. + * + * @param {string} target + * @param {string} data + * @returns {ProcessingInstruction} + * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction + * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction + * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7 + */ + createProcessingInstruction : function(target,data){ + var node = new ProcessingInstruction(); + node.ownerDocument = this; + node.tagName = node.nodeName = node.target = target; + node.nodeValue = node.data = data; + return node; + }, + createAttribute : function(name){ + var node = new Attr(); + node.ownerDocument = this; + node.name = name; + node.nodeName = name; + node.localName = name; + node.specified = true; + return node; + }, + createEntityReference : function(name){ + var node = new EntityReference(); + node.ownerDocument = this; + node.nodeName = name; + return node; + }, + // Introduced in DOM Level 2: + createElementNS : function(namespaceURI,qualifiedName){ + var node = new Element(); + var pl = qualifiedName.split(':'); + var attrs = node.attributes = new NamedNodeMap(); + node.childNodes = new NodeList(); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.tagName = qualifiedName; + node.namespaceURI = namespaceURI; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else { + //el.prefix = null; + node.localName = qualifiedName; + } + attrs._ownerElement = node; + return node; + }, + // Introduced in DOM Level 2: + createAttributeNS : function(namespaceURI,qualifiedName){ + var node = new Attr(); + var pl = qualifiedName.split(':'); + node.ownerDocument = this; + node.nodeName = qualifiedName; + node.name = qualifiedName; + node.namespaceURI = namespaceURI; + node.specified = true; + if(pl.length == 2){ + node.prefix = pl[0]; + node.localName = pl[1]; + }else { + //el.prefix = null; + node.localName = qualifiedName; + } + return node; + } + }; + _extends(Document,Node); + + + function Element() { + this._nsMap = {}; + } Element.prototype = { + nodeType : ELEMENT_NODE, + hasAttribute : function(name){ + return this.getAttributeNode(name)!=null; + }, + getAttribute : function(name){ + var attr = this.getAttributeNode(name); + return attr && attr.value || ''; + }, + getAttributeNode : function(name){ + return this.attributes.getNamedItem(name); + }, + setAttribute : function(name, value){ + var attr = this.ownerDocument.createAttribute(name); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr); + }, + removeAttribute : function(name){ + var attr = this.getAttributeNode(name); + attr && this.removeAttributeNode(attr); + }, + + //four real opeartion method + appendChild:function(newChild){ + if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ + return this.insertBefore(newChild,null); + }else { + return _appendSingleChild(this,newChild); + } + }, + setAttributeNode : function(newAttr){ + return this.attributes.setNamedItem(newAttr); + }, + setAttributeNodeNS : function(newAttr){ + return this.attributes.setNamedItemNS(newAttr); + }, + removeAttributeNode : function(oldAttr){ + //console.log(this == oldAttr.ownerElement) + return this.attributes.removeNamedItem(oldAttr.nodeName); + }, + //get real attribute name,and remove it by removeAttributeNode + removeAttributeNS : function(namespaceURI, localName){ + var old = this.getAttributeNodeNS(namespaceURI, localName); + old && this.removeAttributeNode(old); + }, + + hasAttributeNS : function(namespaceURI, localName){ + return this.getAttributeNodeNS(namespaceURI, localName)!=null; + }, + getAttributeNS : function(namespaceURI, localName){ + var attr = this.getAttributeNodeNS(namespaceURI, localName); + return attr && attr.value || ''; + }, + setAttributeNS : function(namespaceURI, qualifiedName, value){ + var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); + attr.value = attr.nodeValue = "" + value; + this.setAttributeNode(attr); + }, + getAttributeNodeNS : function(namespaceURI, localName){ + return this.attributes.getNamedItemNS(namespaceURI, localName); + }, + + getElementsByTagName : function(tagName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ + ls.push(node); + } + }); + return ls; + }); + }, + getElementsByTagNameNS : function(namespaceURI, localName){ + return new LiveNodeList(this,function(base){ + var ls = []; + _visitNode(base,function(node){ + if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ + ls.push(node); + } + }); + return ls; + + }); + } + }; + Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; + Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; + + + _extends(Element,Node); + function Attr() { + } Attr.prototype.nodeType = ATTRIBUTE_NODE; + _extends(Attr,Node); + + + function CharacterData() { + } CharacterData.prototype = { + data : '', + substringData : function(offset, count) { + return this.data.substring(offset, offset+count); + }, + appendData: function(text) { + text = this.data+text; + this.nodeValue = this.data = text; + this.length = text.length; + }, + insertData: function(offset,text) { + this.replaceData(offset,0,text); + + }, + appendChild:function(newChild){ + throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) + }, + deleteData: function(offset, count) { + this.replaceData(offset,count,""); + }, + replaceData: function(offset, count, text) { + var start = this.data.substring(0,offset); + var end = this.data.substring(offset+count); + text = start + text + end; + this.nodeValue = this.data = text; + this.length = text.length; + } + }; + _extends(CharacterData,Node); + function Text() { + } Text.prototype = { + nodeName : "#text", + nodeType : TEXT_NODE, + splitText : function(offset) { + var text = this.data; + var newText = text.substring(offset); + text = text.substring(0, offset); + this.data = this.nodeValue = text; + this.length = text.length; + var newNode = this.ownerDocument.createTextNode(newText); + if(this.parentNode){ + this.parentNode.insertBefore(newNode, this.nextSibling); + } + return newNode; + } + }; + _extends(Text,CharacterData); + function Comment() { + } Comment.prototype = { + nodeName : "#comment", + nodeType : COMMENT_NODE + }; + _extends(Comment,CharacterData); + + function CDATASection() { + } CDATASection.prototype = { + nodeName : "#cdata-section", + nodeType : CDATA_SECTION_NODE + }; + _extends(CDATASection,CharacterData); + + + /** + * Represents a DocumentType node (the `` declaration). + * + * `publicId`, `systemId`, and `internalSubset` are plain own-property assignments. + * xmldom does not enforce the `readonly` constraint declared by the WHATWG DOM spec — + * direct property writes succeed silently. Values are serialized verbatim when + * `requireWellFormed` is false (the default). When the serializer is invoked with + * `requireWellFormed: true` (via the 4th-parameter options object), it validates each + * field and throws `DOMException` with code `INVALID_STATE_ERR` on invalid values. + * + * @class + * @see https://developer.mozilla.org/en-US/docs/Web/API/DocumentType MDN + */ + function DocumentType() { + } DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; + _extends(DocumentType,Node); + + function Notation() { + } Notation.prototype.nodeType = NOTATION_NODE; + _extends(Notation,Node); + + function Entity() { + } Entity.prototype.nodeType = ENTITY_NODE; + _extends(Entity,Node); + + function EntityReference() { + } EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; + _extends(EntityReference,Node); + + function DocumentFragment() { + } DocumentFragment.prototype.nodeName = "#document-fragment"; + DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; + _extends(DocumentFragment,Node); + + + function ProcessingInstruction() { + } + ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; + _extends(ProcessingInstruction,Node); + function XMLSerializer(){} + /** + * Returns the result of serializing `node` to XML. + * + * When `options.requireWellFormed` is `true`, the serializer throws for content that would + * produce ill-formed XML. + * + * __This implementation differs from the specification:__ + * - CDATASection nodes whose data contains `]]>` are serialized by splitting the section + * at each `]]>` occurrence (following W3C DOM Level 3 Core `split-cdata-sections` + * default behaviour) unless `requireWellFormed` is `true`. + * - when `requireWellFormed` is `true`, `DOMException` with code `INVALID_STATE_ERR` + * is only thrown to prevent injection vectors, not for all the spec mandated checks. + * + * @param {Node} node + * @param {boolean} [isHtml] + * @param {function} [nodeFilter] + * @param {Object} [options] + * @param {boolean} [options.requireWellFormed=false] + * When `true`, throws for content that would produce ill-formed XML. + * @returns {string} + * @throws {DOMException} + * With code `INVALID_STATE_ERR` when `requireWellFormed` is `true` and: + * - a CDATASection node's data contains `"]]>"`, + * - a Comment node's data contains `"-->"` (bare `"--"` does not throw on this branch), + * - a ProcessingInstruction's data contains `"?>"`, + * - a DocumentType's `publicId` is non-empty and does not match the XML `PubidLiteral` + * production, + * - a DocumentType's `systemId` is non-empty and does not match the XML `SystemLiteral` + * production, or + * - a DocumentType's `internalSubset` contains `"]>"`. + * Note: xmldom does not enforce `readonly` on DocumentType fields — direct property + * writes succeed and are covered by the serializer-level checks above. + * @see https://html.spec.whatwg.org/#dom-xmlserializer-serializetostring + * @see https://w3c.github.io/DOM-Parsing/#xml-serialization + * @see https://github.com/w3c/DOM-Parsing/issues/84 + */ + XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter,options){ + return nodeSerializeToString.call(node,isHtml,nodeFilter,options); + }; + Node.prototype.toString = nodeSerializeToString; + function nodeSerializeToString(isHtml,nodeFilter,options){ + var requireWellFormed = !!options && !!options.requireWellFormed; + var buf = []; + var refNode = this.nodeType == 9 && this.documentElement || this; + var prefix = refNode.prefix; + var uri = refNode.namespaceURI; + + if(uri && prefix == null){ + //console.log(prefix) + var prefix = refNode.lookupPrefix(uri); + if(prefix == null){ + //isHTML = true; + var visibleNamespaces=[ + {namespace:uri,prefix:null} + //{namespace:uri,prefix:''} + ]; + } + } + serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces,requireWellFormed); + //console.log('###',this.nodeType,uri,prefix,buf.join('')) + return buf.join(''); + } + + function needNamespaceDefine(node, isHTML, visibleNamespaces) { + var prefix = node.prefix || ''; + var uri = node.namespaceURI; + // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) , + // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl : + // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty. + // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using) + // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared : + // > [...] Furthermore, the attribute value [...] must not be an empty string. + // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document. + if (!uri) { + return false; + } + if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) { + return false; + } + + var i = visibleNamespaces.length; + while (i--) { + var ns = visibleNamespaces[i]; + // get namespace prefix + if (ns.prefix === prefix) { + return ns.namespace !== uri; + } + } + return true; + } + /** + * Well-formed constraint: No < in Attribute Values + * > The replacement text of any entity referred to directly or indirectly + * > in an attribute value must not contain a <. + * @see https://www.w3.org/TR/xml11/#CleanAttrVals + * @see https://www.w3.org/TR/xml11/#NT-AttValue + * + * Literal whitespace other than space that appear in attribute values + * are serialized as their entity references, so they will be preserved. + * (In contrast to whitespace literals in the input which are normalized to spaces) + * @see https://www.w3.org/TR/xml11/#AVNormalize + * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes + */ + function addSerializedAttribute(buf, qualifiedName, value) { + buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"'); + } + + function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces, requireWellFormed) { + if (!visibleNamespaces) { + visibleNamespaces = []; + } + walkDOM(node, { ns: visibleNamespaces, isHTML: isHTML }, { + enter: function (n, ctx) { + var ns = ctx.ns; + var html = ctx.isHTML; + + if (nodeFilter) { + n = nodeFilter(n); + if (n) { + if (typeof n == 'string') { + buf.push(n); + return null; + } + } else { + return null; + } + } + + switch (n.nodeType) { + case ELEMENT_NODE: + var attrs = n.attributes; + var len = attrs.length; + var nodeName = n.tagName; + + html = NAMESPACE.isHTML(n.namespaceURI) || html; + + var prefixedNodeName = nodeName; + if (!html && !n.prefix && n.namespaceURI) { + var defaultNS; + // lookup current default ns from `xmlns` attribute + for (var ai = 0; ai < attrs.length; ai++) { + if (attrs.item(ai).name === 'xmlns') { + defaultNS = attrs.item(ai).value; + break; + } + } + if (!defaultNS) { + // lookup current default ns in visibleNamespaces + for (var nsi = ns.length - 1; nsi >= 0; nsi--) { + var nsEntry = ns[nsi]; + if (nsEntry.prefix === '' && nsEntry.namespace === n.namespaceURI) { + defaultNS = nsEntry.namespace; + break; + } + } + } + if (defaultNS !== n.namespaceURI) { + for (var nsi = ns.length - 1; nsi >= 0; nsi--) { + var nsEntry = ns[nsi]; + if (nsEntry.namespace === n.namespaceURI) { + if (nsEntry.prefix) { + prefixedNodeName = nsEntry.prefix + ':' + nodeName; + } + break; + } + } + } + } + + buf.push('<', prefixedNodeName); + + // Build a fresh namespace snapshot for this element's children. + // The slice prevents sibling elements from inheriting each other's declarations. + var childNs = ns.slice(); + for (var i = 0; i < len; i++) { + var attr = attrs.item(i); + if (attr.prefix == 'xmlns') { + childNs.push({ prefix: attr.localName, namespace: attr.value }); + } else if (attr.nodeName == 'xmlns') { + childNs.push({ prefix: '', namespace: attr.value }); + } + } + + for (var i = 0; i < len; i++) { + var attr = attrs.item(i); + if (needNamespaceDefine(attr, html, childNs)) { + var attrPrefix = attr.prefix || ''; + var uri = attr.namespaceURI; + addSerializedAttribute(buf, attrPrefix ? 'xmlns:' + attrPrefix : 'xmlns', uri); + childNs.push({ prefix: attrPrefix, namespace: uri }); + } + // Apply nodeFilter and serialize the attribute. + var filteredAttr = nodeFilter ? nodeFilter(attr) : attr; + if (filteredAttr) { + if (typeof filteredAttr === 'string') { + buf.push(filteredAttr); + } else { + addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value); + } + } + } + + // add namespace for current node + if (nodeName === prefixedNodeName && needNamespaceDefine(n, html, childNs)) { + var nodePrefix = n.prefix || ''; + var uri = n.namespaceURI; + addSerializedAttribute(buf, nodePrefix ? 'xmlns:' + nodePrefix : 'xmlns', uri); + childNs.push({ prefix: nodePrefix, namespace: uri }); + } + + var child = n.firstChild; + if (child || html && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) { + buf.push('>'); + if (html && /^script$/i.test(nodeName)) { + // Inline serialization for