dev-api: add developer portal, OpenAPI spec, and Flatenbadet case study
- New /developers/ page with API docs, SDKs, pricing, use cases - OpenAPI 3.0 spec for Orders, Missions, Photos, Analytics - Case study: Glasskiosken i Flatenbadet — complete ROI analysis - Updated /order/ with recurring missions and frequency dropdown
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
../acorn/bin/acorn
|
||||
+1
@@ -0,0 +1 @@
|
||||
../esbuild/bin/esbuild
|
||||
+1
@@ -0,0 +1 @@
|
||||
../eslint/bin/eslint.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../js-yaml/bin/js-yaml.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../mime/cli.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../nanoid/bin/nanoid.cjs
|
||||
+1
@@ -0,0 +1 @@
|
||||
../which/bin/node-which
|
||||
+1
@@ -0,0 +1 @@
|
||||
../pino/bin.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../pino-pretty/bin.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../rimraf/bin.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../rollup/dist/bin/rollup
|
||||
+1
@@ -0,0 +1 @@
|
||||
../vite/bin/vite.js
|
||||
+1
@@ -0,0 +1 @@
|
||||
../vite-node/vite-node.mjs
|
||||
+1
@@ -0,0 +1 @@
|
||||
../vitest/vitest.mjs
|
||||
+1
@@ -0,0 +1 @@
|
||||
../why-is-node-running/cli.js
|
||||
+3598
@@ -0,0 +1,3598 @@
|
||||
{
|
||||
"name": "@quixzoom/frilans-payout-server",
|
||||
"version": "2.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.21.5",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
|
||||
"integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"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/eslintrc": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz",
|
||||
"integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ajv": "^6.12.4",
|
||||
"debug": "^4.3.2",
|
||||
"espree": "^9.6.0",
|
||||
"globals": "^13.19.0",
|
||||
"ignore": "^5.2.0",
|
||||
"import-fresh": "^3.2.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"minimatch": "^3.1.2",
|
||||
"strip-json-comments": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/js": {
|
||||
"version": "8.57.1",
|
||||
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz",
|
||||
"integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@humanwhocodes/config-array": {
|
||||
"version": "0.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
|
||||
"integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==",
|
||||
"deprecated": "Use @eslint/config-array instead",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@humanwhocodes/object-schema": "^2.0.3",
|
||||
"debug": "^4.3.1",
|
||||
"minimatch": "^3.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.10.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/object-schema": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz",
|
||||
"integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==",
|
||||
"deprecated": "Use @eslint/object-schema instead",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"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/@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/@nodelib/fs.scandir": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
|
||||
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "2.0.5",
|
||||
"run-parallel": "^1.1.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.stat": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
|
||||
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@nodelib/fs.walk": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
|
||||
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.scandir": "2.1.5",
|
||||
"fastq": "^1.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"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,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
]
|
||||
},
|
||||
"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/@types/estree": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
||||
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@ungap/structured-clone": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.3.tgz",
|
||||
"integrity": "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
|
||||
"integrity": "sha512-jXL+9+ZNIJKruofqXuuTClf44eSpcHlgj3CiuNihUF3Ioujtmc0zIa3UJOW5RjDK1YLBJZnWBlPuqhYycLioog==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/spy": "1.6.1",
|
||||
"@vitest/utils": "1.6.1",
|
||||
"chai": "^4.3.10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/runner": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-1.6.1.tgz",
|
||||
"integrity": "sha512-3nSnYXkVkf3mXFfE7vVyPmi3Sazhb/2cfZGGs0JRzFsPFvAMBEcrweV1V1GsrstdXeKCTXlJbvnQwGWgEIHmOA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/utils": "1.6.1",
|
||||
"p-limit": "^5.0.0",
|
||||
"pathe": "^1.1.1"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/runner/node_modules/p-limit": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-5.0.0.tgz",
|
||||
"integrity": "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"yocto-queue": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/runner/node_modules/yocto-queue": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz",
|
||||
"integrity": "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/snapshot": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-1.6.1.tgz",
|
||||
"integrity": "sha512-WvidQuWAzU2p95u8GAKlRMqMyN1yOJkGHnx3M1PL9Raf7AQ1kwLKg04ADlCa3+OXUZE7BceOhVZiuWAbzCKcUQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"magic-string": "^0.30.5",
|
||||
"pathe": "^1.1.1",
|
||||
"pretty-format": "^29.7.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/spy": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-1.6.1.tgz",
|
||||
"integrity": "sha512-MGcMmpGkZebsMZhbQKkAf9CX5zGvjkBTqf8Zx3ApYWXr3wG+QvEu2eXWfnIIWYSJExIp4V9FCKDEeygzkYrXMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tinyspy": "^2.2.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/utils": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-1.6.1.tgz",
|
||||
"integrity": "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"diff-sequences": "^29.6.3",
|
||||
"estree-walker": "^3.0.3",
|
||||
"loupe": "^2.3.7",
|
||||
"pretty-format": "^29.7.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/abort-controller": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
|
||||
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"event-target-shim": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.5"
|
||||
}
|
||||
},
|
||||
"node_modules/accepts": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
|
||||
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.34",
|
||||
"negotiator": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.17.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
|
||||
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn-jsx": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
|
||||
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn-walk": {
|
||||
"version": "8.3.5",
|
||||
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",
|
||||
"integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"acorn": "^8.11.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "6.15.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
|
||||
"integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
"fast-json-stable-stringify": "^2.0.0",
|
||||
"json-schema-traverse": "^0.4.1",
|
||||
"uri-js": "^4.2.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/array-flatten": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
|
||||
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz",
|
||||
"integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/atomic-sleep": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
|
||||
"integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "1.20.6",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz",
|
||||
"integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"content-type": "~1.0.5",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "~1.2.0",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"on-finished": "~2.4.1",
|
||||
"qs": "~6.15.1",
|
||||
"raw-body": "~2.5.3",
|
||||
"type-is": "~1.6.18",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.16",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
|
||||
"integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/cac": {
|
||||
"version": "6.7.14",
|
||||
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
|
||||
"integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bound": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
|
||||
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/callsites": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
|
||||
"integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/chai": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-4.5.0.tgz",
|
||||
"integrity": "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"assertion-error": "^1.1.0",
|
||||
"check-error": "^1.0.3",
|
||||
"deep-eql": "^4.1.3",
|
||||
"get-func-name": "^2.0.2",
|
||||
"loupe": "^2.3.6",
|
||||
"pathval": "^1.1.1",
|
||||
"type-detect": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/chalk?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/check-error": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz",
|
||||
"integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"get-func-name": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/colorette": {
|
||||
"version": "2.0.20",
|
||||
"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
|
||||
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/confbox": {
|
||||
"version": "0.1.8",
|
||||
"resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
|
||||
"integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/content-disposition": {
|
||||
"version": "0.5.4",
|
||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "5.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/content-type": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
|
||||
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
|
||||
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie-signature": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
|
||||
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cors": {
|
||||
"version": "2.8.6",
|
||||
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
|
||||
"integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"object-assign": "^4",
|
||||
"vary": "^1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
"shebang-command": "^2.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/dateformat": {
|
||||
"version": "4.6.3",
|
||||
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
|
||||
"integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/deep-eql": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.4.tgz",
|
||||
"integrity": "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"type-detect": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/deep-is": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
|
||||
"integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/destroy": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
|
||||
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8",
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/diff-sequences": {
|
||||
"version": "29.6.3",
|
||||
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
|
||||
"integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/doctrine": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
|
||||
"integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"esutils": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/encodeurl": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
|
||||
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/end-of-stream": {
|
||||
"version": "1.4.5",
|
||||
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
|
||||
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"once": "^1.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"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==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
|
||||
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.21.5",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
|
||||
"integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.21.5",
|
||||
"@esbuild/android-arm": "0.21.5",
|
||||
"@esbuild/android-arm64": "0.21.5",
|
||||
"@esbuild/android-x64": "0.21.5",
|
||||
"@esbuild/darwin-arm64": "0.21.5",
|
||||
"@esbuild/darwin-x64": "0.21.5",
|
||||
"@esbuild/freebsd-arm64": "0.21.5",
|
||||
"@esbuild/freebsd-x64": "0.21.5",
|
||||
"@esbuild/linux-arm": "0.21.5",
|
||||
"@esbuild/linux-arm64": "0.21.5",
|
||||
"@esbuild/linux-ia32": "0.21.5",
|
||||
"@esbuild/linux-loong64": "0.21.5",
|
||||
"@esbuild/linux-mips64el": "0.21.5",
|
||||
"@esbuild/linux-ppc64": "0.21.5",
|
||||
"@esbuild/linux-riscv64": "0.21.5",
|
||||
"@esbuild/linux-s390x": "0.21.5",
|
||||
"@esbuild/linux-x64": "0.21.5",
|
||||
"@esbuild/netbsd-x64": "0.21.5",
|
||||
"@esbuild/openbsd-x64": "0.21.5",
|
||||
"@esbuild/sunos-x64": "0.21.5",
|
||||
"@esbuild/win32-arm64": "0.21.5",
|
||||
"@esbuild/win32-ia32": "0.21.5",
|
||||
"@esbuild/win32-x64": "0.21.5"
|
||||
}
|
||||
},
|
||||
"node_modules/escape-html": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
|
||||
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/escape-string-regexp": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
|
||||
"integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint": {
|
||||
"version": "8.57.1",
|
||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz",
|
||||
"integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==",
|
||||
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.6.1",
|
||||
"@eslint/eslintrc": "^2.1.4",
|
||||
"@eslint/js": "8.57.1",
|
||||
"@humanwhocodes/config-array": "^0.13.0",
|
||||
"@humanwhocodes/module-importer": "^1.0.1",
|
||||
"@nodelib/fs.walk": "^1.2.8",
|
||||
"@ungap/structured-clone": "^1.2.0",
|
||||
"ajv": "^6.12.4",
|
||||
"chalk": "^4.0.0",
|
||||
"cross-spawn": "^7.0.2",
|
||||
"debug": "^4.3.2",
|
||||
"doctrine": "^3.0.0",
|
||||
"escape-string-regexp": "^4.0.0",
|
||||
"eslint-scope": "^7.2.2",
|
||||
"eslint-visitor-keys": "^3.4.3",
|
||||
"espree": "^9.6.1",
|
||||
"esquery": "^1.4.2",
|
||||
"esutils": "^2.0.2",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"file-entry-cache": "^6.0.1",
|
||||
"find-up": "^5.0.0",
|
||||
"glob-parent": "^6.0.2",
|
||||
"globals": "^13.19.0",
|
||||
"graphemer": "^1.4.0",
|
||||
"ignore": "^5.2.0",
|
||||
"imurmurhash": "^0.1.4",
|
||||
"is-glob": "^4.0.0",
|
||||
"is-path-inside": "^3.0.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"json-stable-stringify-without-jsonify": "^1.0.1",
|
||||
"levn": "^0.4.1",
|
||||
"lodash.merge": "^4.6.2",
|
||||
"minimatch": "^3.1.2",
|
||||
"natural-compare": "^1.4.0",
|
||||
"optionator": "^0.9.3",
|
||||
"strip-ansi": "^6.0.1",
|
||||
"text-table": "^0.2.0"
|
||||
},
|
||||
"bin": {
|
||||
"eslint": "bin/eslint.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-scope": {
|
||||
"version": "7.2.2",
|
||||
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz",
|
||||
"integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"esrecurse": "^4.3.0",
|
||||
"estraverse": "^5.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-visitor-keys": {
|
||||
"version": "3.4.3",
|
||||
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz",
|
||||
"integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/espree": {
|
||||
"version": "9.6.1",
|
||||
"resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz",
|
||||
"integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"acorn": "^8.9.0",
|
||||
"acorn-jsx": "^5.3.2",
|
||||
"eslint-visitor-keys": "^3.4.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/esquery": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz",
|
||||
"integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"estraverse": "^5.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/esrecurse": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
|
||||
"integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"estraverse": "^5.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/estraverse": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
|
||||
"integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/estree-walker": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/esutils": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
|
||||
"integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/etag": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
|
||||
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/event-target-shim": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
|
||||
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8.x"
|
||||
}
|
||||
},
|
||||
"node_modules/execa": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz",
|
||||
"integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cross-spawn": "^7.0.3",
|
||||
"get-stream": "^8.0.1",
|
||||
"human-signals": "^5.0.0",
|
||||
"is-stream": "^3.0.0",
|
||||
"merge-stream": "^2.0.0",
|
||||
"npm-run-path": "^5.1.0",
|
||||
"onetime": "^6.0.0",
|
||||
"signal-exit": "^4.1.0",
|
||||
"strip-final-newline": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.17"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sindresorhus/execa?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/express": {
|
||||
"version": "4.22.2",
|
||||
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
|
||||
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"accepts": "~1.3.8",
|
||||
"array-flatten": "1.1.1",
|
||||
"body-parser": "~1.20.5",
|
||||
"content-disposition": "~0.5.4",
|
||||
"content-type": "~1.0.4",
|
||||
"cookie": "~0.7.1",
|
||||
"cookie-signature": "~1.0.6",
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"finalhandler": "~1.3.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.0",
|
||||
"merge-descriptors": "1.0.3",
|
||||
"methods": "~1.1.2",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"path-to-regexp": "~0.1.12",
|
||||
"proxy-addr": "~2.0.7",
|
||||
"qs": "~6.15.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"safe-buffer": "5.2.1",
|
||||
"send": "~0.19.0",
|
||||
"serve-static": "~1.16.2",
|
||||
"setprototypeof": "1.2.0",
|
||||
"statuses": "~2.0.1",
|
||||
"type-is": "~1.6.18",
|
||||
"utils-merge": "1.0.1",
|
||||
"vary": "~1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/express-rate-limit": {
|
||||
"version": "7.5.1",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz",
|
||||
"integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/express-rate-limit"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"express": ">= 4.11"
|
||||
}
|
||||
},
|
||||
"node_modules/express/node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/express/node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-copy": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz",
|
||||
"integrity": "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-deep-equal": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-json-stable-stringify": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
|
||||
"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-levenshtein": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
|
||||
"integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-redact": {
|
||||
"version": "3.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz",
|
||||
"integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/fast-safe-stringify": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
|
||||
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fastq": {
|
||||
"version": "1.20.1",
|
||||
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
|
||||
"integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"reusify": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/file-entry-cache": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
|
||||
"integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"flat-cache": "^3.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10.12.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler": {
|
||||
"version": "1.3.2",
|
||||
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
|
||||
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"parseurl": "~1.3.3",
|
||||
"statuses": "~2.0.2",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler/node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/finalhandler/node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",
|
||||
"integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^6.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/flat-cache": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz",
|
||||
"integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"flatted": "^3.2.9",
|
||||
"keyv": "^4.5.3",
|
||||
"rimraf": "^3.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10.12.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/flatted": {
|
||||
"version": "3.4.2",
|
||||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
|
||||
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/forwarded": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fresh": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
|
||||
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/fs.realpath": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
|
||||
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"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==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-func-name": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz",
|
||||
"integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/get-stream": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz",
|
||||
"integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/glob-parent": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
|
||||
"integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"is-glob": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/globals": {
|
||||
"version": "13.24.0",
|
||||
"resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz",
|
||||
"integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"type-fest": "^0.20.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/graphemer": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
|
||||
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"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==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/helmet": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/helmet/-/helmet-7.2.0.tgz",
|
||||
"integrity": "sha512-ZRiwvN089JfMXokizgqEPXsl2Guk094yExfoDXR0cBYWxtBbaSww/w+vT4WEJsBW2iTUi1GgZ6swmoug3Oy4Xw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/help-me": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
|
||||
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/http-errors": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
|
||||
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"depd": "~2.0.0",
|
||||
"inherits": "~2.0.4",
|
||||
"setprototypeof": "~1.2.0",
|
||||
"statuses": "~2.0.2",
|
||||
"toidentifier": "~1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/human-signals": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
|
||||
"integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=16.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/import-fresh": {
|
||||
"version": "3.3.1",
|
||||
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
|
||||
"integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"parent-module": "^1.0.0",
|
||||
"resolve-from": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/imurmurhash": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
|
||||
"integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.8.19"
|
||||
}
|
||||
},
|
||||
"node_modules/inflight": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
|
||||
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
|
||||
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"once": "^1.3.0",
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/inherits": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ipaddr.js": {
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
|
||||
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-glob": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-path-inside": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz",
|
||||
"integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-stream": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",
|
||||
"integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/joycon": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
|
||||
"integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/js-tokens": {
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
|
||||
"integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
||||
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/json-buffer": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
|
||||
"integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/json-stable-stringify-without-jsonify": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz",
|
||||
"integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/keyv": {
|
||||
"version": "4.5.4",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
||||
"integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"json-buffer": "3.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/levn": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
|
||||
"integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prelude-ls": "^1.2.1",
|
||||
"type-check": "~0.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/local-pkg": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.1.tgz",
|
||||
"integrity": "sha512-9rrA30MRRP3gBD3HTGnC6cDFpaE1kVDWxWgqWJUN0RvDNAo+Nz/9GxB+nHOH0ifbVFy0hSA1V6vFDvnx54lTEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mlly": "^1.7.3",
|
||||
"pkg-types": "^1.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
|
||||
"integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.merge": {
|
||||
"version": "4.6.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
|
||||
"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/loupe": {
|
||||
"version": "2.3.7",
|
||||
"resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz",
|
||||
"integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"get-func-name": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"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/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/media-typer": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
|
||||
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-descriptors": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
|
||||
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-stream": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
|
||||
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/methods": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
|
||||
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
|
||||
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"mime": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mimic-fn": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",
|
||||
"integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
|
||||
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/mlly": {
|
||||
"version": "1.8.2",
|
||||
"resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
|
||||
"integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"acorn": "^8.16.0",
|
||||
"pathe": "^2.0.3",
|
||||
"pkg-types": "^1.3.1",
|
||||
"ufo": "^1.6.3"
|
||||
}
|
||||
},
|
||||
"node_modules/mlly/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/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"nanoid": "bin/nanoid.cjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/natural-compare": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
|
||||
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/npm-run-path": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz",
|
||||
"integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/npm-run-path/node_modules/path-key": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz",
|
||||
"integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/object-assign": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/on-exit-leak-free": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
|
||||
"integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/on-finished": {
|
||||
"version": "2.4.1",
|
||||
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
|
||||
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ee-first": "1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/once": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
|
||||
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/onetime": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz",
|
||||
"integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mimic-fn": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
"integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"deep-is": "^0.1.3",
|
||||
"fast-levenshtein": "^2.0.6",
|
||||
"levn": "^0.4.1",
|
||||
"prelude-ls": "^1.2.1",
|
||||
"type-check": "^0.4.0",
|
||||
"word-wrap": "^1.2.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
|
||||
"integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"yocto-queue": "^0.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-locate": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
|
||||
"integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^3.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/parent-module": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
|
||||
"integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"callsites": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/parseurl": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-is-absolute": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
|
||||
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
|
||||
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
|
||||
"integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pathval": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz",
|
||||
"integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.22.0",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
|
||||
"integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.14.0",
|
||||
"pg-pool": "^3.14.0",
|
||||
"pg-protocol": "^1.15.0",
|
||||
"pg-types": "2.2.0",
|
||||
"pgpass": "1.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"pg-cloudflare": "^1.4.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg-native": ">=3.0.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"pg-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/pg-cloudflare": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
|
||||
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/pg-connection-string": {
|
||||
"version": "2.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
|
||||
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-int8": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-pool": {
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-protocol": {
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.15.0.tgz",
|
||||
"integrity": "sha512-cq9sECI5s0+uPUXjbz8ioyPJni6RzsRib0US67i5IoTZKw8fNeYlVE7u8F4dG7vEJJtc5wdD1K189lCCUwqWTQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
"postgres-array": "~2.0.0",
|
||||
"postgres-bytea": "~1.0.0",
|
||||
"postgres-date": "~1.0.4",
|
||||
"postgres-interval": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/pgpass": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/pino": {
|
||||
"version": "8.21.0",
|
||||
"resolved": "https://registry.npmjs.org/pino/-/pino-8.21.0.tgz",
|
||||
"integrity": "sha512-ip4qdzjkAyDDZklUaZkcRFb2iA118H9SgRh8yzTkSQK8HilsOJF7rSY8HoW5+I0M46AZgX/pxbprf2vvzQCE0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"atomic-sleep": "^1.0.0",
|
||||
"fast-redact": "^3.1.1",
|
||||
"on-exit-leak-free": "^2.1.0",
|
||||
"pino-abstract-transport": "^1.2.0",
|
||||
"pino-std-serializers": "^6.0.0",
|
||||
"process-warning": "^3.0.0",
|
||||
"quick-format-unescaped": "^4.0.3",
|
||||
"real-require": "^0.2.0",
|
||||
"safe-stable-stringify": "^2.3.1",
|
||||
"sonic-boom": "^3.7.0",
|
||||
"thread-stream": "^2.6.0"
|
||||
},
|
||||
"bin": {
|
||||
"pino": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/pino-abstract-transport": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.2.0.tgz",
|
||||
"integrity": "sha512-Guhh8EZfPCfH+PMXAb6rKOjGQEoy0xlAIn+irODG5kgfYV+BQ0rGYYWTIel3P5mmyXqkYkPmdIkywsn6QKUR1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"readable-stream": "^4.0.0",
|
||||
"split2": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pino-pretty": {
|
||||
"version": "10.3.1",
|
||||
"resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.3.1.tgz",
|
||||
"integrity": "sha512-az8JbIYeN/1iLj2t0jR9DV48/LQ3RC6hZPpapKPkb84Q+yTidMCpgWxIT3N0flnBDilyBQ1luWNpOeJptjdp/g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"colorette": "^2.0.7",
|
||||
"dateformat": "^4.6.3",
|
||||
"fast-copy": "^3.0.0",
|
||||
"fast-safe-stringify": "^2.1.1",
|
||||
"help-me": "^5.0.0",
|
||||
"joycon": "^3.1.1",
|
||||
"minimist": "^1.2.6",
|
||||
"on-exit-leak-free": "^2.1.0",
|
||||
"pino-abstract-transport": "^1.0.0",
|
||||
"pump": "^3.0.0",
|
||||
"readable-stream": "^4.0.0",
|
||||
"secure-json-parse": "^2.4.0",
|
||||
"sonic-boom": "^3.0.0",
|
||||
"strip-json-comments": "^3.1.1"
|
||||
},
|
||||
"bin": {
|
||||
"pino-pretty": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/pino-std-serializers": {
|
||||
"version": "6.2.2",
|
||||
"resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-6.2.2.tgz",
|
||||
"integrity": "sha512-cHjPPsE+vhj/tnhCy/wiMh3M3z3h/j15zHQX+S9GkTBgqJuTuJzYJ4gUyACLhDaJ7kk9ba9iRDmbH2tJU03OiA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pkg-types": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
|
||||
"integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"confbox": "^0.1.8",
|
||||
"mlly": "^1.7.4",
|
||||
"pathe": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pkg-types/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/postcss": {
|
||||
"version": "8.5.19",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.19.tgz",
|
||||
"integrity": "sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/postcss/"
|
||||
},
|
||||
{
|
||||
"type": "tidelift",
|
||||
"url": "https://tidelift.com/funding/github/npm/postcss"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.12",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-array": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-bytea": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-date": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-interval": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/prelude-ls": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||
"integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"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/pretty-format/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/process": {
|
||||
"version": "0.11.10",
|
||||
"resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
|
||||
"integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/process-warning": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
|
||||
"integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/proxy-addr": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"forwarded": "0.2.0",
|
||||
"ipaddr.js": "1.9.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/pump": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
||||
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"end-of-stream": "^1.1.0",
|
||||
"once": "^1.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/punycode": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/quick-format-unescaped": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
|
||||
"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/raw-body": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
|
||||
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "~3.1.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"iconv-lite": "~0.4.24",
|
||||
"unpipe": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"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/readable-stream": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
|
||||
"integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"buffer": "^6.0.3",
|
||||
"events": "^3.3.0",
|
||||
"process": "^0.11.10",
|
||||
"string_decoder": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/real-require": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
|
||||
"integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12.13.0"
|
||||
}
|
||||
},
|
||||
"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/reusify": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
||||
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"iojs": ">=1.0.0",
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
||||
"deprecated": "Rimraf versions prior to v4 are no longer supported",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"glob": "^7.1.3"
|
||||
},
|
||||
"bin": {
|
||||
"rimraf": "bin.js"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"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": ">=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/run-parallel": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"queue-microtask": "^1.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safe-stable-stringify": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
|
||||
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/secure-json-parse": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",
|
||||
"integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/send": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
|
||||
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "2.6.9",
|
||||
"depd": "2.0.0",
|
||||
"destroy": "1.2.0",
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"etag": "~1.8.1",
|
||||
"fresh": "~0.5.2",
|
||||
"http-errors": "~2.0.1",
|
||||
"mime": "1.6.0",
|
||||
"ms": "2.1.3",
|
||||
"on-finished": "~2.4.1",
|
||||
"range-parser": "~1.2.1",
|
||||
"statuses": "~2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/debug": {
|
||||
"version": "2.6.9",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/send/node_modules/debug/node_modules/ms": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/serve-static": {
|
||||
"version": "1.16.3",
|
||||
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
|
||||
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"encodeurl": "~2.0.0",
|
||||
"escape-html": "~1.0.3",
|
||||
"parseurl": "~1.3.3",
|
||||
"send": "~0.19.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-regex": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
||||
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
|
||||
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4",
|
||||
"side-channel-list": "^1.0.1",
|
||||
"side-channel-map": "^1.0.1",
|
||||
"side-channel-weakmap": "^1.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-list": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
|
||||
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"object-inspect": "^1.13.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-map": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
|
||||
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/side-channel-weakmap": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
|
||||
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bound": "^1.0.2",
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.5",
|
||||
"object-inspect": "^1.13.3",
|
||||
"side-channel-map": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/siginfo": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
|
||||
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/signal-exit": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
|
||||
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/sonic-boom": {
|
||||
"version": "3.8.1",
|
||||
"resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.8.1.tgz",
|
||||
"integrity": "sha512-y4Z8LCDBuum+PBP3lSV7RHrXscqksve/bi0as7mhwVnBW+/wUqKT/2Kb7um8yqcFy0duYbbPxzt89Zy2nOCaxg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"atomic-sleep": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/split2": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/stackback": {
|
||||
"version": "0.0.2",
|
||||
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
||||
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/statuses": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/std-env": {
|
||||
"version": "3.10.0",
|
||||
"resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
|
||||
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
||||
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "~5.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-final-newline": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz",
|
||||
"integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-json-comments": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
|
||||
"integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-literal": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-2.1.1.tgz",
|
||||
"integrity": "sha512-631UJ6O00eNGfMiWG78ck80dfBab8X6IVFB51jZK5Icd7XAs60Z5y7QdSd/wGIklnWvRbUNloVzhOKKmutxQ6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"js-tokens": "^9.0.1"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/supports-color": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-flag": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/text-table": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
|
||||
"integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/thread-stream": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-2.7.0.tgz",
|
||||
"integrity": "sha512-qQiRWsU/wvNolI6tbbCKd9iKaTnCXsTwVxhhKM6nctPdujTyztjlbUkUTUymidWcMnZ5pWR0ej4a0tjsW021vw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"real-require": "^0.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinypool": {
|
||||
"version": "0.8.4",
|
||||
"resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.8.4.tgz",
|
||||
"integrity": "sha512-i11VH5gS6IFeLY3gMBQ00/MmLncVP7JLXOw1vlgkytLmJK7QnEr7NXf0LBdxfmNPAeyetukOk0bOYrJrFGjYJQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyspy": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz",
|
||||
"integrity": "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/toidentifier": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
|
||||
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
"integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"prelude-ls": "^1.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/type-detect": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz",
|
||||
"integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/type-fest": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz",
|
||||
"integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==",
|
||||
"dev": true,
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "1.6.18",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"media-typer": "0.3.0",
|
||||
"mime-types": "~2.1.24"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/ufo": {
|
||||
"version": "1.6.4",
|
||||
"resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz",
|
||||
"integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/unpipe": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/uri-js": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/utils-merge": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vary": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "5.4.21",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
||||
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.21.3",
|
||||
"postcss": "^8.4.43",
|
||||
"rollup": "^4.20.0"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.0.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/vitejs/vite?sponsor=1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": "^18.0.0 || >=20.0.0",
|
||||
"less": "*",
|
||||
"lightningcss": "^1.21.0",
|
||||
"sass": "*",
|
||||
"sass-embedded": "*",
|
||||
"stylus": "*",
|
||||
"sugarss": "*",
|
||||
"terser": "^5.4.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"less": {
|
||||
"optional": true
|
||||
},
|
||||
"lightningcss": {
|
||||
"optional": true
|
||||
},
|
||||
"sass": {
|
||||
"optional": true
|
||||
},
|
||||
"sass-embedded": {
|
||||
"optional": true
|
||||
},
|
||||
"stylus": {
|
||||
"optional": true
|
||||
},
|
||||
"sugarss": {
|
||||
"optional": true
|
||||
},
|
||||
"terser": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vite-node": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/vite-node/-/vite-node-1.6.1.tgz",
|
||||
"integrity": "sha512-YAXkfvGtuTzwWbDSACdJSg4A4DZiAqckWe90Zapc/sEX3XvHcw1NdurM/6od8J207tSDqNbSsgdCacBgvJKFuA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cac": "^6.7.14",
|
||||
"debug": "^4.3.4",
|
||||
"pathe": "^1.1.1",
|
||||
"picocolors": "^1.0.0",
|
||||
"vite": "^5.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"vite-node": "vite-node.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.0.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "1.6.1",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-1.6.1.tgz",
|
||||
"integrity": "sha512-Ljb1cnSJSivGN0LqXd/zmDbWEM0RNNg2t1QW/XUhYl/qPqyu7CsqeWtqQXHVaJsecLPuDoak2oJcZN2QoRIOag==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/expect": "1.6.1",
|
||||
"@vitest/runner": "1.6.1",
|
||||
"@vitest/snapshot": "1.6.1",
|
||||
"@vitest/spy": "1.6.1",
|
||||
"@vitest/utils": "1.6.1",
|
||||
"acorn-walk": "^8.3.2",
|
||||
"chai": "^4.3.10",
|
||||
"debug": "^4.3.4",
|
||||
"execa": "^8.0.1",
|
||||
"local-pkg": "^0.5.0",
|
||||
"magic-string": "^0.30.5",
|
||||
"pathe": "^1.1.1",
|
||||
"picocolors": "^1.0.0",
|
||||
"std-env": "^3.5.0",
|
||||
"strip-literal": "^2.0.0",
|
||||
"tinybench": "^2.5.1",
|
||||
"tinypool": "^0.8.3",
|
||||
"vite": "^5.0.0",
|
||||
"vite-node": "1.6.1",
|
||||
"why-is-node-running": "^2.2.2"
|
||||
},
|
||||
"bin": {
|
||||
"vitest": "vitest.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.0.0 || >=20.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@edge-runtime/vm": "*",
|
||||
"@types/node": "^18.0.0 || >=20.0.0",
|
||||
"@vitest/browser": "1.6.1",
|
||||
"@vitest/ui": "1.6.1",
|
||||
"happy-dom": "*",
|
||||
"jsdom": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@edge-runtime/vm": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/browser": {
|
||||
"optional": true
|
||||
},
|
||||
"@vitest/ui": {
|
||||
"optional": true
|
||||
},
|
||||
"happy-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"jsdom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/node-which"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/why-is-node-running": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"siginfo": "^2.0.0",
|
||||
"stackback": "0.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"why-is-node-running": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/word-wrap": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
||||
"integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
"integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":"1.6.1","results":[[":tests/frilans.test.mjs",{"duration":3,"failed":false}]]}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# esbuild
|
||||
|
||||
This is the Linux ARM 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
|
||||
BIN
Binary file not shown.
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@esbuild/linux-arm64",
|
||||
"version": "0.21.5",
|
||||
"description": "The Linux ARM 64-bit binary for esbuild, a JavaScript bundler.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/evanw/esbuild.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"preferUnplugged": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# @eslint-community/eslint-utils
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/eslint-utils)
|
||||
[](http://www.npmtrends.com/@eslint-community/eslint-utils)
|
||||
[](https://github.com/eslint-community/eslint-utils/actions)
|
||||
[](https://codecov.io/gh/eslint-community/eslint-utils)
|
||||
|
||||
## 🏁 Goal
|
||||
|
||||
This package provides utility functions and classes for make ESLint custom rules.
|
||||
|
||||
For examples:
|
||||
|
||||
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
|
||||
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
See [documentation](https://eslint-community.github.io/eslint-utils).
|
||||
|
||||
## 📰 Changelog
|
||||
|
||||
See [releases](https://github.com/eslint-community/eslint-utils/releases).
|
||||
|
||||
## ❤️ Contributing
|
||||
|
||||
Welcome contributing!
|
||||
|
||||
Please use GitHub's Issues/PRs.
|
||||
|
||||
### Development Tools
|
||||
|
||||
- `npm run test-coverage` runs tests and measures coverage.
|
||||
- `npm run clean` removes the coverage result of `npm run test-coverage` command.
|
||||
- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command.
|
||||
- `npm run lint` runs ESLint.
|
||||
- `npm run watch` runs tests on each file change.
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
import * as eslint from 'eslint';
|
||||
import { Rule, AST } from 'eslint';
|
||||
import * as estree from 'estree';
|
||||
|
||||
declare const READ: unique symbol;
|
||||
declare const CALL: unique symbol;
|
||||
declare const CONSTRUCT: unique symbol;
|
||||
declare const ESM: unique symbol;
|
||||
declare class ReferenceTracker {
|
||||
constructor(globalScope: Scope$2, options?: {
|
||||
mode?: "legacy" | "strict" | undefined;
|
||||
globalObjectNames?: string[] | undefined;
|
||||
} | undefined);
|
||||
private variableStack;
|
||||
private globalScope;
|
||||
private mode;
|
||||
private globalObjectNames;
|
||||
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
|
||||
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
|
||||
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
|
||||
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
|
||||
private _iterateVariableReferences;
|
||||
private _iteratePropertyReferences;
|
||||
private _iterateLhsReferences;
|
||||
private _iterateImportReferences;
|
||||
}
|
||||
declare namespace ReferenceTracker {
|
||||
export { READ };
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
}
|
||||
type Scope$2 = eslint.Scope.Scope;
|
||||
type Expression = estree.Expression;
|
||||
type TraceMap$2<T> = TraceMap$1<T>;
|
||||
type TrackedReferences$2<T> = TrackedReferences$1<T>;
|
||||
|
||||
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
|
||||
type StaticValueProvided$1 = {
|
||||
optional?: undefined;
|
||||
value: unknown;
|
||||
};
|
||||
type StaticValueOptional$1 = {
|
||||
optional?: true;
|
||||
value: undefined;
|
||||
};
|
||||
type ReferenceTrackerOptions$1 = {
|
||||
globalObjectNames?: string[];
|
||||
mode?: "legacy" | "strict";
|
||||
};
|
||||
type TraceMap$1<T = unknown> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
};
|
||||
type TraceMapObject<T> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
[CALL]?: T;
|
||||
[CONSTRUCT]?: T;
|
||||
[READ]?: T;
|
||||
[ESM]?: boolean;
|
||||
};
|
||||
type TrackedReferences$1<T> = {
|
||||
info: T;
|
||||
node: Rule.Node;
|
||||
path: string[];
|
||||
type: typeof CALL | typeof CONSTRUCT | typeof READ;
|
||||
};
|
||||
type HasSideEffectOptions$1 = {
|
||||
considerGetters?: boolean;
|
||||
considerImplicitTypeConversion?: boolean;
|
||||
};
|
||||
type PunctuatorToken<Value extends string> = AST.Token & {
|
||||
type: "Punctuator";
|
||||
value: Value;
|
||||
};
|
||||
type ArrowToken$1 = PunctuatorToken<"=>">;
|
||||
type CommaToken$1 = PunctuatorToken<",">;
|
||||
type SemicolonToken$1 = PunctuatorToken<";">;
|
||||
type ColonToken$1 = PunctuatorToken<":">;
|
||||
type OpeningParenToken$1 = PunctuatorToken<"(">;
|
||||
type ClosingParenToken$1 = PunctuatorToken<")">;
|
||||
type OpeningBracketToken$1 = PunctuatorToken<"[">;
|
||||
type ClosingBracketToken$1 = PunctuatorToken<"]">;
|
||||
type OpeningBraceToken$1 = PunctuatorToken<"{">;
|
||||
type ClosingBraceToken$1 = PunctuatorToken<"}">;
|
||||
|
||||
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
|
||||
type Scope$1 = eslint.Scope.Scope;
|
||||
type Variable = eslint.Scope.Variable;
|
||||
type Identifier = estree.Identifier;
|
||||
|
||||
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
|
||||
type SourceCode$2 = eslint.SourceCode;
|
||||
type FunctionNode$1 = estree.Function;
|
||||
type SourceLocation = estree.SourceLocation;
|
||||
|
||||
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
|
||||
type FunctionNode = estree.Function;
|
||||
|
||||
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
|
||||
type Scope = eslint.Scope.Scope;
|
||||
type Node$4 = estree.Node;
|
||||
|
||||
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
|
||||
type MemberExpression = estree.MemberExpression;
|
||||
type MethodDefinition = estree.MethodDefinition;
|
||||
type Property = estree.Property;
|
||||
type PropertyDefinition = estree.PropertyDefinition;
|
||||
|
||||
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
|
||||
type StaticValue$1 = StaticValue$2;
|
||||
type Node$3 = estree.Node;
|
||||
|
||||
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
|
||||
type Node$2 = estree.Node;
|
||||
|
||||
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
|
||||
type Node$1 = estree.Node;
|
||||
type SourceCode$1 = eslint.SourceCode;
|
||||
|
||||
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
|
||||
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
|
||||
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
|
||||
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
|
||||
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
|
||||
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
|
||||
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
|
||||
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
|
||||
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
|
||||
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
|
||||
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
|
||||
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotColonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
|
||||
type Token = eslint.AST.Token;
|
||||
type Comment = estree.Comment;
|
||||
type CommentOrToken = Comment | Token;
|
||||
|
||||
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
|
||||
type Node = estree.Node;
|
||||
type SourceCode = eslint.SourceCode;
|
||||
|
||||
declare class PatternMatcher {
|
||||
constructor(pattern: RegExp, options?: {
|
||||
escaped?: boolean | undefined;
|
||||
} | undefined);
|
||||
execAll(str: string): IterableIterator<RegExpExecArray>;
|
||||
test(str: string): boolean;
|
||||
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
|
||||
}
|
||||
|
||||
declare namespace _default {
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
export { findVariable };
|
||||
export { getFunctionHeadLocation };
|
||||
export { getFunctionNameWithKind };
|
||||
export { getInnermostScope };
|
||||
export { getPropertyName };
|
||||
export { getStaticValue };
|
||||
export { getStringIfConstant };
|
||||
export { hasSideEffect };
|
||||
export { isArrowToken };
|
||||
export { isClosingBraceToken };
|
||||
export { isClosingBracketToken };
|
||||
export { isClosingParenToken };
|
||||
export { isColonToken };
|
||||
export { isCommaToken };
|
||||
export { isCommentToken };
|
||||
export { isNotArrowToken };
|
||||
export { isNotClosingBraceToken };
|
||||
export { isNotClosingBracketToken };
|
||||
export { isNotClosingParenToken };
|
||||
export { isNotColonToken };
|
||||
export { isNotCommaToken };
|
||||
export { isNotCommentToken };
|
||||
export { isNotOpeningBraceToken };
|
||||
export { isNotOpeningBracketToken };
|
||||
export { isNotOpeningParenToken };
|
||||
export { isNotSemicolonToken };
|
||||
export { isOpeningBraceToken };
|
||||
export { isOpeningBracketToken };
|
||||
export { isOpeningParenToken };
|
||||
export { isParenthesized };
|
||||
export { isSemicolonToken };
|
||||
export { PatternMatcher };
|
||||
export { READ };
|
||||
export { ReferenceTracker };
|
||||
}
|
||||
|
||||
type StaticValue = StaticValue$2;
|
||||
type StaticValueOptional = StaticValueOptional$1;
|
||||
type StaticValueProvided = StaticValueProvided$1;
|
||||
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
|
||||
type TraceMap<T> = TraceMap$1<T>;
|
||||
type TrackedReferences<T> = TrackedReferences$1<T>;
|
||||
type HasSideEffectOptions = HasSideEffectOptions$1;
|
||||
type ArrowToken = ArrowToken$1;
|
||||
type CommaToken = CommaToken$1;
|
||||
type SemicolonToken = SemicolonToken$1;
|
||||
type ColonToken = ColonToken$1;
|
||||
type OpeningParenToken = OpeningParenToken$1;
|
||||
type ClosingParenToken = ClosingParenToken$1;
|
||||
type OpeningBracketToken = OpeningBracketToken$1;
|
||||
type ClosingBracketToken = ClosingBracketToken$1;
|
||||
type OpeningBraceToken = OpeningBraceToken$1;
|
||||
type ClosingBraceToken = ClosingBraceToken$1;
|
||||
|
||||
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
import * as eslint from 'eslint';
|
||||
import { Rule, AST } from 'eslint';
|
||||
import * as estree from 'estree';
|
||||
|
||||
declare const READ: unique symbol;
|
||||
declare const CALL: unique symbol;
|
||||
declare const CONSTRUCT: unique symbol;
|
||||
declare const ESM: unique symbol;
|
||||
declare class ReferenceTracker {
|
||||
constructor(globalScope: Scope$2, options?: {
|
||||
mode?: "legacy" | "strict" | undefined;
|
||||
globalObjectNames?: string[] | undefined;
|
||||
} | undefined);
|
||||
private variableStack;
|
||||
private globalScope;
|
||||
private mode;
|
||||
private globalObjectNames;
|
||||
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
|
||||
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
|
||||
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
|
||||
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
|
||||
private _iterateVariableReferences;
|
||||
private _iteratePropertyReferences;
|
||||
private _iterateLhsReferences;
|
||||
private _iterateImportReferences;
|
||||
}
|
||||
declare namespace ReferenceTracker {
|
||||
export { READ };
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
}
|
||||
type Scope$2 = eslint.Scope.Scope;
|
||||
type Expression = estree.Expression;
|
||||
type TraceMap$2<T> = TraceMap$1<T>;
|
||||
type TrackedReferences$2<T> = TrackedReferences$1<T>;
|
||||
|
||||
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
|
||||
type StaticValueProvided$1 = {
|
||||
optional?: undefined;
|
||||
value: unknown;
|
||||
};
|
||||
type StaticValueOptional$1 = {
|
||||
optional?: true;
|
||||
value: undefined;
|
||||
};
|
||||
type ReferenceTrackerOptions$1 = {
|
||||
globalObjectNames?: string[];
|
||||
mode?: "legacy" | "strict";
|
||||
};
|
||||
type TraceMap$1<T = unknown> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
};
|
||||
type TraceMapObject<T> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
[CALL]?: T;
|
||||
[CONSTRUCT]?: T;
|
||||
[READ]?: T;
|
||||
[ESM]?: boolean;
|
||||
};
|
||||
type TrackedReferences$1<T> = {
|
||||
info: T;
|
||||
node: Rule.Node;
|
||||
path: string[];
|
||||
type: typeof CALL | typeof CONSTRUCT | typeof READ;
|
||||
};
|
||||
type HasSideEffectOptions$1 = {
|
||||
considerGetters?: boolean;
|
||||
considerImplicitTypeConversion?: boolean;
|
||||
};
|
||||
type PunctuatorToken<Value extends string> = AST.Token & {
|
||||
type: "Punctuator";
|
||||
value: Value;
|
||||
};
|
||||
type ArrowToken$1 = PunctuatorToken<"=>">;
|
||||
type CommaToken$1 = PunctuatorToken<",">;
|
||||
type SemicolonToken$1 = PunctuatorToken<";">;
|
||||
type ColonToken$1 = PunctuatorToken<":">;
|
||||
type OpeningParenToken$1 = PunctuatorToken<"(">;
|
||||
type ClosingParenToken$1 = PunctuatorToken<")">;
|
||||
type OpeningBracketToken$1 = PunctuatorToken<"[">;
|
||||
type ClosingBracketToken$1 = PunctuatorToken<"]">;
|
||||
type OpeningBraceToken$1 = PunctuatorToken<"{">;
|
||||
type ClosingBraceToken$1 = PunctuatorToken<"}">;
|
||||
|
||||
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
|
||||
type Scope$1 = eslint.Scope.Scope;
|
||||
type Variable = eslint.Scope.Variable;
|
||||
type Identifier = estree.Identifier;
|
||||
|
||||
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
|
||||
type SourceCode$2 = eslint.SourceCode;
|
||||
type FunctionNode$1 = estree.Function;
|
||||
type SourceLocation = estree.SourceLocation;
|
||||
|
||||
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
|
||||
type FunctionNode = estree.Function;
|
||||
|
||||
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
|
||||
type Scope = eslint.Scope.Scope;
|
||||
type Node$4 = estree.Node;
|
||||
|
||||
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
|
||||
type MemberExpression = estree.MemberExpression;
|
||||
type MethodDefinition = estree.MethodDefinition;
|
||||
type Property = estree.Property;
|
||||
type PropertyDefinition = estree.PropertyDefinition;
|
||||
|
||||
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
|
||||
type StaticValue$1 = StaticValue$2;
|
||||
type Node$3 = estree.Node;
|
||||
|
||||
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
|
||||
type Node$2 = estree.Node;
|
||||
|
||||
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
|
||||
type Node$1 = estree.Node;
|
||||
type SourceCode$1 = eslint.SourceCode;
|
||||
|
||||
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
|
||||
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
|
||||
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
|
||||
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
|
||||
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
|
||||
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
|
||||
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
|
||||
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
|
||||
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
|
||||
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
|
||||
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
|
||||
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotColonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
|
||||
type Token = eslint.AST.Token;
|
||||
type Comment = estree.Comment;
|
||||
type CommentOrToken = Comment | Token;
|
||||
|
||||
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
|
||||
type Node = estree.Node;
|
||||
type SourceCode = eslint.SourceCode;
|
||||
|
||||
declare class PatternMatcher {
|
||||
constructor(pattern: RegExp, options?: {
|
||||
escaped?: boolean | undefined;
|
||||
} | undefined);
|
||||
execAll(str: string): IterableIterator<RegExpExecArray>;
|
||||
test(str: string): boolean;
|
||||
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
|
||||
}
|
||||
|
||||
declare namespace _default {
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
export { findVariable };
|
||||
export { getFunctionHeadLocation };
|
||||
export { getFunctionNameWithKind };
|
||||
export { getInnermostScope };
|
||||
export { getPropertyName };
|
||||
export { getStaticValue };
|
||||
export { getStringIfConstant };
|
||||
export { hasSideEffect };
|
||||
export { isArrowToken };
|
||||
export { isClosingBraceToken };
|
||||
export { isClosingBracketToken };
|
||||
export { isClosingParenToken };
|
||||
export { isColonToken };
|
||||
export { isCommaToken };
|
||||
export { isCommentToken };
|
||||
export { isNotArrowToken };
|
||||
export { isNotClosingBraceToken };
|
||||
export { isNotClosingBracketToken };
|
||||
export { isNotClosingParenToken };
|
||||
export { isNotColonToken };
|
||||
export { isNotCommaToken };
|
||||
export { isNotCommentToken };
|
||||
export { isNotOpeningBraceToken };
|
||||
export { isNotOpeningBracketToken };
|
||||
export { isNotOpeningParenToken };
|
||||
export { isNotSemicolonToken };
|
||||
export { isOpeningBraceToken };
|
||||
export { isOpeningBracketToken };
|
||||
export { isOpeningParenToken };
|
||||
export { isParenthesized };
|
||||
export { isSemicolonToken };
|
||||
export { PatternMatcher };
|
||||
export { READ };
|
||||
export { ReferenceTracker };
|
||||
}
|
||||
|
||||
type StaticValue = StaticValue$2;
|
||||
type StaticValueOptional = StaticValueOptional$1;
|
||||
type StaticValueProvided = StaticValueProvided$1;
|
||||
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
|
||||
type TraceMap<T> = TraceMap$1<T>;
|
||||
type TrackedReferences<T> = TrackedReferences$1<T>;
|
||||
type HasSideEffectOptions = HasSideEffectOptions$1;
|
||||
type ArrowToken = ArrowToken$1;
|
||||
type CommaToken = CommaToken$1;
|
||||
type SemicolonToken = SemicolonToken$1;
|
||||
type ColonToken = ColonToken$1;
|
||||
type OpeningParenToken = OpeningParenToken$1;
|
||||
type ClosingParenToken = ClosingParenToken$1;
|
||||
type OpeningBracketToken = OpeningBracketToken$1;
|
||||
type ClosingBracketToken = ClosingBracketToken$1;
|
||||
type OpeningBraceToken = OpeningBraceToken$1;
|
||||
type ClosingBraceToken = ClosingBraceToken$1;
|
||||
|
||||
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
+2620
@@ -0,0 +1,2620 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var eslintVisitorKeys = require('eslint-visitor-keys');
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
|
||||
/**
|
||||
* Get the innermost scope which contains a given location.
|
||||
* @param {Scope} initialScope The initial scope to search.
|
||||
* @param {Node} node The location to search.
|
||||
* @returns {Scope} The innermost scope.
|
||||
*/
|
||||
function getInnermostScope(initialScope, node) {
|
||||
const location = /** @type {[number, number]} */ (node.range)[0];
|
||||
|
||||
let scope = initialScope;
|
||||
let found = false;
|
||||
do {
|
||||
found = false;
|
||||
for (const childScope of scope.childScopes) {
|
||||
const range = /** @type {[number, number]} */ (
|
||||
childScope.block.range
|
||||
);
|
||||
|
||||
if (range[0] <= location && location < range[1]) {
|
||||
scope = childScope;
|
||||
found = true;
|
||||
break
|
||||
}
|
||||
}
|
||||
} while (found)
|
||||
|
||||
return scope
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Find the variable of a given name.
|
||||
* @param {Scope} initialScope The scope to start finding.
|
||||
* @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
|
||||
* @returns {Variable|null} The found variable or null.
|
||||
*/
|
||||
function findVariable(initialScope, nameOrNode) {
|
||||
let name = "";
|
||||
/** @type {Scope|null} */
|
||||
let scope = initialScope;
|
||||
|
||||
if (typeof nameOrNode === "string") {
|
||||
name = nameOrNode;
|
||||
} else {
|
||||
name = nameOrNode.name;
|
||||
scope = getInnermostScope(scope, nameOrNode);
|
||||
}
|
||||
|
||||
while (scope != null) {
|
||||
const variable = scope.set.get(name);
|
||||
if (variable != null) {
|
||||
return variable
|
||||
}
|
||||
scope = scope.upper;
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("estree").Comment} Comment */
|
||||
/** @typedef {import("./types.mjs").ArrowToken} ArrowToken */
|
||||
/** @typedef {import("./types.mjs").CommaToken} CommaToken */
|
||||
/** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */
|
||||
/** @typedef {import("./types.mjs").ColonToken} ColonToken */
|
||||
/** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */
|
||||
/** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */
|
||||
/** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */
|
||||
/** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */
|
||||
/** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */
|
||||
/** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */
|
||||
/**
|
||||
* @template {string} Value
|
||||
* @typedef {import("./types.mjs").PunctuatorToken<Value>} PunctuatorToken
|
||||
*/
|
||||
|
||||
/** @typedef {Comment | Token} CommentOrToken */
|
||||
|
||||
/**
|
||||
* Creates the negate function of the given function.
|
||||
* @param {function(CommentOrToken):boolean} f - The function to negate.
|
||||
* @returns {function(CommentOrToken):boolean} Negated function.
|
||||
*/
|
||||
function negate(f) {
|
||||
return (token) => !f(token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a PunctuatorToken with the given value
|
||||
* @template {string} Value
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @param {Value} value - The value to check.
|
||||
* @returns {token is PunctuatorToken<Value>} `true` if the token is a PunctuatorToken with the given value.
|
||||
*/
|
||||
function isPunctuatorTokenWithValue(token, value) {
|
||||
return token.type === "Punctuator" && token.value === value
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an arrow token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ArrowToken} `true` if the token is an arrow token.
|
||||
*/
|
||||
function isArrowToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "=>")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a comma token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is CommaToken} `true` if the token is a comma token.
|
||||
*/
|
||||
function isCommaToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ",")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a semicolon token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is SemicolonToken} `true` if the token is a semicolon token.
|
||||
*/
|
||||
function isSemicolonToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ";")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a colon token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ColonToken} `true` if the token is a colon token.
|
||||
*/
|
||||
function isColonToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ":")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening parenthesis token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.
|
||||
*/
|
||||
function isOpeningParenToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "(")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing parenthesis token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.
|
||||
*/
|
||||
function isClosingParenToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ")")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening square bracket token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.
|
||||
*/
|
||||
function isOpeningBracketToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "[")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing square bracket token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.
|
||||
*/
|
||||
function isClosingBracketToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "]")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening brace token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.
|
||||
*/
|
||||
function isOpeningBraceToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "{")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing brace token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.
|
||||
*/
|
||||
function isClosingBraceToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a comment token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is Comment} `true` if the token is a comment token.
|
||||
*/
|
||||
function isCommentToken(token) {
|
||||
return ["Block", "Line", "Shebang"].includes(token.type)
|
||||
}
|
||||
|
||||
const isNotArrowToken = negate(isArrowToken);
|
||||
const isNotCommaToken = negate(isCommaToken);
|
||||
const isNotSemicolonToken = negate(isSemicolonToken);
|
||||
const isNotColonToken = negate(isColonToken);
|
||||
const isNotOpeningParenToken = negate(isOpeningParenToken);
|
||||
const isNotClosingParenToken = negate(isClosingParenToken);
|
||||
const isNotOpeningBracketToken = negate(isOpeningBracketToken);
|
||||
const isNotClosingBracketToken = negate(isClosingBracketToken);
|
||||
const isNotOpeningBraceToken = negate(isOpeningBraceToken);
|
||||
const isNotClosingBraceToken = negate(isClosingBraceToken);
|
||||
const isNotCommentToken = negate(isCommentToken);
|
||||
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("estree").Function} FunctionNode */
|
||||
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
|
||||
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
|
||||
/** @typedef {import("estree").SourceLocation} SourceLocation */
|
||||
/** @typedef {import("estree").Position} Position */
|
||||
|
||||
/**
|
||||
* Get the `(` token of the given function node.
|
||||
* @param {FunctionExpression | FunctionDeclaration} node - The function node to get.
|
||||
* @param {SourceCode} sourceCode - The source code object to get tokens.
|
||||
* @returns {Token} `(` token.
|
||||
*/
|
||||
function getOpeningParenOfParams(node, sourceCode) {
|
||||
return node.id
|
||||
? /** @type {Token} */ (
|
||||
sourceCode.getTokenAfter(node.id, isOpeningParenToken)
|
||||
)
|
||||
: /** @type {Token} */ (
|
||||
sourceCode.getFirstToken(node, isOpeningParenToken)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the location of the given function node for reporting.
|
||||
* @param {FunctionNode} node - The function node to get.
|
||||
* @param {SourceCode} sourceCode - The source code object to get tokens.
|
||||
* @returns {SourceLocation|null} The location of the function node for reporting.
|
||||
*/
|
||||
function getFunctionHeadLocation(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
/** @type {Position|null} */
|
||||
let start = null;
|
||||
/** @type {Position|null} */
|
||||
let end = null;
|
||||
|
||||
if (node.type === "ArrowFunctionExpression") {
|
||||
const arrowToken = /** @type {Token} */ (
|
||||
sourceCode.getTokenBefore(node.body, isArrowToken)
|
||||
);
|
||||
|
||||
start = arrowToken.loc.start;
|
||||
end = arrowToken.loc.end;
|
||||
} else if (
|
||||
parent &&
|
||||
(parent.type === "Property" ||
|
||||
parent.type === "MethodDefinition" ||
|
||||
parent.type === "PropertyDefinition")
|
||||
) {
|
||||
start = /** @type {SourceLocation} */ (parent.loc).start;
|
||||
end = getOpeningParenOfParams(node, sourceCode).loc.start;
|
||||
} else {
|
||||
start = /** @type {SourceLocation} */ (node.loc).start;
|
||||
end = getOpeningParenOfParams(node, sourceCode).loc.start;
|
||||
}
|
||||
|
||||
return {
|
||||
start: { ...start },
|
||||
end: { ...end },
|
||||
}
|
||||
}
|
||||
|
||||
/* globals globalThis, global, self, window */
|
||||
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */
|
||||
|
||||
const globalObject =
|
||||
typeof globalThis !== "undefined"
|
||||
? globalThis
|
||||
: // @ts-ignore
|
||||
typeof self !== "undefined"
|
||||
? // @ts-ignore
|
||||
self
|
||||
: // @ts-ignore
|
||||
typeof window !== "undefined"
|
||||
? // @ts-ignore
|
||||
window
|
||||
: typeof global !== "undefined"
|
||||
? global
|
||||
: {};
|
||||
|
||||
const builtinNames = Object.freeze(
|
||||
new Set([
|
||||
"Array",
|
||||
"ArrayBuffer",
|
||||
"BigInt",
|
||||
"BigInt64Array",
|
||||
"BigUint64Array",
|
||||
"Boolean",
|
||||
"DataView",
|
||||
"Date",
|
||||
"decodeURI",
|
||||
"decodeURIComponent",
|
||||
"encodeURI",
|
||||
"encodeURIComponent",
|
||||
"escape",
|
||||
"Float32Array",
|
||||
"Float64Array",
|
||||
"Function",
|
||||
"Infinity",
|
||||
"Int16Array",
|
||||
"Int32Array",
|
||||
"Int8Array",
|
||||
"isFinite",
|
||||
"isNaN",
|
||||
"isPrototypeOf",
|
||||
"JSON",
|
||||
"Map",
|
||||
"Math",
|
||||
"NaN",
|
||||
"Number",
|
||||
"Object",
|
||||
"parseFloat",
|
||||
"parseInt",
|
||||
"Promise",
|
||||
"Proxy",
|
||||
"Reflect",
|
||||
"RegExp",
|
||||
"Set",
|
||||
"String",
|
||||
"Symbol",
|
||||
"Uint16Array",
|
||||
"Uint32Array",
|
||||
"Uint8Array",
|
||||
"Uint8ClampedArray",
|
||||
"undefined",
|
||||
"unescape",
|
||||
"WeakMap",
|
||||
"WeakSet",
|
||||
]),
|
||||
);
|
||||
const callAllowed = new Set(
|
||||
[
|
||||
Array.isArray,
|
||||
Array.of,
|
||||
Array.prototype.at,
|
||||
Array.prototype.concat,
|
||||
Array.prototype.entries,
|
||||
Array.prototype.every,
|
||||
Array.prototype.filter,
|
||||
Array.prototype.find,
|
||||
Array.prototype.findIndex,
|
||||
Array.prototype.flat,
|
||||
Array.prototype.includes,
|
||||
Array.prototype.indexOf,
|
||||
Array.prototype.join,
|
||||
Array.prototype.keys,
|
||||
Array.prototype.lastIndexOf,
|
||||
Array.prototype.slice,
|
||||
Array.prototype.some,
|
||||
Array.prototype.toString,
|
||||
Array.prototype.values,
|
||||
typeof BigInt === "function" ? BigInt : undefined,
|
||||
Boolean,
|
||||
Date,
|
||||
Date.parse,
|
||||
decodeURI,
|
||||
decodeURIComponent,
|
||||
encodeURI,
|
||||
encodeURIComponent,
|
||||
escape,
|
||||
isFinite,
|
||||
isNaN,
|
||||
// @ts-ignore
|
||||
isPrototypeOf,
|
||||
Map,
|
||||
Map.prototype.entries,
|
||||
Map.prototype.get,
|
||||
Map.prototype.has,
|
||||
Map.prototype.keys,
|
||||
Map.prototype.values,
|
||||
.../** @type {(keyof typeof Math)[]} */ (
|
||||
Object.getOwnPropertyNames(Math)
|
||||
)
|
||||
.filter((k) => k !== "random")
|
||||
.map((k) => Math[k])
|
||||
.filter((f) => typeof f === "function"),
|
||||
Number,
|
||||
Number.isFinite,
|
||||
Number.isNaN,
|
||||
Number.parseFloat,
|
||||
Number.parseInt,
|
||||
Number.prototype.toExponential,
|
||||
Number.prototype.toFixed,
|
||||
Number.prototype.toPrecision,
|
||||
Number.prototype.toString,
|
||||
Object,
|
||||
Object.entries,
|
||||
Object.is,
|
||||
Object.isExtensible,
|
||||
Object.isFrozen,
|
||||
Object.isSealed,
|
||||
Object.keys,
|
||||
Object.values,
|
||||
parseFloat,
|
||||
parseInt,
|
||||
RegExp,
|
||||
Set,
|
||||
Set.prototype.entries,
|
||||
Set.prototype.has,
|
||||
Set.prototype.keys,
|
||||
Set.prototype.values,
|
||||
String,
|
||||
String.fromCharCode,
|
||||
String.fromCodePoint,
|
||||
String.raw,
|
||||
String.prototype.at,
|
||||
String.prototype.charAt,
|
||||
String.prototype.charCodeAt,
|
||||
String.prototype.codePointAt,
|
||||
String.prototype.concat,
|
||||
String.prototype.endsWith,
|
||||
String.prototype.includes,
|
||||
String.prototype.indexOf,
|
||||
String.prototype.lastIndexOf,
|
||||
String.prototype.normalize,
|
||||
String.prototype.padEnd,
|
||||
String.prototype.padStart,
|
||||
String.prototype.slice,
|
||||
String.prototype.startsWith,
|
||||
String.prototype.substr,
|
||||
String.prototype.substring,
|
||||
String.prototype.toLowerCase,
|
||||
String.prototype.toString,
|
||||
String.prototype.toUpperCase,
|
||||
String.prototype.trim,
|
||||
String.prototype.trimEnd,
|
||||
String.prototype.trimLeft,
|
||||
String.prototype.trimRight,
|
||||
String.prototype.trimStart,
|
||||
Symbol.for,
|
||||
Symbol.keyFor,
|
||||
unescape,
|
||||
].filter((f) => typeof f === "function"),
|
||||
);
|
||||
const callPassThrough = new Set([
|
||||
Object.freeze,
|
||||
Object.preventExtensions,
|
||||
Object.seal,
|
||||
]);
|
||||
|
||||
/** @type {ReadonlyArray<readonly [Function, ReadonlySet<string>]>} */
|
||||
const getterAllowed = [
|
||||
[Map, new Set(["size"])],
|
||||
[
|
||||
RegExp,
|
||||
new Set([
|
||||
"dotAll",
|
||||
"flags",
|
||||
"global",
|
||||
"hasIndices",
|
||||
"ignoreCase",
|
||||
"multiline",
|
||||
"source",
|
||||
"sticky",
|
||||
"unicode",
|
||||
]),
|
||||
],
|
||||
[Set, new Set(["size"])],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the property descriptor.
|
||||
* @param {object} object The object to get.
|
||||
* @param {string|number|symbol} name The property name to get.
|
||||
*/
|
||||
function getPropertyDescriptor(object, name) {
|
||||
let x = object;
|
||||
while ((typeof x === "object" || typeof x === "function") && x !== null) {
|
||||
const d = Object.getOwnPropertyDescriptor(x, name);
|
||||
if (d) {
|
||||
return d
|
||||
}
|
||||
x = Object.getPrototypeOf(x);
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a property is getter or not.
|
||||
* @param {object} object The object to check.
|
||||
* @param {string|number|symbol} name The property name to check.
|
||||
*/
|
||||
function isGetter(object, name) {
|
||||
const d = getPropertyDescriptor(object, name);
|
||||
return d != null && d.get != null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the element values of a given node list.
|
||||
* @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.
|
||||
* @param {Scope|undefined|null} initialScope The initial scope to find variables.
|
||||
* @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
|
||||
*/
|
||||
function getElementValues(nodeList, initialScope) {
|
||||
const valueList = [];
|
||||
|
||||
for (let i = 0; i < nodeList.length; ++i) {
|
||||
const elementNode = nodeList[i];
|
||||
|
||||
if (elementNode == null) {
|
||||
valueList.length = i + 1;
|
||||
} else if (elementNode.type === "SpreadElement") {
|
||||
const argument = getStaticValueR(elementNode.argument, initialScope);
|
||||
if (argument == null) {
|
||||
return null
|
||||
}
|
||||
valueList.push(.../** @type {Iterable<any>} */ (argument.value));
|
||||
} else {
|
||||
const element = getStaticValueR(elementNode, initialScope);
|
||||
if (element == null) {
|
||||
return null
|
||||
}
|
||||
valueList.push(element.value);
|
||||
}
|
||||
}
|
||||
|
||||
return valueList
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable is a built-in global.
|
||||
* @param {Variable|null} variable The variable to check.
|
||||
* @returns {variable is Variable & {defs:[]}}
|
||||
*/
|
||||
function isBuiltinGlobal(variable) {
|
||||
return (
|
||||
variable != null &&
|
||||
variable.defs.length === 0 &&
|
||||
builtinNames.has(variable.name) &&
|
||||
variable.name in globalObject
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable can be considered as a constant.
|
||||
* @param {Variable} variable
|
||||
* @returns {variable is Variable & {defs: [import("eslint").Scope.Definition & { type: "Variable" }]}} True if the variable can be considered as a constant.
|
||||
*/
|
||||
function canBeConsideredConst(variable) {
|
||||
if (variable.defs.length !== 1) {
|
||||
return false
|
||||
}
|
||||
const def = variable.defs[0];
|
||||
return Boolean(
|
||||
def.parent &&
|
||||
def.type === "Variable" &&
|
||||
(def.parent.kind === "const" || isEffectivelyConst(variable)),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the given variable is never written to after initialization.
|
||||
* @param {Variable} variable
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isEffectivelyConst(variable) {
|
||||
const refs = variable.references;
|
||||
|
||||
const inits = refs.filter((r) => r.init).length;
|
||||
const reads = refs.filter((r) => r.isReadOnly()).length;
|
||||
if (inits === 1 && reads + inits === refs.length) {
|
||||
// there is only one init and all other references only read
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable has mutation in its property.
|
||||
* @param {Variable} variable The variable to check.
|
||||
* @param {Scope|null} initialScope The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {boolean} True if the variable has mutation in its property.
|
||||
*/
|
||||
function hasMutationInProperty(variable, initialScope) {
|
||||
for (const ref of variable.references) {
|
||||
let node = /** @type {TSESTreeNode} */ (ref.identifier);
|
||||
while (node && node.parent && node.parent.type === "MemberExpression") {
|
||||
node = node.parent;
|
||||
}
|
||||
if (!node || !node.parent) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
(node.parent.type === "AssignmentExpression" &&
|
||||
node.parent.left === node) ||
|
||||
(node.parent.type === "UpdateExpression" &&
|
||||
node.parent.argument === node)
|
||||
) {
|
||||
// This is a mutation.
|
||||
return true
|
||||
}
|
||||
if (
|
||||
node.parent.type === "CallExpression" &&
|
||||
node.parent.callee === node &&
|
||||
node.type === "MemberExpression"
|
||||
) {
|
||||
const methodName = getStaticPropertyNameValue(node, initialScope);
|
||||
if (isNameOfMutationArrayMethod(methodName)) {
|
||||
// This is a mutation.
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
/**
|
||||
* Checks if a method name is one of the mutation array methods.
|
||||
* @param {StaticValue|null} methodName The method name to check.
|
||||
* @returns {boolean} True if the method name is a mutation array method.
|
||||
*/
|
||||
function isNameOfMutationArrayMethod(methodName) {
|
||||
if (methodName == null || methodName.value == null) {
|
||||
return false
|
||||
}
|
||||
const name = methodName.value;
|
||||
return (
|
||||
name === "copyWithin" ||
|
||||
name === "fill" ||
|
||||
name === "pop" ||
|
||||
name === "push" ||
|
||||
name === "reverse" ||
|
||||
name === "shift" ||
|
||||
name === "sort" ||
|
||||
name === "splice" ||
|
||||
name === "unshift"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {TSESTreeNodeTypes} T
|
||||
* @callback VisitorCallback
|
||||
* @param {TSESTreeNode & { type: T }} node
|
||||
* @param {Scope|undefined|null} initialScope
|
||||
* @returns {StaticValue | null}
|
||||
*/
|
||||
/**
|
||||
* @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback<K> } } Operations
|
||||
*/
|
||||
/**
|
||||
* @type {Operations}
|
||||
*/
|
||||
const operations = Object.freeze({
|
||||
ArrayExpression(node, initialScope) {
|
||||
const elements = getElementValues(node.elements, initialScope);
|
||||
return elements != null ? { value: elements } : null
|
||||
},
|
||||
|
||||
AssignmentExpression(node, initialScope) {
|
||||
if (node.operator === "=") {
|
||||
return getStaticValueR(node.right, initialScope)
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
//eslint-disable-next-line complexity
|
||||
BinaryExpression(node, initialScope) {
|
||||
if (node.operator === "in" || node.operator === "instanceof") {
|
||||
// Not supported.
|
||||
return null
|
||||
}
|
||||
|
||||
const left = getStaticValueR(node.left, initialScope);
|
||||
const right = getStaticValueR(node.right, initialScope);
|
||||
if (left != null && right != null) {
|
||||
switch (node.operator) {
|
||||
case "==":
|
||||
return { value: left.value == right.value } //eslint-disable-line eqeqeq
|
||||
case "!=":
|
||||
return { value: left.value != right.value } //eslint-disable-line eqeqeq
|
||||
case "===":
|
||||
return { value: left.value === right.value }
|
||||
case "!==":
|
||||
return { value: left.value !== right.value }
|
||||
case "<":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "<=":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <=
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">=":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >=
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "<<":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <<
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">>":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >>
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">>>":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >>>
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "+":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) +
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "-":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) -
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "*":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) *
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "/":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) /
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "%":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) %
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "**":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) **
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "|":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) |
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "^":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) ^
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "&":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) &
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
|
||||
// no default
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
CallExpression(node, initialScope) {
|
||||
const calleeNode = node.callee;
|
||||
const args = getElementValues(node.arguments, initialScope);
|
||||
|
||||
if (args != null) {
|
||||
if (calleeNode.type === "MemberExpression") {
|
||||
if (calleeNode.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
const object = getStaticValueR(calleeNode.object, initialScope);
|
||||
if (object != null) {
|
||||
if (
|
||||
object.value == null &&
|
||||
(object.optional || node.optional)
|
||||
) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const property = getStaticPropertyNameValue(
|
||||
calleeNode,
|
||||
initialScope,
|
||||
);
|
||||
|
||||
if (property != null) {
|
||||
const receiver =
|
||||
/** @type {Record<PropertyKey, (...args: any[]) => any>} */ (
|
||||
object.value
|
||||
);
|
||||
const methodName = /** @type {PropertyKey} */ (
|
||||
property.value
|
||||
);
|
||||
if (callAllowed.has(receiver[methodName])) {
|
||||
return {
|
||||
value: receiver[methodName](...args),
|
||||
}
|
||||
}
|
||||
if (callPassThrough.has(receiver[methodName])) {
|
||||
return { value: args[0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const callee = getStaticValueR(calleeNode, initialScope);
|
||||
if (callee != null) {
|
||||
if (callee.value == null && node.optional) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const func = /** @type {(...args: any[]) => any} */ (
|
||||
callee.value
|
||||
);
|
||||
if (callAllowed.has(func)) {
|
||||
return { value: func(...args) }
|
||||
}
|
||||
if (callPassThrough.has(func)) {
|
||||
return { value: args[0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
ConditionalExpression(node, initialScope) {
|
||||
const test = getStaticValueR(node.test, initialScope);
|
||||
if (test != null) {
|
||||
return test.value
|
||||
? getStaticValueR(node.consequent, initialScope)
|
||||
: getStaticValueR(node.alternate, initialScope)
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
ExpressionStatement(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
|
||||
Identifier(node, initialScope) {
|
||||
if (initialScope != null) {
|
||||
const variable = findVariable(initialScope, node);
|
||||
|
||||
if (variable != null) {
|
||||
// Built-in globals.
|
||||
if (isBuiltinGlobal(variable)) {
|
||||
return { value: globalObject[variable.name] }
|
||||
}
|
||||
|
||||
// Constants.
|
||||
if (canBeConsideredConst(variable)) {
|
||||
const def = variable.defs[0];
|
||||
if (
|
||||
// TODO(mysticatea): don't support destructuring here.
|
||||
def.node.id.type === "Identifier"
|
||||
) {
|
||||
const init = getStaticValueR(
|
||||
def.node.init,
|
||||
initialScope,
|
||||
);
|
||||
if (
|
||||
init &&
|
||||
typeof init.value === "object" &&
|
||||
init.value !== null
|
||||
) {
|
||||
if (hasMutationInProperty(variable, initialScope)) {
|
||||
// This variable has mutation in its property.
|
||||
return null
|
||||
}
|
||||
}
|
||||
return init
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
Literal(node) {
|
||||
const literal =
|
||||
/** @type {Partial<Literal> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
|
||||
node
|
||||
);
|
||||
//istanbul ignore if : this is implementation-specific behavior.
|
||||
if (
|
||||
(literal.regex != null || literal.bigint != null) &&
|
||||
literal.value == null
|
||||
) {
|
||||
// It was a RegExp/BigInt literal, but Node.js didn't support it.
|
||||
return null
|
||||
}
|
||||
return { value: literal.value }
|
||||
},
|
||||
|
||||
LogicalExpression(node, initialScope) {
|
||||
const left = getStaticValueR(node.left, initialScope);
|
||||
if (left != null) {
|
||||
if (
|
||||
(node.operator === "||" && Boolean(left.value) === true) ||
|
||||
(node.operator === "&&" && Boolean(left.value) === false) ||
|
||||
(node.operator === "??" && left.value != null)
|
||||
) {
|
||||
return left
|
||||
}
|
||||
|
||||
const right = getStaticValueR(node.right, initialScope);
|
||||
if (right != null) {
|
||||
return right
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
MemberExpression(node, initialScope) {
|
||||
if (node.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
const object = getStaticValueR(node.object, initialScope);
|
||||
if (object != null) {
|
||||
if (object.value == null && (object.optional || node.optional)) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const property = getStaticPropertyNameValue(node, initialScope);
|
||||
|
||||
if (property != null) {
|
||||
if (
|
||||
!isGetter(
|
||||
/** @type {object} */ (object.value),
|
||||
/** @type {PropertyKey} */ (property.value),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
value: /** @type {Record<PropertyKey, unknown>} */ (
|
||||
object.value
|
||||
)[/** @type {PropertyKey} */ (property.value)],
|
||||
}
|
||||
}
|
||||
|
||||
for (const [classFn, allowed] of getterAllowed) {
|
||||
if (
|
||||
object.value instanceof classFn &&
|
||||
allowed.has(/** @type {string} */ (property.value))
|
||||
) {
|
||||
return {
|
||||
value: /** @type {Record<PropertyKey, unknown>} */ (
|
||||
object.value
|
||||
)[/** @type {PropertyKey} */ (property.value)],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
ChainExpression(node, initialScope) {
|
||||
const expression = getStaticValueR(node.expression, initialScope);
|
||||
if (expression != null) {
|
||||
return { value: expression.value }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
NewExpression(node, initialScope) {
|
||||
const callee = getStaticValueR(node.callee, initialScope);
|
||||
const args = getElementValues(node.arguments, initialScope);
|
||||
|
||||
if (callee != null && args != null) {
|
||||
const Func = /** @type {new (...args: any[]) => any} */ (
|
||||
callee.value
|
||||
);
|
||||
if (callAllowed.has(Func)) {
|
||||
return { value: new Func(...args) }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
ObjectExpression(node, initialScope) {
|
||||
/** @type {Record<PropertyKey, unknown>} */
|
||||
const object = {};
|
||||
|
||||
for (const propertyNode of node.properties) {
|
||||
if (propertyNode.type === "Property") {
|
||||
if (propertyNode.kind !== "init") {
|
||||
return null
|
||||
}
|
||||
const key = getStaticPropertyNameValue(
|
||||
propertyNode,
|
||||
initialScope,
|
||||
);
|
||||
const value = getStaticValueR(propertyNode.value, initialScope);
|
||||
if (key == null || value == null) {
|
||||
return null
|
||||
}
|
||||
object[/** @type {PropertyKey} */ (key.value)] = value.value;
|
||||
} else if (
|
||||
propertyNode.type === "SpreadElement" ||
|
||||
// @ts-expect-error -- Backward compatibility
|
||||
propertyNode.type === "ExperimentalSpreadProperty"
|
||||
) {
|
||||
const argument = getStaticValueR(
|
||||
propertyNode.argument,
|
||||
initialScope,
|
||||
);
|
||||
if (argument == null) {
|
||||
return null
|
||||
}
|
||||
Object.assign(object, argument.value);
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return { value: object }
|
||||
},
|
||||
|
||||
SequenceExpression(node, initialScope) {
|
||||
const last = node.expressions[node.expressions.length - 1];
|
||||
return getStaticValueR(last, initialScope)
|
||||
},
|
||||
|
||||
TaggedTemplateExpression(node, initialScope) {
|
||||
const tag = getStaticValueR(node.tag, initialScope);
|
||||
const expressions = getElementValues(
|
||||
node.quasi.expressions,
|
||||
initialScope,
|
||||
);
|
||||
|
||||
if (tag != null && expressions != null) {
|
||||
const func = /** @type {(...args: any[]) => any} */ (tag.value);
|
||||
/** @type {any[] & { raw?: string[] }} */
|
||||
const strings = node.quasi.quasis.map((q) => q.value.cooked);
|
||||
strings.raw = node.quasi.quasis.map((q) => q.value.raw);
|
||||
|
||||
if (func === String.raw) {
|
||||
return { value: func(strings, ...expressions) }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
TemplateLiteral(node, initialScope) {
|
||||
const expressions = getElementValues(node.expressions, initialScope);
|
||||
if (expressions != null) {
|
||||
let value = node.quasis[0].value.cooked;
|
||||
for (let i = 0; i < expressions.length; ++i) {
|
||||
value += expressions[i];
|
||||
value += /** @type {string} */ (node.quasis[i + 1].value.cooked);
|
||||
}
|
||||
return { value }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
UnaryExpression(node, initialScope) {
|
||||
if (node.operator === "delete") {
|
||||
// Not supported.
|
||||
return null
|
||||
}
|
||||
if (node.operator === "void") {
|
||||
return { value: undefined }
|
||||
}
|
||||
|
||||
const arg = getStaticValueR(node.argument, initialScope);
|
||||
if (arg != null) {
|
||||
switch (node.operator) {
|
||||
case "-":
|
||||
return { value: -(/** @type {any} */ (arg.value)) }
|
||||
case "+":
|
||||
return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion
|
||||
case "!":
|
||||
return { value: !arg.value }
|
||||
case "~":
|
||||
return { value: ~(/** @type {any} */ (arg.value)) }
|
||||
case "typeof":
|
||||
return { value: typeof arg.value }
|
||||
|
||||
// no default
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
TSAsExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSSatisfiesExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSTypeAssertion(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSNonNullExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSInstantiationExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a static value.
|
||||
* @param {Node|TSESTreeNode|null|undefined} node The node to get.
|
||||
* @param {Scope|undefined|null} initialScope The scope to start finding variable.
|
||||
* @returns {StaticValue|null} The static value of the node, or `null`.
|
||||
*/
|
||||
function getStaticValueR(node, initialScope) {
|
||||
if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
|
||||
return /** @type {VisitorCallback<any>} */ (operations[node.type])(
|
||||
/** @type {TSESTreeNode} */ (node),
|
||||
initialScope,
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the static value of property name from a MemberExpression node or a Property node.
|
||||
* @param {MemberExpression|Property} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {StaticValue|null} The static value of the property name of the node, or `null`.
|
||||
*/
|
||||
function getStaticPropertyNameValue(node, initialScope) {
|
||||
const nameNode = node.type === "Property" ? node.key : node.property;
|
||||
|
||||
if (node.computed) {
|
||||
return getStaticValueR(nameNode, initialScope)
|
||||
}
|
||||
|
||||
if (nameNode.type === "Identifier") {
|
||||
return { value: nameNode.name }
|
||||
}
|
||||
|
||||
if (nameNode.type === "Literal") {
|
||||
if (/** @type {Partial<BigIntLiteral>} */ (nameNode).bigint) {
|
||||
return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }
|
||||
}
|
||||
return { value: String(nameNode.value) }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a static value.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
|
||||
* @returns {StaticValue | null} The static value of the node, or `null`.
|
||||
*/
|
||||
function getStaticValue(node, initialScope = null) {
|
||||
try {
|
||||
return getStaticValueR(node, initialScope)
|
||||
} catch (_error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("estree").RegExpLiteral} RegExpLiteral */
|
||||
/** @typedef {import("estree").BigIntLiteral} BigIntLiteral */
|
||||
/** @typedef {import("estree").SimpleLiteral} SimpleLiteral */
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a literal or a template literal.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
|
||||
* @returns {string|null} The value of the node, or `null`.
|
||||
*/
|
||||
function getStringIfConstant(node, initialScope = null) {
|
||||
// Handle the literals that the platform doesn't support natively.
|
||||
if (node && node.type === "Literal" && node.value === null) {
|
||||
const literal =
|
||||
/** @type {Partial<SimpleLiteral> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
|
||||
node
|
||||
);
|
||||
if (literal.regex) {
|
||||
return `/${literal.regex.pattern}/${literal.regex.flags}`
|
||||
}
|
||||
if (literal.bigint) {
|
||||
return literal.bigint
|
||||
}
|
||||
}
|
||||
|
||||
const evaluated = getStaticValue(node, initialScope);
|
||||
|
||||
if (evaluated) {
|
||||
// `String(Symbol.prototype)` throws error
|
||||
try {
|
||||
return String(evaluated.value)
|
||||
} catch {
|
||||
// No op
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").MemberExpression} MemberExpression */
|
||||
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Get the property name from a MemberExpression node or a Property node.
|
||||
* @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.
|
||||
* @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {string|null|undefined} The property name of the node.
|
||||
*/
|
||||
function getPropertyName(node, initialScope) {
|
||||
switch (node.type) {
|
||||
case "MemberExpression":
|
||||
if (node.computed) {
|
||||
return getStringIfConstant(node.property, initialScope)
|
||||
}
|
||||
if (node.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
return /** @type {Partial<Identifier>} */ (node.property).name
|
||||
|
||||
case "Property":
|
||||
case "MethodDefinition":
|
||||
case "PropertyDefinition":
|
||||
if (node.computed) {
|
||||
return getStringIfConstant(node.key, initialScope)
|
||||
}
|
||||
if (node.key.type === "Literal") {
|
||||
return String(node.key.value)
|
||||
}
|
||||
if (node.key.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
return /** @type {Partial<Identifier>} */ (node.key).name
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("estree").Function} FunctionNode */
|
||||
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
|
||||
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Get the name and kind of the given function node.
|
||||
* @param {FunctionNode} node - The function node to get.
|
||||
* @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
|
||||
* @returns {string} The name and kind of the function node.
|
||||
*/
|
||||
// eslint-disable-next-line complexity
|
||||
function getFunctionNameWithKind(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
if (!parent) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const tokens = [];
|
||||
const isObjectMethod = parent.type === "Property" && parent.value === node;
|
||||
const isClassMethod =
|
||||
parent.type === "MethodDefinition" && parent.value === node;
|
||||
const isClassFieldMethod =
|
||||
parent.type === "PropertyDefinition" && parent.value === node;
|
||||
|
||||
// Modifiers.
|
||||
if (isClassMethod || isClassFieldMethod) {
|
||||
if (parent.static) {
|
||||
tokens.push("static");
|
||||
}
|
||||
if (parent.key.type === "PrivateIdentifier") {
|
||||
tokens.push("private");
|
||||
}
|
||||
}
|
||||
if (node.async) {
|
||||
tokens.push("async");
|
||||
}
|
||||
if (node.generator) {
|
||||
tokens.push("generator");
|
||||
}
|
||||
|
||||
// Kinds.
|
||||
if (isObjectMethod || isClassMethod) {
|
||||
if (parent.kind === "constructor") {
|
||||
return "constructor"
|
||||
}
|
||||
if (parent.kind === "get") {
|
||||
tokens.push("getter");
|
||||
} else if (parent.kind === "set") {
|
||||
tokens.push("setter");
|
||||
} else {
|
||||
tokens.push("method");
|
||||
}
|
||||
} else if (isClassFieldMethod) {
|
||||
tokens.push("method");
|
||||
} else {
|
||||
if (node.type === "ArrowFunctionExpression") {
|
||||
tokens.push("arrow");
|
||||
}
|
||||
tokens.push("function");
|
||||
}
|
||||
|
||||
// Names.
|
||||
if (isObjectMethod || isClassMethod || isClassFieldMethod) {
|
||||
if (parent.key.type === "PrivateIdentifier") {
|
||||
tokens.push(`#${parent.key.name}`);
|
||||
} else {
|
||||
const name = getPropertyName(parent);
|
||||
if (name) {
|
||||
tokens.push(`'${name}'`);
|
||||
} else if (sourceCode) {
|
||||
const keyText = sourceCode.getText(parent.key);
|
||||
if (!keyText.includes("\n")) {
|
||||
tokens.push(`[${keyText}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (hasId(node)) {
|
||||
tokens.push(`'${node.id.name}'`);
|
||||
} else if (
|
||||
parent.type === "VariableDeclarator" &&
|
||||
parent.id &&
|
||||
parent.id.type === "Identifier"
|
||||
) {
|
||||
tokens.push(`'${parent.id.name}'`);
|
||||
} else if (
|
||||
(parent.type === "AssignmentExpression" ||
|
||||
parent.type === "AssignmentPattern") &&
|
||||
parent.left &&
|
||||
parent.left.type === "Identifier"
|
||||
) {
|
||||
tokens.push(`'${parent.left.name}'`);
|
||||
} else if (
|
||||
parent.type === "ExportDefaultDeclaration" &&
|
||||
parent.declaration === node
|
||||
) {
|
||||
tokens.push("'default'");
|
||||
}
|
||||
|
||||
return tokens.join(" ")
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FunctionNode} node
|
||||
* @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}
|
||||
*/
|
||||
function hasId(node) {
|
||||
return Boolean(
|
||||
/** @type {Partial<FunctionDeclaration | FunctionExpression>} */ (node)
|
||||
.id,
|
||||
)
|
||||
}
|
||||
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */
|
||||
/** @typedef {import("estree").BinaryExpression} BinaryExpression */
|
||||
/** @typedef {import("estree").MemberExpression} MemberExpression */
|
||||
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
|
||||
/** @typedef {import("estree").UnaryExpression} UnaryExpression */
|
||||
|
||||
const typeConversionBinaryOps = Object.freeze(
|
||||
new Set([
|
||||
"==",
|
||||
"!=",
|
||||
"<",
|
||||
"<=",
|
||||
">",
|
||||
">=",
|
||||
"<<",
|
||||
">>",
|
||||
">>>",
|
||||
"+",
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"%",
|
||||
"|",
|
||||
"^",
|
||||
"&",
|
||||
"in",
|
||||
]),
|
||||
);
|
||||
const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
|
||||
|
||||
/**
|
||||
* Check whether the given value is an ASTNode or not.
|
||||
* @param {any} x The value to check.
|
||||
* @returns {x is Node} `true` if the value is an ASTNode.
|
||||
*/
|
||||
function isNode(x) {
|
||||
return x !== null && typeof x === "object" && typeof x.type === "string"
|
||||
}
|
||||
|
||||
const visitor = Object.freeze(
|
||||
Object.assign(Object.create(null), {
|
||||
/**
|
||||
* @param {Node} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
$visit(node, options, visitorKeys) {
|
||||
const { type } = node;
|
||||
|
||||
if (typeof (/** @type {any} */ (this)[type]) === "function") {
|
||||
return /** @type {any} */ (this)[type](
|
||||
node,
|
||||
options,
|
||||
visitorKeys,
|
||||
)
|
||||
}
|
||||
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {Node} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
$visitChildren(node, options, visitorKeys) {
|
||||
const { type } = node;
|
||||
|
||||
for (const key of /** @type {(keyof Node)[]} */ (
|
||||
visitorKeys[type] || eslintVisitorKeys.getKeys(node)
|
||||
)) {
|
||||
const value = node[key];
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const element of value) {
|
||||
if (
|
||||
isNode(element) &&
|
||||
this.$visit(element, options, visitorKeys)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
isNode(value) &&
|
||||
this.$visit(value, options, visitorKeys)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
|
||||
ArrowFunctionExpression() {
|
||||
return false
|
||||
},
|
||||
AssignmentExpression() {
|
||||
return true
|
||||
},
|
||||
AwaitExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {BinaryExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
BinaryExpression(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
typeConversionBinaryOps.has(node.operator) &&
|
||||
(node.left.type !== "Literal" || node.right.type !== "Literal")
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
CallExpression() {
|
||||
return true
|
||||
},
|
||||
FunctionExpression() {
|
||||
return false
|
||||
},
|
||||
ImportExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {MemberExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
MemberExpression(node, options, visitorKeys) {
|
||||
if (options.considerGetters) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.property.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {MethodDefinition} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
MethodDefinition(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
NewExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {Property} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
Property(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {PropertyDefinition} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
PropertyDefinition(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {UnaryExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
UnaryExpression(node, options, visitorKeys) {
|
||||
if (node.operator === "delete") {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
typeConversionUnaryOps.has(node.operator) &&
|
||||
node.argument.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
UpdateExpression() {
|
||||
return true
|
||||
},
|
||||
YieldExpression() {
|
||||
return true
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* Check whether a given node has any side effect or not.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {SourceCode} sourceCode The source code object.
|
||||
* @param {HasSideEffectOptions} [options] The option object.
|
||||
* @returns {boolean} `true` if the node has a certain side effect.
|
||||
*/
|
||||
function hasSideEffect(node, sourceCode, options = {}) {
|
||||
const { considerGetters = false, considerImplicitTypeConversion = false } =
|
||||
options;
|
||||
return visitor.$visit(
|
||||
node,
|
||||
{ considerGetters, considerImplicitTypeConversion },
|
||||
sourceCode.visitorKeys || eslintVisitorKeys.KEYS,
|
||||
)
|
||||
}
|
||||
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.NewExpression} TSNewExpression */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.CallExpression} TSCallExpression */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
|
||||
/**
|
||||
* Get the left parenthesis of the parent node syntax if it exists.
|
||||
* E.g., `if (a) {}` then the `(`.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {Token|null} The left parenthesis of the parent node syntax
|
||||
*/
|
||||
// eslint-disable-next-line complexity
|
||||
function getParentSyntaxParen(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
if (!parent) {
|
||||
return null
|
||||
}
|
||||
|
||||
switch (parent.type) {
|
||||
case "CallExpression":
|
||||
case "NewExpression":
|
||||
if (parent.arguments.length === 1 && parent.arguments[0] === node) {
|
||||
return sourceCode.getTokenAfter(
|
||||
// @ts-expect-error https://github.com/typescript-eslint/typescript-eslint/pull/5384
|
||||
parent.typeArguments ||
|
||||
/** @type {RuleNode} */ (
|
||||
/** @type {unknown} */ (
|
||||
/** @type {TSNewExpression | TSCallExpression} */ (
|
||||
parent
|
||||
).typeParameters
|
||||
)
|
||||
) ||
|
||||
parent.callee,
|
||||
isOpeningParenToken,
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
case "DoWhileStatement":
|
||||
if (parent.test === node) {
|
||||
return sourceCode.getTokenAfter(
|
||||
parent.body,
|
||||
isOpeningParenToken,
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
case "IfStatement":
|
||||
case "WhileStatement":
|
||||
if (parent.test === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "ImportExpression":
|
||||
if (parent.source === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "SwitchStatement":
|
||||
if (parent.discriminant === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "WithStatement":
|
||||
if (parent.object === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {number} times The number of parantheses.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {boolean} `true` if the node is parenthesized the given times.
|
||||
*/
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {boolean} `true` if the node is parenthesized.
|
||||
*/
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {Node|number} timesOrNode The first parameter.
|
||||
* @param {Node|SourceCode} nodeOrSourceCode The second parameter.
|
||||
* @param {SourceCode} [optionalSourceCode] The third parameter.
|
||||
* @returns {boolean} `true` if the node is parenthesized.
|
||||
*/
|
||||
function isParenthesized(
|
||||
timesOrNode,
|
||||
nodeOrSourceCode,
|
||||
optionalSourceCode,
|
||||
) {
|
||||
/** @type {number} */
|
||||
let times,
|
||||
/** @type {RuleNode} */
|
||||
node,
|
||||
/** @type {SourceCode} */
|
||||
sourceCode,
|
||||
maybeLeftParen,
|
||||
maybeRightParen;
|
||||
if (typeof timesOrNode === "number") {
|
||||
times = timesOrNode | 0;
|
||||
node = /** @type {RuleNode} */ (nodeOrSourceCode);
|
||||
sourceCode = /** @type {SourceCode} */ (optionalSourceCode);
|
||||
if (!(times >= 1)) {
|
||||
throw new TypeError("'times' should be a positive integer.")
|
||||
}
|
||||
} else {
|
||||
times = 1;
|
||||
node = /** @type {RuleNode} */ (timesOrNode);
|
||||
sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode);
|
||||
}
|
||||
|
||||
if (
|
||||
node == null ||
|
||||
// `Program` can't be parenthesized
|
||||
node.parent == null ||
|
||||
// `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
|
||||
(node.parent.type === "CatchClause" && node.parent.param === node)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
maybeLeftParen = maybeRightParen = node;
|
||||
do {
|
||||
maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
|
||||
maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
|
||||
} while (
|
||||
maybeLeftParen != null &&
|
||||
maybeRightParen != null &&
|
||||
isOpeningParenToken(maybeLeftParen) &&
|
||||
isClosingParenToken(maybeRightParen) &&
|
||||
// Avoid false positive such as `if (a) {}`
|
||||
maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
|
||||
--times > 0
|
||||
)
|
||||
|
||||
return times === 0
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
|
||||
const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
|
||||
|
||||
/** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
|
||||
const internal = new WeakMap();
|
||||
|
||||
/**
|
||||
* Check whether a given character is escaped or not.
|
||||
* @param {string} str The string to check.
|
||||
* @param {number} index The location of the character to check.
|
||||
* @returns {boolean} `true` if the character is escaped.
|
||||
*/
|
||||
function isEscaped(str, index) {
|
||||
let escaped = false;
|
||||
for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
|
||||
escaped = !escaped;
|
||||
}
|
||||
return escaped
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string by a given matcher.
|
||||
* @param {PatternMatcher} matcher The pattern matcher.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {string} replacement The new substring to replace each matched part.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replaceS(matcher, str, replacement) {
|
||||
const chunks = [];
|
||||
let index = 0;
|
||||
|
||||
/**
|
||||
* @param {string} key The placeholder.
|
||||
* @param {RegExpExecArray} match The matched information.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replacer(key, match) {
|
||||
switch (key) {
|
||||
case "$$":
|
||||
return "$"
|
||||
case "$&":
|
||||
return match[0]
|
||||
case "$`":
|
||||
return str.slice(0, match.index)
|
||||
case "$'":
|
||||
return str.slice(match.index + match[0].length)
|
||||
default: {
|
||||
const i = key.slice(1);
|
||||
if (i in match) {
|
||||
return match[/** @type {any} */ (i)]
|
||||
}
|
||||
return key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const match of matcher.execAll(str)) {
|
||||
chunks.push(str.slice(index, match.index));
|
||||
chunks.push(
|
||||
replacement.replace(placeholder, (key) => replacer(key, match)),
|
||||
);
|
||||
index = match.index + match[0].length;
|
||||
}
|
||||
chunks.push(str.slice(index));
|
||||
|
||||
return chunks.join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string by a given matcher.
|
||||
* @param {PatternMatcher} matcher The pattern matcher.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replaceF(matcher, str, replace) {
|
||||
const chunks = [];
|
||||
let index = 0;
|
||||
|
||||
for (const match of matcher.execAll(str)) {
|
||||
chunks.push(str.slice(index, match.index));
|
||||
chunks.push(
|
||||
String(
|
||||
replace(
|
||||
.../** @type {[string, ...string[]]} */ (
|
||||
/** @type {string[]} */ (match)
|
||||
),
|
||||
match.index,
|
||||
match.input,
|
||||
),
|
||||
),
|
||||
);
|
||||
index = match.index + match[0].length;
|
||||
}
|
||||
chunks.push(str.slice(index));
|
||||
|
||||
return chunks.join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* The class to find patterns as considering escape sequences.
|
||||
*/
|
||||
class PatternMatcher {
|
||||
/**
|
||||
* Initialize this matcher.
|
||||
* @param {RegExp} pattern The pattern to match.
|
||||
* @param {{escaped?:boolean}} [options] The options.
|
||||
*/
|
||||
constructor(pattern, options = {}) {
|
||||
const { escaped = false } = options;
|
||||
if (!(pattern instanceof RegExp)) {
|
||||
throw new TypeError("'pattern' should be a RegExp instance.")
|
||||
}
|
||||
if (!pattern.flags.includes("g")) {
|
||||
throw new Error("'pattern' should contains 'g' flag.")
|
||||
}
|
||||
|
||||
internal.set(this, {
|
||||
pattern: new RegExp(pattern.source, pattern.flags),
|
||||
escaped: Boolean(escaped),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the pattern in a given string.
|
||||
* @param {string} str The string to find.
|
||||
* @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
|
||||
*/
|
||||
*execAll(str) {
|
||||
const { pattern, escaped } =
|
||||
/** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this));
|
||||
let match = null;
|
||||
let lastIndex = 0;
|
||||
|
||||
pattern.lastIndex = 0;
|
||||
while ((match = pattern.exec(str)) != null) {
|
||||
if (escaped || !isEscaped(str, match.index)) {
|
||||
lastIndex = pattern.lastIndex;
|
||||
yield match;
|
||||
pattern.lastIndex = lastIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the pattern is found in a given string.
|
||||
* @param {string} str The string to check.
|
||||
* @returns {boolean} `true` if the pattern was found in the string.
|
||||
*/
|
||||
test(str) {
|
||||
const it = this.execAll(str);
|
||||
const ret = it.next();
|
||||
return !ret.done
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
[Symbol.replace](str, replacer) {
|
||||
return typeof replacer === "function"
|
||||
? replaceF(this, String(str), replacer)
|
||||
: replaceS(this, String(str), String(replacer))
|
||||
}
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("estree").Expression} Expression */
|
||||
/** @typedef {import("estree").Pattern} Pattern */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
/** @typedef {import("estree").SimpleCallExpression} CallExpression */
|
||||
/** @typedef {import("estree").Program} Program */
|
||||
/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
|
||||
/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
|
||||
/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
|
||||
/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
|
||||
/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
|
||||
/** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */
|
||||
/** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */
|
||||
/** @typedef {import("estree").ExportSpecifier} ExportSpecifier */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
|
||||
/** @typedef {import("estree").Literal} Literal */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
|
||||
/** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TraceMap<T>} TraceMap
|
||||
*/
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TraceMapObject<T>} TraceMapObject
|
||||
*/
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TrackedReferences<T>} TrackedReferences
|
||||
*/
|
||||
|
||||
const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
|
||||
|
||||
/**
|
||||
* Check whether a given node is an import node or not.
|
||||
* @param {Node} node
|
||||
* @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.
|
||||
*/
|
||||
function isHasSource(node) {
|
||||
return (
|
||||
IMPORT_TYPE.test(node.type) &&
|
||||
/** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (
|
||||
node
|
||||
).source != null
|
||||
)
|
||||
}
|
||||
const has =
|
||||
/** @type {<T>(traceMap: TraceMap<unknown>, v: T) => v is (string extends T ? string : T)} */ (
|
||||
Function.call.bind(Object.hasOwnProperty)
|
||||
);
|
||||
|
||||
const READ = Symbol("read");
|
||||
const CALL = Symbol("call");
|
||||
const CONSTRUCT = Symbol("construct");
|
||||
const ESM = Symbol("esm");
|
||||
|
||||
const requireCall = { require: { [CALL]: true } };
|
||||
|
||||
/**
|
||||
* Check whether a given variable is modified or not.
|
||||
* @param {Variable|undefined} variable The variable to check.
|
||||
* @returns {boolean} `true` if the variable is modified.
|
||||
*/
|
||||
function isModifiedGlobal(variable) {
|
||||
return (
|
||||
variable == null ||
|
||||
variable.defs.length !== 0 ||
|
||||
variable.references.some((r) => r.isWrite())
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the value of a given node is passed through to the parent syntax as-is.
|
||||
* For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
|
||||
* @param {Node} node A node to check.
|
||||
* @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.
|
||||
*/
|
||||
function isPassThrough(node) {
|
||||
const parent = /** @type {TSESTreeNode} */ (node).parent;
|
||||
|
||||
if (parent) {
|
||||
switch (parent.type) {
|
||||
case "ConditionalExpression":
|
||||
return parent.consequent === node || parent.alternate === node
|
||||
case "LogicalExpression":
|
||||
return true
|
||||
case "SequenceExpression":
|
||||
return (
|
||||
parent.expressions[parent.expressions.length - 1] === node
|
||||
)
|
||||
case "ChainExpression":
|
||||
return true
|
||||
case "TSAsExpression":
|
||||
case "TSSatisfiesExpression":
|
||||
case "TSTypeAssertion":
|
||||
case "TSNonNullExpression":
|
||||
case "TSInstantiationExpression":
|
||||
return true
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference tracker.
|
||||
*/
|
||||
class ReferenceTracker {
|
||||
/**
|
||||
* Initialize this tracker.
|
||||
* @param {Scope} globalScope The global scope.
|
||||
* @param {object} [options] The options.
|
||||
* @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
|
||||
* @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
|
||||
*/
|
||||
constructor(globalScope, options = {}) {
|
||||
const {
|
||||
mode = "strict",
|
||||
globalObjectNames = ["global", "globalThis", "self", "window"],
|
||||
} = options;
|
||||
/** @private @type {Variable[]} */
|
||||
this.variableStack = [];
|
||||
/** @private */
|
||||
this.globalScope = globalScope;
|
||||
/** @private */
|
||||
this.mode = mode;
|
||||
/** @private */
|
||||
this.globalObjectNames = globalObjectNames.slice(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of global variables.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateGlobalReferences(traceMap) {
|
||||
for (const key of Object.keys(traceMap)) {
|
||||
const nextTraceMap = traceMap[key];
|
||||
const path = [key];
|
||||
const variable = this.globalScope.set.get(key);
|
||||
|
||||
if (isModifiedGlobal(variable)) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (variable),
|
||||
path,
|
||||
nextTraceMap,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
for (const key of this.globalObjectNames) {
|
||||
/** @type {string[]} */
|
||||
const path = [];
|
||||
const variable = this.globalScope.set.get(key);
|
||||
|
||||
if (isModifiedGlobal(variable)) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (variable),
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of CommonJS modules.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateCjsReferences(traceMap) {
|
||||
for (const { node } of this.iterateGlobalReferences(requireCall)) {
|
||||
const key = getStringIfConstant(
|
||||
/** @type {CallExpression} */ (node).arguments[0],
|
||||
);
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const nextTraceMap = traceMap[key];
|
||||
const path = [key];
|
||||
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node,
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iteratePropertyReferences(
|
||||
/** @type {CallExpression} */ (node),
|
||||
path,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of ES modules.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateEsmReferences(traceMap) {
|
||||
const programNode = /** @type {Program} */ (this.globalScope.block);
|
||||
|
||||
for (const node of programNode.body) {
|
||||
if (!isHasSource(node)) {
|
||||
continue
|
||||
}
|
||||
const moduleId = /** @type {string} */ (node.source.value);
|
||||
|
||||
if (!has(traceMap, moduleId)) {
|
||||
continue
|
||||
}
|
||||
const nextTraceMap = traceMap[moduleId];
|
||||
const path = [moduleId];
|
||||
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
// eslint-disable-next-line object-shorthand -- apply type
|
||||
node: /** @type {RuleNode} */ (node),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
|
||||
if (node.type === "ExportAllDeclaration") {
|
||||
for (const key of Object.keys(nextTraceMap)) {
|
||||
const exportTraceMap = nextTraceMap[key];
|
||||
if (exportTraceMap[READ]) {
|
||||
yield {
|
||||
// eslint-disable-next-line object-shorthand -- apply type
|
||||
node: /** @type {RuleNode} */ (node),
|
||||
path: path.concat(key),
|
||||
type: READ,
|
||||
info: exportTraceMap[READ],
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const specifier of node.specifiers) {
|
||||
const esm = has(nextTraceMap, ESM);
|
||||
const it = this._iterateImportReferences(
|
||||
specifier,
|
||||
path,
|
||||
esm
|
||||
? nextTraceMap
|
||||
: this.mode === "legacy"
|
||||
? { default: nextTraceMap, ...nextTraceMap }
|
||||
: { default: nextTraceMap },
|
||||
);
|
||||
|
||||
if (esm) {
|
||||
yield* it;
|
||||
} else {
|
||||
for (const report of it) {
|
||||
report.path = report.path.filter(exceptDefault);
|
||||
if (
|
||||
report.path.length >= 2 ||
|
||||
report.type !== READ
|
||||
) {
|
||||
yield report;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the property references for a given expression AST node.
|
||||
* @template T
|
||||
* @param {Expression} node The expression AST node to iterate property references.
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate property references.
|
||||
*/
|
||||
*iteratePropertyReferences(node, traceMap) {
|
||||
yield* this._iteratePropertyReferences(node, [], traceMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given variable.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Variable} variable The variable to iterate that references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @param {boolean} shouldReport = The flag to report those references.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateVariableReferences(variable, path, traceMap, shouldReport) {
|
||||
if (this.variableStack.includes(variable)) {
|
||||
return
|
||||
}
|
||||
this.variableStack.push(variable);
|
||||
try {
|
||||
for (const reference of variable.references) {
|
||||
if (!reference.isRead()) {
|
||||
continue
|
||||
}
|
||||
const node = /** @type {RuleNode & Identifier} */ (
|
||||
reference.identifier
|
||||
);
|
||||
|
||||
if (shouldReport && traceMap[READ]) {
|
||||
yield { node, path, type: READ, info: traceMap[READ] };
|
||||
}
|
||||
yield* this._iteratePropertyReferences(node, path, traceMap);
|
||||
}
|
||||
} finally {
|
||||
this.variableStack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given AST node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Expression} rootNode The AST node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
//eslint-disable-next-line complexity
|
||||
*_iteratePropertyReferences(rootNode, path, traceMap) {
|
||||
let node = rootNode;
|
||||
while (isPassThrough(node)) {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
if (!parent) {
|
||||
return
|
||||
}
|
||||
if (parent.type === "MemberExpression") {
|
||||
if (parent.object === node) {
|
||||
const key = getPropertyName(parent);
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: parent,
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iteratePropertyReferences(
|
||||
parent,
|
||||
path,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "CallExpression") {
|
||||
if (parent.callee === node && traceMap[CALL]) {
|
||||
yield { node: parent, path, type: CALL, info: traceMap[CALL] };
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "NewExpression") {
|
||||
if (parent.callee === node && traceMap[CONSTRUCT]) {
|
||||
yield {
|
||||
node: parent,
|
||||
path,
|
||||
type: CONSTRUCT,
|
||||
info: traceMap[CONSTRUCT],
|
||||
};
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "AssignmentExpression") {
|
||||
if (parent.right === node) {
|
||||
yield* this._iterateLhsReferences(parent.left, path, traceMap);
|
||||
yield* this._iteratePropertyReferences(parent, path, traceMap);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "AssignmentPattern") {
|
||||
if (parent.right === node) {
|
||||
yield* this._iterateLhsReferences(parent.left, path, traceMap);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "VariableDeclarator") {
|
||||
if (parent.init === node) {
|
||||
yield* this._iterateLhsReferences(parent.id, path, traceMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given Pattern node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Pattern} patternNode The Pattern node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateLhsReferences(patternNode, path, traceMap) {
|
||||
if (patternNode.type === "Identifier") {
|
||||
const variable = findVariable(this.globalScope, patternNode);
|
||||
if (variable != null) {
|
||||
yield* this._iterateVariableReferences(
|
||||
variable,
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (patternNode.type === "ObjectPattern") {
|
||||
for (const property of patternNode.properties) {
|
||||
const key = getPropertyName(
|
||||
/** @type {AssignmentProperty} */ (property),
|
||||
);
|
||||
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const nextPath = path.concat(key);
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (property),
|
||||
path: nextPath,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iterateLhsReferences(
|
||||
/** @type {AssignmentProperty} */ (property).value,
|
||||
nextPath,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (patternNode.type === "AssignmentPattern") {
|
||||
yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given ModuleSpecifier node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateImportReferences(specifierNode, path, traceMap) {
|
||||
const type = specifierNode.type;
|
||||
|
||||
if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
|
||||
const key =
|
||||
type === "ImportDefaultSpecifier"
|
||||
? "default"
|
||||
: specifierNode.imported.type === "Identifier"
|
||||
? specifierNode.imported.name
|
||||
: specifierNode.imported.value;
|
||||
if (!has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (specifierNode),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (
|
||||
findVariable(this.globalScope, specifierNode.local)
|
||||
),
|
||||
path,
|
||||
nextTraceMap,
|
||||
false,
|
||||
);
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (type === "ImportNamespaceSpecifier") {
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (
|
||||
findVariable(this.globalScope, specifierNode.local)
|
||||
),
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
return
|
||||
}
|
||||
|
||||
if (type === "ExportSpecifier") {
|
||||
const key =
|
||||
specifierNode.local.type === "Identifier"
|
||||
? specifierNode.local.name
|
||||
: specifierNode.local.value;
|
||||
if (!has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (specifierNode),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReferenceTracker.READ = READ;
|
||||
ReferenceTracker.CALL = CALL;
|
||||
ReferenceTracker.CONSTRUCT = CONSTRUCT;
|
||||
ReferenceTracker.ESM = ESM;
|
||||
|
||||
/**
|
||||
* This is a predicate function for Array#filter.
|
||||
* @param {string} name A name part.
|
||||
* @param {number} index The index of the name.
|
||||
* @returns {boolean} `false` if it's default.
|
||||
*/
|
||||
function exceptDefault(name, index) {
|
||||
return !(index === 1 && name === "default")
|
||||
}
|
||||
|
||||
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
|
||||
|
||||
var index = {
|
||||
CALL,
|
||||
CONSTRUCT,
|
||||
ESM,
|
||||
findVariable,
|
||||
getFunctionHeadLocation,
|
||||
getFunctionNameWithKind,
|
||||
getInnermostScope,
|
||||
getPropertyName,
|
||||
getStaticValue,
|
||||
getStringIfConstant,
|
||||
hasSideEffect,
|
||||
isArrowToken,
|
||||
isClosingBraceToken,
|
||||
isClosingBracketToken,
|
||||
isClosingParenToken,
|
||||
isColonToken,
|
||||
isCommaToken,
|
||||
isCommentToken,
|
||||
isNotArrowToken,
|
||||
isNotClosingBraceToken,
|
||||
isNotClosingBracketToken,
|
||||
isNotClosingParenToken,
|
||||
isNotColonToken,
|
||||
isNotCommaToken,
|
||||
isNotCommentToken,
|
||||
isNotOpeningBraceToken,
|
||||
isNotOpeningBracketToken,
|
||||
isNotOpeningParenToken,
|
||||
isNotSemicolonToken,
|
||||
isOpeningBraceToken,
|
||||
isOpeningBracketToken,
|
||||
isOpeningParenToken,
|
||||
isParenthesized,
|
||||
isSemicolonToken,
|
||||
PatternMatcher,
|
||||
READ,
|
||||
ReferenceTracker,
|
||||
};
|
||||
|
||||
exports.CALL = CALL;
|
||||
exports.CONSTRUCT = CONSTRUCT;
|
||||
exports.ESM = ESM;
|
||||
exports.PatternMatcher = PatternMatcher;
|
||||
exports.READ = READ;
|
||||
exports.ReferenceTracker = ReferenceTracker;
|
||||
exports["default"] = index;
|
||||
exports.findVariable = findVariable;
|
||||
exports.getFunctionHeadLocation = getFunctionHeadLocation;
|
||||
exports.getFunctionNameWithKind = getFunctionNameWithKind;
|
||||
exports.getInnermostScope = getInnermostScope;
|
||||
exports.getPropertyName = getPropertyName;
|
||||
exports.getStaticValue = getStaticValue;
|
||||
exports.getStringIfConstant = getStringIfConstant;
|
||||
exports.hasSideEffect = hasSideEffect;
|
||||
exports.isArrowToken = isArrowToken;
|
||||
exports.isClosingBraceToken = isClosingBraceToken;
|
||||
exports.isClosingBracketToken = isClosingBracketToken;
|
||||
exports.isClosingParenToken = isClosingParenToken;
|
||||
exports.isColonToken = isColonToken;
|
||||
exports.isCommaToken = isCommaToken;
|
||||
exports.isCommentToken = isCommentToken;
|
||||
exports.isNotArrowToken = isNotArrowToken;
|
||||
exports.isNotClosingBraceToken = isNotClosingBraceToken;
|
||||
exports.isNotClosingBracketToken = isNotClosingBracketToken;
|
||||
exports.isNotClosingParenToken = isNotClosingParenToken;
|
||||
exports.isNotColonToken = isNotColonToken;
|
||||
exports.isNotCommaToken = isNotCommaToken;
|
||||
exports.isNotCommentToken = isNotCommentToken;
|
||||
exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
|
||||
exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
|
||||
exports.isNotOpeningParenToken = isNotOpeningParenToken;
|
||||
exports.isNotSemicolonToken = isNotSemicolonToken;
|
||||
exports.isOpeningBraceToken = isOpeningBraceToken;
|
||||
exports.isOpeningBracketToken = isOpeningBracketToken;
|
||||
exports.isOpeningParenToken = isOpeningParenToken;
|
||||
exports.isParenthesized = isParenthesized;
|
||||
exports.isSemicolonToken = isSemicolonToken;
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2579
@@ -0,0 +1,2579 @@
|
||||
import { getKeys, KEYS } from 'eslint-visitor-keys';
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
|
||||
/**
|
||||
* Get the innermost scope which contains a given location.
|
||||
* @param {Scope} initialScope The initial scope to search.
|
||||
* @param {Node} node The location to search.
|
||||
* @returns {Scope} The innermost scope.
|
||||
*/
|
||||
function getInnermostScope(initialScope, node) {
|
||||
const location = /** @type {[number, number]} */ (node.range)[0];
|
||||
|
||||
let scope = initialScope;
|
||||
let found = false;
|
||||
do {
|
||||
found = false;
|
||||
for (const childScope of scope.childScopes) {
|
||||
const range = /** @type {[number, number]} */ (
|
||||
childScope.block.range
|
||||
);
|
||||
|
||||
if (range[0] <= location && location < range[1]) {
|
||||
scope = childScope;
|
||||
found = true;
|
||||
break
|
||||
}
|
||||
}
|
||||
} while (found)
|
||||
|
||||
return scope
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Find the variable of a given name.
|
||||
* @param {Scope} initialScope The scope to start finding.
|
||||
* @param {string|Identifier} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
|
||||
* @returns {Variable|null} The found variable or null.
|
||||
*/
|
||||
function findVariable(initialScope, nameOrNode) {
|
||||
let name = "";
|
||||
/** @type {Scope|null} */
|
||||
let scope = initialScope;
|
||||
|
||||
if (typeof nameOrNode === "string") {
|
||||
name = nameOrNode;
|
||||
} else {
|
||||
name = nameOrNode.name;
|
||||
scope = getInnermostScope(scope, nameOrNode);
|
||||
}
|
||||
|
||||
while (scope != null) {
|
||||
const variable = scope.set.get(name);
|
||||
if (variable != null) {
|
||||
return variable
|
||||
}
|
||||
scope = scope.upper;
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("estree").Comment} Comment */
|
||||
/** @typedef {import("./types.mjs").ArrowToken} ArrowToken */
|
||||
/** @typedef {import("./types.mjs").CommaToken} CommaToken */
|
||||
/** @typedef {import("./types.mjs").SemicolonToken} SemicolonToken */
|
||||
/** @typedef {import("./types.mjs").ColonToken} ColonToken */
|
||||
/** @typedef {import("./types.mjs").OpeningParenToken} OpeningParenToken */
|
||||
/** @typedef {import("./types.mjs").ClosingParenToken} ClosingParenToken */
|
||||
/** @typedef {import("./types.mjs").OpeningBracketToken} OpeningBracketToken */
|
||||
/** @typedef {import("./types.mjs").ClosingBracketToken} ClosingBracketToken */
|
||||
/** @typedef {import("./types.mjs").OpeningBraceToken} OpeningBraceToken */
|
||||
/** @typedef {import("./types.mjs").ClosingBraceToken} ClosingBraceToken */
|
||||
/**
|
||||
* @template {string} Value
|
||||
* @typedef {import("./types.mjs").PunctuatorToken<Value>} PunctuatorToken
|
||||
*/
|
||||
|
||||
/** @typedef {Comment | Token} CommentOrToken */
|
||||
|
||||
/**
|
||||
* Creates the negate function of the given function.
|
||||
* @param {function(CommentOrToken):boolean} f - The function to negate.
|
||||
* @returns {function(CommentOrToken):boolean} Negated function.
|
||||
*/
|
||||
function negate(f) {
|
||||
return (token) => !f(token)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a PunctuatorToken with the given value
|
||||
* @template {string} Value
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @param {Value} value - The value to check.
|
||||
* @returns {token is PunctuatorToken<Value>} `true` if the token is a PunctuatorToken with the given value.
|
||||
*/
|
||||
function isPunctuatorTokenWithValue(token, value) {
|
||||
return token.type === "Punctuator" && token.value === value
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an arrow token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ArrowToken} `true` if the token is an arrow token.
|
||||
*/
|
||||
function isArrowToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "=>")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a comma token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is CommaToken} `true` if the token is a comma token.
|
||||
*/
|
||||
function isCommaToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ",")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a semicolon token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is SemicolonToken} `true` if the token is a semicolon token.
|
||||
*/
|
||||
function isSemicolonToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ";")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a colon token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ColonToken} `true` if the token is a colon token.
|
||||
*/
|
||||
function isColonToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ":")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening parenthesis token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningParenToken} `true` if the token is an opening parenthesis token.
|
||||
*/
|
||||
function isOpeningParenToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "(")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing parenthesis token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingParenToken} `true` if the token is a closing parenthesis token.
|
||||
*/
|
||||
function isClosingParenToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, ")")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening square bracket token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningBracketToken} `true` if the token is an opening square bracket token.
|
||||
*/
|
||||
function isOpeningBracketToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "[")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing square bracket token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingBracketToken} `true` if the token is a closing square bracket token.
|
||||
*/
|
||||
function isClosingBracketToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "]")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is an opening brace token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is OpeningBraceToken} `true` if the token is an opening brace token.
|
||||
*/
|
||||
function isOpeningBraceToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "{")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a closing brace token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is ClosingBraceToken} `true` if the token is a closing brace token.
|
||||
*/
|
||||
function isClosingBraceToken(token) {
|
||||
return isPunctuatorTokenWithValue(token, "}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given token is a comment token or not.
|
||||
* @param {CommentOrToken} token - The token to check.
|
||||
* @returns {token is Comment} `true` if the token is a comment token.
|
||||
*/
|
||||
function isCommentToken(token) {
|
||||
return ["Block", "Line", "Shebang"].includes(token.type)
|
||||
}
|
||||
|
||||
const isNotArrowToken = negate(isArrowToken);
|
||||
const isNotCommaToken = negate(isCommaToken);
|
||||
const isNotSemicolonToken = negate(isSemicolonToken);
|
||||
const isNotColonToken = negate(isColonToken);
|
||||
const isNotOpeningParenToken = negate(isOpeningParenToken);
|
||||
const isNotClosingParenToken = negate(isClosingParenToken);
|
||||
const isNotOpeningBracketToken = negate(isOpeningBracketToken);
|
||||
const isNotClosingBracketToken = negate(isClosingBracketToken);
|
||||
const isNotOpeningBraceToken = negate(isOpeningBraceToken);
|
||||
const isNotClosingBraceToken = negate(isClosingBraceToken);
|
||||
const isNotCommentToken = negate(isCommentToken);
|
||||
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("estree").Function} FunctionNode */
|
||||
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
|
||||
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
|
||||
/** @typedef {import("estree").SourceLocation} SourceLocation */
|
||||
/** @typedef {import("estree").Position} Position */
|
||||
|
||||
/**
|
||||
* Get the `(` token of the given function node.
|
||||
* @param {FunctionExpression | FunctionDeclaration} node - The function node to get.
|
||||
* @param {SourceCode} sourceCode - The source code object to get tokens.
|
||||
* @returns {Token} `(` token.
|
||||
*/
|
||||
function getOpeningParenOfParams(node, sourceCode) {
|
||||
return node.id
|
||||
? /** @type {Token} */ (
|
||||
sourceCode.getTokenAfter(node.id, isOpeningParenToken)
|
||||
)
|
||||
: /** @type {Token} */ (
|
||||
sourceCode.getFirstToken(node, isOpeningParenToken)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the location of the given function node for reporting.
|
||||
* @param {FunctionNode} node - The function node to get.
|
||||
* @param {SourceCode} sourceCode - The source code object to get tokens.
|
||||
* @returns {SourceLocation|null} The location of the function node for reporting.
|
||||
*/
|
||||
function getFunctionHeadLocation(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
/** @type {Position|null} */
|
||||
let start = null;
|
||||
/** @type {Position|null} */
|
||||
let end = null;
|
||||
|
||||
if (node.type === "ArrowFunctionExpression") {
|
||||
const arrowToken = /** @type {Token} */ (
|
||||
sourceCode.getTokenBefore(node.body, isArrowToken)
|
||||
);
|
||||
|
||||
start = arrowToken.loc.start;
|
||||
end = arrowToken.loc.end;
|
||||
} else if (
|
||||
parent &&
|
||||
(parent.type === "Property" ||
|
||||
parent.type === "MethodDefinition" ||
|
||||
parent.type === "PropertyDefinition")
|
||||
) {
|
||||
start = /** @type {SourceLocation} */ (parent.loc).start;
|
||||
end = getOpeningParenOfParams(node, sourceCode).loc.start;
|
||||
} else {
|
||||
start = /** @type {SourceLocation} */ (node.loc).start;
|
||||
end = getOpeningParenOfParams(node, sourceCode).loc.start;
|
||||
}
|
||||
|
||||
return {
|
||||
start: { ...start },
|
||||
end: { ...end },
|
||||
}
|
||||
}
|
||||
|
||||
/* globals globalThis, global, self, window */
|
||||
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.MemberExpression} MemberExpression */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Property} Property */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.RegExpLiteral} RegExpLiteral */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.BigIntLiteral} BigIntLiteral */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Literal} Literal */
|
||||
|
||||
const globalObject =
|
||||
typeof globalThis !== "undefined"
|
||||
? globalThis
|
||||
: // @ts-ignore
|
||||
typeof self !== "undefined"
|
||||
? // @ts-ignore
|
||||
self
|
||||
: // @ts-ignore
|
||||
typeof window !== "undefined"
|
||||
? // @ts-ignore
|
||||
window
|
||||
: typeof global !== "undefined"
|
||||
? global
|
||||
: {};
|
||||
|
||||
const builtinNames = Object.freeze(
|
||||
new Set([
|
||||
"Array",
|
||||
"ArrayBuffer",
|
||||
"BigInt",
|
||||
"BigInt64Array",
|
||||
"BigUint64Array",
|
||||
"Boolean",
|
||||
"DataView",
|
||||
"Date",
|
||||
"decodeURI",
|
||||
"decodeURIComponent",
|
||||
"encodeURI",
|
||||
"encodeURIComponent",
|
||||
"escape",
|
||||
"Float32Array",
|
||||
"Float64Array",
|
||||
"Function",
|
||||
"Infinity",
|
||||
"Int16Array",
|
||||
"Int32Array",
|
||||
"Int8Array",
|
||||
"isFinite",
|
||||
"isNaN",
|
||||
"isPrototypeOf",
|
||||
"JSON",
|
||||
"Map",
|
||||
"Math",
|
||||
"NaN",
|
||||
"Number",
|
||||
"Object",
|
||||
"parseFloat",
|
||||
"parseInt",
|
||||
"Promise",
|
||||
"Proxy",
|
||||
"Reflect",
|
||||
"RegExp",
|
||||
"Set",
|
||||
"String",
|
||||
"Symbol",
|
||||
"Uint16Array",
|
||||
"Uint32Array",
|
||||
"Uint8Array",
|
||||
"Uint8ClampedArray",
|
||||
"undefined",
|
||||
"unescape",
|
||||
"WeakMap",
|
||||
"WeakSet",
|
||||
]),
|
||||
);
|
||||
const callAllowed = new Set(
|
||||
[
|
||||
Array.isArray,
|
||||
Array.of,
|
||||
Array.prototype.at,
|
||||
Array.prototype.concat,
|
||||
Array.prototype.entries,
|
||||
Array.prototype.every,
|
||||
Array.prototype.filter,
|
||||
Array.prototype.find,
|
||||
Array.prototype.findIndex,
|
||||
Array.prototype.flat,
|
||||
Array.prototype.includes,
|
||||
Array.prototype.indexOf,
|
||||
Array.prototype.join,
|
||||
Array.prototype.keys,
|
||||
Array.prototype.lastIndexOf,
|
||||
Array.prototype.slice,
|
||||
Array.prototype.some,
|
||||
Array.prototype.toString,
|
||||
Array.prototype.values,
|
||||
typeof BigInt === "function" ? BigInt : undefined,
|
||||
Boolean,
|
||||
Date,
|
||||
Date.parse,
|
||||
decodeURI,
|
||||
decodeURIComponent,
|
||||
encodeURI,
|
||||
encodeURIComponent,
|
||||
escape,
|
||||
isFinite,
|
||||
isNaN,
|
||||
// @ts-ignore
|
||||
isPrototypeOf,
|
||||
Map,
|
||||
Map.prototype.entries,
|
||||
Map.prototype.get,
|
||||
Map.prototype.has,
|
||||
Map.prototype.keys,
|
||||
Map.prototype.values,
|
||||
.../** @type {(keyof typeof Math)[]} */ (
|
||||
Object.getOwnPropertyNames(Math)
|
||||
)
|
||||
.filter((k) => k !== "random")
|
||||
.map((k) => Math[k])
|
||||
.filter((f) => typeof f === "function"),
|
||||
Number,
|
||||
Number.isFinite,
|
||||
Number.isNaN,
|
||||
Number.parseFloat,
|
||||
Number.parseInt,
|
||||
Number.prototype.toExponential,
|
||||
Number.prototype.toFixed,
|
||||
Number.prototype.toPrecision,
|
||||
Number.prototype.toString,
|
||||
Object,
|
||||
Object.entries,
|
||||
Object.is,
|
||||
Object.isExtensible,
|
||||
Object.isFrozen,
|
||||
Object.isSealed,
|
||||
Object.keys,
|
||||
Object.values,
|
||||
parseFloat,
|
||||
parseInt,
|
||||
RegExp,
|
||||
Set,
|
||||
Set.prototype.entries,
|
||||
Set.prototype.has,
|
||||
Set.prototype.keys,
|
||||
Set.prototype.values,
|
||||
String,
|
||||
String.fromCharCode,
|
||||
String.fromCodePoint,
|
||||
String.raw,
|
||||
String.prototype.at,
|
||||
String.prototype.charAt,
|
||||
String.prototype.charCodeAt,
|
||||
String.prototype.codePointAt,
|
||||
String.prototype.concat,
|
||||
String.prototype.endsWith,
|
||||
String.prototype.includes,
|
||||
String.prototype.indexOf,
|
||||
String.prototype.lastIndexOf,
|
||||
String.prototype.normalize,
|
||||
String.prototype.padEnd,
|
||||
String.prototype.padStart,
|
||||
String.prototype.slice,
|
||||
String.prototype.startsWith,
|
||||
String.prototype.substr,
|
||||
String.prototype.substring,
|
||||
String.prototype.toLowerCase,
|
||||
String.prototype.toString,
|
||||
String.prototype.toUpperCase,
|
||||
String.prototype.trim,
|
||||
String.prototype.trimEnd,
|
||||
String.prototype.trimLeft,
|
||||
String.prototype.trimRight,
|
||||
String.prototype.trimStart,
|
||||
Symbol.for,
|
||||
Symbol.keyFor,
|
||||
unescape,
|
||||
].filter((f) => typeof f === "function"),
|
||||
);
|
||||
const callPassThrough = new Set([
|
||||
Object.freeze,
|
||||
Object.preventExtensions,
|
||||
Object.seal,
|
||||
]);
|
||||
|
||||
/** @type {ReadonlyArray<readonly [Function, ReadonlySet<string>]>} */
|
||||
const getterAllowed = [
|
||||
[Map, new Set(["size"])],
|
||||
[
|
||||
RegExp,
|
||||
new Set([
|
||||
"dotAll",
|
||||
"flags",
|
||||
"global",
|
||||
"hasIndices",
|
||||
"ignoreCase",
|
||||
"multiline",
|
||||
"source",
|
||||
"sticky",
|
||||
"unicode",
|
||||
]),
|
||||
],
|
||||
[Set, new Set(["size"])],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the property descriptor.
|
||||
* @param {object} object The object to get.
|
||||
* @param {string|number|symbol} name The property name to get.
|
||||
*/
|
||||
function getPropertyDescriptor(object, name) {
|
||||
let x = object;
|
||||
while ((typeof x === "object" || typeof x === "function") && x !== null) {
|
||||
const d = Object.getOwnPropertyDescriptor(x, name);
|
||||
if (d) {
|
||||
return d
|
||||
}
|
||||
x = Object.getPrototypeOf(x);
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a property is getter or not.
|
||||
* @param {object} object The object to check.
|
||||
* @param {string|number|symbol} name The property name to check.
|
||||
*/
|
||||
function isGetter(object, name) {
|
||||
const d = getPropertyDescriptor(object, name);
|
||||
return d != null && d.get != null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the element values of a given node list.
|
||||
* @param {(Node|TSESTreeNode|null)[]} nodeList The node list to get values.
|
||||
* @param {Scope|undefined|null} initialScope The initial scope to find variables.
|
||||
* @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
|
||||
*/
|
||||
function getElementValues(nodeList, initialScope) {
|
||||
const valueList = [];
|
||||
|
||||
for (let i = 0; i < nodeList.length; ++i) {
|
||||
const elementNode = nodeList[i];
|
||||
|
||||
if (elementNode == null) {
|
||||
valueList.length = i + 1;
|
||||
} else if (elementNode.type === "SpreadElement") {
|
||||
const argument = getStaticValueR(elementNode.argument, initialScope);
|
||||
if (argument == null) {
|
||||
return null
|
||||
}
|
||||
valueList.push(.../** @type {Iterable<any>} */ (argument.value));
|
||||
} else {
|
||||
const element = getStaticValueR(elementNode, initialScope);
|
||||
if (element == null) {
|
||||
return null
|
||||
}
|
||||
valueList.push(element.value);
|
||||
}
|
||||
}
|
||||
|
||||
return valueList
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable is a built-in global.
|
||||
* @param {Variable|null} variable The variable to check.
|
||||
* @returns {variable is Variable & {defs:[]}}
|
||||
*/
|
||||
function isBuiltinGlobal(variable) {
|
||||
return (
|
||||
variable != null &&
|
||||
variable.defs.length === 0 &&
|
||||
builtinNames.has(variable.name) &&
|
||||
variable.name in globalObject
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable can be considered as a constant.
|
||||
* @param {Variable} variable
|
||||
* @returns {variable is Variable & {defs: [import("eslint").Scope.Definition & { type: "Variable" }]}} True if the variable can be considered as a constant.
|
||||
*/
|
||||
function canBeConsideredConst(variable) {
|
||||
if (variable.defs.length !== 1) {
|
||||
return false
|
||||
}
|
||||
const def = variable.defs[0];
|
||||
return Boolean(
|
||||
def.parent &&
|
||||
def.type === "Variable" &&
|
||||
(def.parent.kind === "const" || isEffectivelyConst(variable)),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the given variable is never written to after initialization.
|
||||
* @param {Variable} variable
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isEffectivelyConst(variable) {
|
||||
const refs = variable.references;
|
||||
|
||||
const inits = refs.filter((r) => r.init).length;
|
||||
const reads = refs.filter((r) => r.isReadOnly()).length;
|
||||
if (inits === 1 && reads + inits === refs.length) {
|
||||
// there is only one init and all other references only read
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a variable has mutation in its property.
|
||||
* @param {Variable} variable The variable to check.
|
||||
* @param {Scope|null} initialScope The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {boolean} True if the variable has mutation in its property.
|
||||
*/
|
||||
function hasMutationInProperty(variable, initialScope) {
|
||||
for (const ref of variable.references) {
|
||||
let node = /** @type {TSESTreeNode} */ (ref.identifier);
|
||||
while (node && node.parent && node.parent.type === "MemberExpression") {
|
||||
node = node.parent;
|
||||
}
|
||||
if (!node || !node.parent) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
(node.parent.type === "AssignmentExpression" &&
|
||||
node.parent.left === node) ||
|
||||
(node.parent.type === "UpdateExpression" &&
|
||||
node.parent.argument === node)
|
||||
) {
|
||||
// This is a mutation.
|
||||
return true
|
||||
}
|
||||
if (
|
||||
node.parent.type === "CallExpression" &&
|
||||
node.parent.callee === node &&
|
||||
node.type === "MemberExpression"
|
||||
) {
|
||||
const methodName = getStaticPropertyNameValue(node, initialScope);
|
||||
if (isNameOfMutationArrayMethod(methodName)) {
|
||||
// This is a mutation.
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
/**
|
||||
* Checks if a method name is one of the mutation array methods.
|
||||
* @param {StaticValue|null} methodName The method name to check.
|
||||
* @returns {boolean} True if the method name is a mutation array method.
|
||||
*/
|
||||
function isNameOfMutationArrayMethod(methodName) {
|
||||
if (methodName == null || methodName.value == null) {
|
||||
return false
|
||||
}
|
||||
const name = methodName.value;
|
||||
return (
|
||||
name === "copyWithin" ||
|
||||
name === "fill" ||
|
||||
name === "pop" ||
|
||||
name === "push" ||
|
||||
name === "reverse" ||
|
||||
name === "shift" ||
|
||||
name === "sort" ||
|
||||
name === "splice" ||
|
||||
name === "unshift"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {TSESTreeNodeTypes} T
|
||||
* @callback VisitorCallback
|
||||
* @param {TSESTreeNode & { type: T }} node
|
||||
* @param {Scope|undefined|null} initialScope
|
||||
* @returns {StaticValue | null}
|
||||
*/
|
||||
/**
|
||||
* @typedef { { [K in TSESTreeNodeTypes]?: VisitorCallback<K> } } Operations
|
||||
*/
|
||||
/**
|
||||
* @type {Operations}
|
||||
*/
|
||||
const operations = Object.freeze({
|
||||
ArrayExpression(node, initialScope) {
|
||||
const elements = getElementValues(node.elements, initialScope);
|
||||
return elements != null ? { value: elements } : null
|
||||
},
|
||||
|
||||
AssignmentExpression(node, initialScope) {
|
||||
if (node.operator === "=") {
|
||||
return getStaticValueR(node.right, initialScope)
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
//eslint-disable-next-line complexity
|
||||
BinaryExpression(node, initialScope) {
|
||||
if (node.operator === "in" || node.operator === "instanceof") {
|
||||
// Not supported.
|
||||
return null
|
||||
}
|
||||
|
||||
const left = getStaticValueR(node.left, initialScope);
|
||||
const right = getStaticValueR(node.right, initialScope);
|
||||
if (left != null && right != null) {
|
||||
switch (node.operator) {
|
||||
case "==":
|
||||
return { value: left.value == right.value } //eslint-disable-line eqeqeq
|
||||
case "!=":
|
||||
return { value: left.value != right.value } //eslint-disable-line eqeqeq
|
||||
case "===":
|
||||
return { value: left.value === right.value }
|
||||
case "!==":
|
||||
return { value: left.value !== right.value }
|
||||
case "<":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "<=":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <=
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">=":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >=
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "<<":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) <<
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">>":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >>
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case ">>>":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) >>>
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "+":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) +
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "-":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) -
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "*":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) *
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "/":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) /
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "%":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) %
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "**":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) **
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "|":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) |
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "^":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) ^
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
case "&":
|
||||
return {
|
||||
value:
|
||||
/** @type {any} */ (left.value) &
|
||||
/** @type {any} */ (right.value),
|
||||
}
|
||||
|
||||
// no default
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
CallExpression(node, initialScope) {
|
||||
const calleeNode = node.callee;
|
||||
const args = getElementValues(node.arguments, initialScope);
|
||||
|
||||
if (args != null) {
|
||||
if (calleeNode.type === "MemberExpression") {
|
||||
if (calleeNode.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
const object = getStaticValueR(calleeNode.object, initialScope);
|
||||
if (object != null) {
|
||||
if (
|
||||
object.value == null &&
|
||||
(object.optional || node.optional)
|
||||
) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const property = getStaticPropertyNameValue(
|
||||
calleeNode,
|
||||
initialScope,
|
||||
);
|
||||
|
||||
if (property != null) {
|
||||
const receiver =
|
||||
/** @type {Record<PropertyKey, (...args: any[]) => any>} */ (
|
||||
object.value
|
||||
);
|
||||
const methodName = /** @type {PropertyKey} */ (
|
||||
property.value
|
||||
);
|
||||
if (callAllowed.has(receiver[methodName])) {
|
||||
return {
|
||||
value: receiver[methodName](...args),
|
||||
}
|
||||
}
|
||||
if (callPassThrough.has(receiver[methodName])) {
|
||||
return { value: args[0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const callee = getStaticValueR(calleeNode, initialScope);
|
||||
if (callee != null) {
|
||||
if (callee.value == null && node.optional) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const func = /** @type {(...args: any[]) => any} */ (
|
||||
callee.value
|
||||
);
|
||||
if (callAllowed.has(func)) {
|
||||
return { value: func(...args) }
|
||||
}
|
||||
if (callPassThrough.has(func)) {
|
||||
return { value: args[0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
ConditionalExpression(node, initialScope) {
|
||||
const test = getStaticValueR(node.test, initialScope);
|
||||
if (test != null) {
|
||||
return test.value
|
||||
? getStaticValueR(node.consequent, initialScope)
|
||||
: getStaticValueR(node.alternate, initialScope)
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
ExpressionStatement(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
|
||||
Identifier(node, initialScope) {
|
||||
if (initialScope != null) {
|
||||
const variable = findVariable(initialScope, node);
|
||||
|
||||
if (variable != null) {
|
||||
// Built-in globals.
|
||||
if (isBuiltinGlobal(variable)) {
|
||||
return { value: globalObject[variable.name] }
|
||||
}
|
||||
|
||||
// Constants.
|
||||
if (canBeConsideredConst(variable)) {
|
||||
const def = variable.defs[0];
|
||||
if (
|
||||
// TODO(mysticatea): don't support destructuring here.
|
||||
def.node.id.type === "Identifier"
|
||||
) {
|
||||
const init = getStaticValueR(
|
||||
def.node.init,
|
||||
initialScope,
|
||||
);
|
||||
if (
|
||||
init &&
|
||||
typeof init.value === "object" &&
|
||||
init.value !== null
|
||||
) {
|
||||
if (hasMutationInProperty(variable, initialScope)) {
|
||||
// This variable has mutation in its property.
|
||||
return null
|
||||
}
|
||||
}
|
||||
return init
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
Literal(node) {
|
||||
const literal =
|
||||
/** @type {Partial<Literal> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
|
||||
node
|
||||
);
|
||||
//istanbul ignore if : this is implementation-specific behavior.
|
||||
if (
|
||||
(literal.regex != null || literal.bigint != null) &&
|
||||
literal.value == null
|
||||
) {
|
||||
// It was a RegExp/BigInt literal, but Node.js didn't support it.
|
||||
return null
|
||||
}
|
||||
return { value: literal.value }
|
||||
},
|
||||
|
||||
LogicalExpression(node, initialScope) {
|
||||
const left = getStaticValueR(node.left, initialScope);
|
||||
if (left != null) {
|
||||
if (
|
||||
(node.operator === "||" && Boolean(left.value) === true) ||
|
||||
(node.operator === "&&" && Boolean(left.value) === false) ||
|
||||
(node.operator === "??" && left.value != null)
|
||||
) {
|
||||
return left
|
||||
}
|
||||
|
||||
const right = getStaticValueR(node.right, initialScope);
|
||||
if (right != null) {
|
||||
return right
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
MemberExpression(node, initialScope) {
|
||||
if (node.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
const object = getStaticValueR(node.object, initialScope);
|
||||
if (object != null) {
|
||||
if (object.value == null && (object.optional || node.optional)) {
|
||||
return { value: undefined, optional: true }
|
||||
}
|
||||
const property = getStaticPropertyNameValue(node, initialScope);
|
||||
|
||||
if (property != null) {
|
||||
if (
|
||||
!isGetter(
|
||||
/** @type {object} */ (object.value),
|
||||
/** @type {PropertyKey} */ (property.value),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
value: /** @type {Record<PropertyKey, unknown>} */ (
|
||||
object.value
|
||||
)[/** @type {PropertyKey} */ (property.value)],
|
||||
}
|
||||
}
|
||||
|
||||
for (const [classFn, allowed] of getterAllowed) {
|
||||
if (
|
||||
object.value instanceof classFn &&
|
||||
allowed.has(/** @type {string} */ (property.value))
|
||||
) {
|
||||
return {
|
||||
value: /** @type {Record<PropertyKey, unknown>} */ (
|
||||
object.value
|
||||
)[/** @type {PropertyKey} */ (property.value)],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
ChainExpression(node, initialScope) {
|
||||
const expression = getStaticValueR(node.expression, initialScope);
|
||||
if (expression != null) {
|
||||
return { value: expression.value }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
NewExpression(node, initialScope) {
|
||||
const callee = getStaticValueR(node.callee, initialScope);
|
||||
const args = getElementValues(node.arguments, initialScope);
|
||||
|
||||
if (callee != null && args != null) {
|
||||
const Func = /** @type {new (...args: any[]) => any} */ (
|
||||
callee.value
|
||||
);
|
||||
if (callAllowed.has(Func)) {
|
||||
return { value: new Func(...args) }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
ObjectExpression(node, initialScope) {
|
||||
/** @type {Record<PropertyKey, unknown>} */
|
||||
const object = {};
|
||||
|
||||
for (const propertyNode of node.properties) {
|
||||
if (propertyNode.type === "Property") {
|
||||
if (propertyNode.kind !== "init") {
|
||||
return null
|
||||
}
|
||||
const key = getStaticPropertyNameValue(
|
||||
propertyNode,
|
||||
initialScope,
|
||||
);
|
||||
const value = getStaticValueR(propertyNode.value, initialScope);
|
||||
if (key == null || value == null) {
|
||||
return null
|
||||
}
|
||||
object[/** @type {PropertyKey} */ (key.value)] = value.value;
|
||||
} else if (
|
||||
propertyNode.type === "SpreadElement" ||
|
||||
// @ts-expect-error -- Backward compatibility
|
||||
propertyNode.type === "ExperimentalSpreadProperty"
|
||||
) {
|
||||
const argument = getStaticValueR(
|
||||
propertyNode.argument,
|
||||
initialScope,
|
||||
);
|
||||
if (argument == null) {
|
||||
return null
|
||||
}
|
||||
Object.assign(object, argument.value);
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return { value: object }
|
||||
},
|
||||
|
||||
SequenceExpression(node, initialScope) {
|
||||
const last = node.expressions[node.expressions.length - 1];
|
||||
return getStaticValueR(last, initialScope)
|
||||
},
|
||||
|
||||
TaggedTemplateExpression(node, initialScope) {
|
||||
const tag = getStaticValueR(node.tag, initialScope);
|
||||
const expressions = getElementValues(
|
||||
node.quasi.expressions,
|
||||
initialScope,
|
||||
);
|
||||
|
||||
if (tag != null && expressions != null) {
|
||||
const func = /** @type {(...args: any[]) => any} */ (tag.value);
|
||||
/** @type {any[] & { raw?: string[] }} */
|
||||
const strings = node.quasi.quasis.map((q) => q.value.cooked);
|
||||
strings.raw = node.quasi.quasis.map((q) => q.value.raw);
|
||||
|
||||
if (func === String.raw) {
|
||||
return { value: func(strings, ...expressions) }
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
|
||||
TemplateLiteral(node, initialScope) {
|
||||
const expressions = getElementValues(node.expressions, initialScope);
|
||||
if (expressions != null) {
|
||||
let value = node.quasis[0].value.cooked;
|
||||
for (let i = 0; i < expressions.length; ++i) {
|
||||
value += expressions[i];
|
||||
value += /** @type {string} */ (node.quasis[i + 1].value.cooked);
|
||||
}
|
||||
return { value }
|
||||
}
|
||||
return null
|
||||
},
|
||||
|
||||
UnaryExpression(node, initialScope) {
|
||||
if (node.operator === "delete") {
|
||||
// Not supported.
|
||||
return null
|
||||
}
|
||||
if (node.operator === "void") {
|
||||
return { value: undefined }
|
||||
}
|
||||
|
||||
const arg = getStaticValueR(node.argument, initialScope);
|
||||
if (arg != null) {
|
||||
switch (node.operator) {
|
||||
case "-":
|
||||
return { value: -(/** @type {any} */ (arg.value)) }
|
||||
case "+":
|
||||
return { value: +(/** @type {any} */ (arg.value)) } //eslint-disable-line no-implicit-coercion
|
||||
case "!":
|
||||
return { value: !arg.value }
|
||||
case "~":
|
||||
return { value: ~(/** @type {any} */ (arg.value)) }
|
||||
case "typeof":
|
||||
return { value: typeof arg.value }
|
||||
|
||||
// no default
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
TSAsExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSSatisfiesExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSTypeAssertion(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSNonNullExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
TSInstantiationExpression(node, initialScope) {
|
||||
return getStaticValueR(node.expression, initialScope)
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a static value.
|
||||
* @param {Node|TSESTreeNode|null|undefined} node The node to get.
|
||||
* @param {Scope|undefined|null} initialScope The scope to start finding variable.
|
||||
* @returns {StaticValue|null} The static value of the node, or `null`.
|
||||
*/
|
||||
function getStaticValueR(node, initialScope) {
|
||||
if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
|
||||
return /** @type {VisitorCallback<any>} */ (operations[node.type])(
|
||||
/** @type {TSESTreeNode} */ (node),
|
||||
initialScope,
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the static value of property name from a MemberExpression node or a Property node.
|
||||
* @param {MemberExpression|Property} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {StaticValue|null} The static value of the property name of the node, or `null`.
|
||||
*/
|
||||
function getStaticPropertyNameValue(node, initialScope) {
|
||||
const nameNode = node.type === "Property" ? node.key : node.property;
|
||||
|
||||
if (node.computed) {
|
||||
return getStaticValueR(nameNode, initialScope)
|
||||
}
|
||||
|
||||
if (nameNode.type === "Identifier") {
|
||||
return { value: nameNode.name }
|
||||
}
|
||||
|
||||
if (nameNode.type === "Literal") {
|
||||
if (/** @type {Partial<BigIntLiteral>} */ (nameNode).bigint) {
|
||||
return { value: /** @type {BigIntLiteral} */ (nameNode).bigint }
|
||||
}
|
||||
return { value: String(nameNode.value) }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a static value.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
|
||||
* @returns {StaticValue | null} The static value of the node, or `null`.
|
||||
*/
|
||||
function getStaticValue(node, initialScope = null) {
|
||||
try {
|
||||
return getStaticValueR(node, initialScope)
|
||||
} catch (_error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("estree").RegExpLiteral} RegExpLiteral */
|
||||
/** @typedef {import("estree").BigIntLiteral} BigIntLiteral */
|
||||
/** @typedef {import("estree").SimpleLiteral} SimpleLiteral */
|
||||
|
||||
/**
|
||||
* Get the value of a given node if it's a literal or a template literal.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {Scope|null} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
|
||||
* @returns {string|null} The value of the node, or `null`.
|
||||
*/
|
||||
function getStringIfConstant(node, initialScope = null) {
|
||||
// Handle the literals that the platform doesn't support natively.
|
||||
if (node && node.type === "Literal" && node.value === null) {
|
||||
const literal =
|
||||
/** @type {Partial<SimpleLiteral> & Partial<RegExpLiteral> & Partial<BigIntLiteral>} */ (
|
||||
node
|
||||
);
|
||||
if (literal.regex) {
|
||||
return `/${literal.regex.pattern}/${literal.regex.flags}`
|
||||
}
|
||||
if (literal.bigint) {
|
||||
return literal.bigint
|
||||
}
|
||||
}
|
||||
|
||||
const evaluated = getStaticValue(node, initialScope);
|
||||
|
||||
if (evaluated) {
|
||||
// `String(Symbol.prototype)` throws error
|
||||
try {
|
||||
return String(evaluated.value)
|
||||
} catch {
|
||||
// No op
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("estree").MemberExpression} MemberExpression */
|
||||
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Get the property name from a MemberExpression node or a Property node.
|
||||
* @param {MemberExpression | MethodDefinition | Property | PropertyDefinition} node The node to get.
|
||||
* @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
|
||||
* @returns {string|null|undefined} The property name of the node.
|
||||
*/
|
||||
function getPropertyName(node, initialScope) {
|
||||
switch (node.type) {
|
||||
case "MemberExpression":
|
||||
if (node.computed) {
|
||||
return getStringIfConstant(node.property, initialScope)
|
||||
}
|
||||
if (node.property.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
return /** @type {Partial<Identifier>} */ (node.property).name
|
||||
|
||||
case "Property":
|
||||
case "MethodDefinition":
|
||||
case "PropertyDefinition":
|
||||
if (node.computed) {
|
||||
return getStringIfConstant(node.key, initialScope)
|
||||
}
|
||||
if (node.key.type === "Literal") {
|
||||
return String(node.key.value)
|
||||
}
|
||||
if (node.key.type === "PrivateIdentifier") {
|
||||
return null
|
||||
}
|
||||
return /** @type {Partial<Identifier>} */ (node.key).name
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("estree").Function} FunctionNode */
|
||||
/** @typedef {import("estree").FunctionDeclaration} FunctionDeclaration */
|
||||
/** @typedef {import("estree").FunctionExpression} FunctionExpression */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
|
||||
/**
|
||||
* Get the name and kind of the given function node.
|
||||
* @param {FunctionNode} node - The function node to get.
|
||||
* @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
|
||||
* @returns {string} The name and kind of the function node.
|
||||
*/
|
||||
// eslint-disable-next-line complexity
|
||||
function getFunctionNameWithKind(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
if (!parent) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const tokens = [];
|
||||
const isObjectMethod = parent.type === "Property" && parent.value === node;
|
||||
const isClassMethod =
|
||||
parent.type === "MethodDefinition" && parent.value === node;
|
||||
const isClassFieldMethod =
|
||||
parent.type === "PropertyDefinition" && parent.value === node;
|
||||
|
||||
// Modifiers.
|
||||
if (isClassMethod || isClassFieldMethod) {
|
||||
if (parent.static) {
|
||||
tokens.push("static");
|
||||
}
|
||||
if (parent.key.type === "PrivateIdentifier") {
|
||||
tokens.push("private");
|
||||
}
|
||||
}
|
||||
if (node.async) {
|
||||
tokens.push("async");
|
||||
}
|
||||
if (node.generator) {
|
||||
tokens.push("generator");
|
||||
}
|
||||
|
||||
// Kinds.
|
||||
if (isObjectMethod || isClassMethod) {
|
||||
if (parent.kind === "constructor") {
|
||||
return "constructor"
|
||||
}
|
||||
if (parent.kind === "get") {
|
||||
tokens.push("getter");
|
||||
} else if (parent.kind === "set") {
|
||||
tokens.push("setter");
|
||||
} else {
|
||||
tokens.push("method");
|
||||
}
|
||||
} else if (isClassFieldMethod) {
|
||||
tokens.push("method");
|
||||
} else {
|
||||
if (node.type === "ArrowFunctionExpression") {
|
||||
tokens.push("arrow");
|
||||
}
|
||||
tokens.push("function");
|
||||
}
|
||||
|
||||
// Names.
|
||||
if (isObjectMethod || isClassMethod || isClassFieldMethod) {
|
||||
if (parent.key.type === "PrivateIdentifier") {
|
||||
tokens.push(`#${parent.key.name}`);
|
||||
} else {
|
||||
const name = getPropertyName(parent);
|
||||
if (name) {
|
||||
tokens.push(`'${name}'`);
|
||||
} else if (sourceCode) {
|
||||
const keyText = sourceCode.getText(parent.key);
|
||||
if (!keyText.includes("\n")) {
|
||||
tokens.push(`[${keyText}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (hasId(node)) {
|
||||
tokens.push(`'${node.id.name}'`);
|
||||
} else if (
|
||||
parent.type === "VariableDeclarator" &&
|
||||
parent.id &&
|
||||
parent.id.type === "Identifier"
|
||||
) {
|
||||
tokens.push(`'${parent.id.name}'`);
|
||||
} else if (
|
||||
(parent.type === "AssignmentExpression" ||
|
||||
parent.type === "AssignmentPattern") &&
|
||||
parent.left &&
|
||||
parent.left.type === "Identifier"
|
||||
) {
|
||||
tokens.push(`'${parent.left.name}'`);
|
||||
} else if (
|
||||
parent.type === "ExportDefaultDeclaration" &&
|
||||
parent.declaration === node
|
||||
) {
|
||||
tokens.push("'default'");
|
||||
}
|
||||
|
||||
return tokens.join(" ")
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FunctionNode} node
|
||||
* @returns {node is FunctionDeclaration | FunctionExpression & { id: Identifier }}
|
||||
*/
|
||||
function hasId(node) {
|
||||
return Boolean(
|
||||
/** @type {Partial<FunctionDeclaration | FunctionExpression>} */ (node)
|
||||
.id,
|
||||
)
|
||||
}
|
||||
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("./types.mjs").HasSideEffectOptions} HasSideEffectOptions */
|
||||
/** @typedef {import("estree").BinaryExpression} BinaryExpression */
|
||||
/** @typedef {import("estree").MemberExpression} MemberExpression */
|
||||
/** @typedef {import("estree").MethodDefinition} MethodDefinition */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").PropertyDefinition} PropertyDefinition */
|
||||
/** @typedef {import("estree").UnaryExpression} UnaryExpression */
|
||||
|
||||
const typeConversionBinaryOps = Object.freeze(
|
||||
new Set([
|
||||
"==",
|
||||
"!=",
|
||||
"<",
|
||||
"<=",
|
||||
">",
|
||||
">=",
|
||||
"<<",
|
||||
">>",
|
||||
">>>",
|
||||
"+",
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"%",
|
||||
"|",
|
||||
"^",
|
||||
"&",
|
||||
"in",
|
||||
]),
|
||||
);
|
||||
const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
|
||||
|
||||
/**
|
||||
* Check whether the given value is an ASTNode or not.
|
||||
* @param {any} x The value to check.
|
||||
* @returns {x is Node} `true` if the value is an ASTNode.
|
||||
*/
|
||||
function isNode(x) {
|
||||
return x !== null && typeof x === "object" && typeof x.type === "string"
|
||||
}
|
||||
|
||||
const visitor = Object.freeze(
|
||||
Object.assign(Object.create(null), {
|
||||
/**
|
||||
* @param {Node} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
$visit(node, options, visitorKeys) {
|
||||
const { type } = node;
|
||||
|
||||
if (typeof (/** @type {any} */ (this)[type]) === "function") {
|
||||
return /** @type {any} */ (this)[type](
|
||||
node,
|
||||
options,
|
||||
visitorKeys,
|
||||
)
|
||||
}
|
||||
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {Node} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
$visitChildren(node, options, visitorKeys) {
|
||||
const { type } = node;
|
||||
|
||||
for (const key of /** @type {(keyof Node)[]} */ (
|
||||
visitorKeys[type] || getKeys(node)
|
||||
)) {
|
||||
const value = node[key];
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const element of value) {
|
||||
if (
|
||||
isNode(element) &&
|
||||
this.$visit(element, options, visitorKeys)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
isNode(value) &&
|
||||
this.$visit(value, options, visitorKeys)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
|
||||
ArrowFunctionExpression() {
|
||||
return false
|
||||
},
|
||||
AssignmentExpression() {
|
||||
return true
|
||||
},
|
||||
AwaitExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {BinaryExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
BinaryExpression(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
typeConversionBinaryOps.has(node.operator) &&
|
||||
(node.left.type !== "Literal" || node.right.type !== "Literal")
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
CallExpression() {
|
||||
return true
|
||||
},
|
||||
FunctionExpression() {
|
||||
return false
|
||||
},
|
||||
ImportExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {MemberExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
MemberExpression(node, options, visitorKeys) {
|
||||
if (options.considerGetters) {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.property.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {MethodDefinition} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
MethodDefinition(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
NewExpression() {
|
||||
return true
|
||||
},
|
||||
/**
|
||||
* @param {Property} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
Property(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {PropertyDefinition} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
PropertyDefinition(node, options, visitorKeys) {
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
node.computed &&
|
||||
node.key.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
/**
|
||||
* @param {UnaryExpression} node
|
||||
* @param {HasSideEffectOptions} options
|
||||
* @param {Record<string, string[]>} visitorKeys
|
||||
*/
|
||||
UnaryExpression(node, options, visitorKeys) {
|
||||
if (node.operator === "delete") {
|
||||
return true
|
||||
}
|
||||
if (
|
||||
options.considerImplicitTypeConversion &&
|
||||
typeConversionUnaryOps.has(node.operator) &&
|
||||
node.argument.type !== "Literal"
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return this.$visitChildren(node, options, visitorKeys)
|
||||
},
|
||||
UpdateExpression() {
|
||||
return true
|
||||
},
|
||||
YieldExpression() {
|
||||
return true
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* Check whether a given node has any side effect or not.
|
||||
* @param {Node} node The node to get.
|
||||
* @param {SourceCode} sourceCode The source code object.
|
||||
* @param {HasSideEffectOptions} [options] The option object.
|
||||
* @returns {boolean} `true` if the node has a certain side effect.
|
||||
*/
|
||||
function hasSideEffect(node, sourceCode, options = {}) {
|
||||
const { considerGetters = false, considerImplicitTypeConversion = false } =
|
||||
options;
|
||||
return visitor.$visit(
|
||||
node,
|
||||
{ considerGetters, considerImplicitTypeConversion },
|
||||
sourceCode.visitorKeys || KEYS,
|
||||
)
|
||||
}
|
||||
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.NewExpression} TSNewExpression */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.CallExpression} TSCallExpression */
|
||||
/** @typedef {import("eslint").SourceCode} SourceCode */
|
||||
/** @typedef {import("eslint").AST.Token} Token */
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
|
||||
/**
|
||||
* Get the left parenthesis of the parent node syntax if it exists.
|
||||
* E.g., `if (a) {}` then the `(`.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {Token|null} The left parenthesis of the parent node syntax
|
||||
*/
|
||||
// eslint-disable-next-line complexity
|
||||
function getParentSyntaxParen(node, sourceCode) {
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
|
||||
if (!parent) {
|
||||
return null
|
||||
}
|
||||
|
||||
switch (parent.type) {
|
||||
case "CallExpression":
|
||||
case "NewExpression":
|
||||
if (parent.arguments.length === 1 && parent.arguments[0] === node) {
|
||||
return sourceCode.getTokenAfter(
|
||||
// @ts-expect-error https://github.com/typescript-eslint/typescript-eslint/pull/5384
|
||||
parent.typeArguments ||
|
||||
/** @type {RuleNode} */ (
|
||||
/** @type {unknown} */ (
|
||||
/** @type {TSNewExpression | TSCallExpression} */ (
|
||||
parent
|
||||
).typeParameters
|
||||
)
|
||||
) ||
|
||||
parent.callee,
|
||||
isOpeningParenToken,
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
case "DoWhileStatement":
|
||||
if (parent.test === node) {
|
||||
return sourceCode.getTokenAfter(
|
||||
parent.body,
|
||||
isOpeningParenToken,
|
||||
)
|
||||
}
|
||||
return null
|
||||
|
||||
case "IfStatement":
|
||||
case "WhileStatement":
|
||||
if (parent.test === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "ImportExpression":
|
||||
if (parent.source === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "SwitchStatement":
|
||||
if (parent.discriminant === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
case "WithStatement":
|
||||
if (parent.object === node) {
|
||||
return sourceCode.getFirstToken(parent, 1)
|
||||
}
|
||||
return null
|
||||
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {number} times The number of parantheses.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {boolean} `true` if the node is parenthesized the given times.
|
||||
*/
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {Node} node The AST node to check.
|
||||
* @param {SourceCode} sourceCode The source code object to get tokens.
|
||||
* @returns {boolean} `true` if the node is parenthesized.
|
||||
*/
|
||||
/**
|
||||
* Check whether a given node is parenthesized or not.
|
||||
* @param {Node|number} timesOrNode The first parameter.
|
||||
* @param {Node|SourceCode} nodeOrSourceCode The second parameter.
|
||||
* @param {SourceCode} [optionalSourceCode] The third parameter.
|
||||
* @returns {boolean} `true` if the node is parenthesized.
|
||||
*/
|
||||
function isParenthesized(
|
||||
timesOrNode,
|
||||
nodeOrSourceCode,
|
||||
optionalSourceCode,
|
||||
) {
|
||||
/** @type {number} */
|
||||
let times,
|
||||
/** @type {RuleNode} */
|
||||
node,
|
||||
/** @type {SourceCode} */
|
||||
sourceCode,
|
||||
maybeLeftParen,
|
||||
maybeRightParen;
|
||||
if (typeof timesOrNode === "number") {
|
||||
times = timesOrNode | 0;
|
||||
node = /** @type {RuleNode} */ (nodeOrSourceCode);
|
||||
sourceCode = /** @type {SourceCode} */ (optionalSourceCode);
|
||||
if (!(times >= 1)) {
|
||||
throw new TypeError("'times' should be a positive integer.")
|
||||
}
|
||||
} else {
|
||||
times = 1;
|
||||
node = /** @type {RuleNode} */ (timesOrNode);
|
||||
sourceCode = /** @type {SourceCode} */ (nodeOrSourceCode);
|
||||
}
|
||||
|
||||
if (
|
||||
node == null ||
|
||||
// `Program` can't be parenthesized
|
||||
node.parent == null ||
|
||||
// `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
|
||||
(node.parent.type === "CatchClause" && node.parent.param === node)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
maybeLeftParen = maybeRightParen = node;
|
||||
do {
|
||||
maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
|
||||
maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
|
||||
} while (
|
||||
maybeLeftParen != null &&
|
||||
maybeRightParen != null &&
|
||||
isOpeningParenToken(maybeLeftParen) &&
|
||||
isClosingParenToken(maybeRightParen) &&
|
||||
// Avoid false positive such as `if (a) {}`
|
||||
maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
|
||||
--times > 0
|
||||
)
|
||||
|
||||
return times === 0
|
||||
}
|
||||
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
|
||||
const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
|
||||
|
||||
/** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
|
||||
const internal = new WeakMap();
|
||||
|
||||
/**
|
||||
* Check whether a given character is escaped or not.
|
||||
* @param {string} str The string to check.
|
||||
* @param {number} index The location of the character to check.
|
||||
* @returns {boolean} `true` if the character is escaped.
|
||||
*/
|
||||
function isEscaped(str, index) {
|
||||
let escaped = false;
|
||||
for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
|
||||
escaped = !escaped;
|
||||
}
|
||||
return escaped
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string by a given matcher.
|
||||
* @param {PatternMatcher} matcher The pattern matcher.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {string} replacement The new substring to replace each matched part.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replaceS(matcher, str, replacement) {
|
||||
const chunks = [];
|
||||
let index = 0;
|
||||
|
||||
/**
|
||||
* @param {string} key The placeholder.
|
||||
* @param {RegExpExecArray} match The matched information.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replacer(key, match) {
|
||||
switch (key) {
|
||||
case "$$":
|
||||
return "$"
|
||||
case "$&":
|
||||
return match[0]
|
||||
case "$`":
|
||||
return str.slice(0, match.index)
|
||||
case "$'":
|
||||
return str.slice(match.index + match[0].length)
|
||||
default: {
|
||||
const i = key.slice(1);
|
||||
if (i in match) {
|
||||
return match[/** @type {any} */ (i)]
|
||||
}
|
||||
return key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const match of matcher.execAll(str)) {
|
||||
chunks.push(str.slice(index, match.index));
|
||||
chunks.push(
|
||||
replacement.replace(placeholder, (key) => replacer(key, match)),
|
||||
);
|
||||
index = match.index + match[0].length;
|
||||
}
|
||||
chunks.push(str.slice(index));
|
||||
|
||||
return chunks.join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string by a given matcher.
|
||||
* @param {PatternMatcher} matcher The pattern matcher.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {(substring: string, ...args: any[]) => string} replace The function to replace each matched part.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
function replaceF(matcher, str, replace) {
|
||||
const chunks = [];
|
||||
let index = 0;
|
||||
|
||||
for (const match of matcher.execAll(str)) {
|
||||
chunks.push(str.slice(index, match.index));
|
||||
chunks.push(
|
||||
String(
|
||||
replace(
|
||||
.../** @type {[string, ...string[]]} */ (
|
||||
/** @type {string[]} */ (match)
|
||||
),
|
||||
match.index,
|
||||
match.input,
|
||||
),
|
||||
),
|
||||
);
|
||||
index = match.index + match[0].length;
|
||||
}
|
||||
chunks.push(str.slice(index));
|
||||
|
||||
return chunks.join("")
|
||||
}
|
||||
|
||||
/**
|
||||
* The class to find patterns as considering escape sequences.
|
||||
*/
|
||||
class PatternMatcher {
|
||||
/**
|
||||
* Initialize this matcher.
|
||||
* @param {RegExp} pattern The pattern to match.
|
||||
* @param {{escaped?:boolean}} [options] The options.
|
||||
*/
|
||||
constructor(pattern, options = {}) {
|
||||
const { escaped = false } = options;
|
||||
if (!(pattern instanceof RegExp)) {
|
||||
throw new TypeError("'pattern' should be a RegExp instance.")
|
||||
}
|
||||
if (!pattern.flags.includes("g")) {
|
||||
throw new Error("'pattern' should contains 'g' flag.")
|
||||
}
|
||||
|
||||
internal.set(this, {
|
||||
pattern: new RegExp(pattern.source, pattern.flags),
|
||||
escaped: Boolean(escaped),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the pattern in a given string.
|
||||
* @param {string} str The string to find.
|
||||
* @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
|
||||
*/
|
||||
*execAll(str) {
|
||||
const { pattern, escaped } =
|
||||
/** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this));
|
||||
let match = null;
|
||||
let lastIndex = 0;
|
||||
|
||||
pattern.lastIndex = 0;
|
||||
while ((match = pattern.exec(str)) != null) {
|
||||
if (escaped || !isEscaped(str, match.index)) {
|
||||
lastIndex = pattern.lastIndex;
|
||||
yield match;
|
||||
pattern.lastIndex = lastIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the pattern is found in a given string.
|
||||
* @param {string} str The string to check.
|
||||
* @returns {boolean} `true` if the pattern was found in the string.
|
||||
*/
|
||||
test(str) {
|
||||
const it = this.execAll(str);
|
||||
const ret = it.next();
|
||||
return !ret.done
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a given string.
|
||||
* @param {string} str The string to be replaced.
|
||||
* @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
|
||||
* @returns {string} The replaced string.
|
||||
*/
|
||||
[Symbol.replace](str, replacer) {
|
||||
return typeof replacer === "function"
|
||||
? replaceF(this, String(str), replacer)
|
||||
: replaceS(this, String(str), String(replacer))
|
||||
}
|
||||
}
|
||||
|
||||
/** @typedef {import("eslint").Scope.Scope} Scope */
|
||||
/** @typedef {import("eslint").Scope.Variable} Variable */
|
||||
/** @typedef {import("eslint").Rule.Node} RuleNode */
|
||||
/** @typedef {import("estree").Node} Node */
|
||||
/** @typedef {import("estree").Expression} Expression */
|
||||
/** @typedef {import("estree").Pattern} Pattern */
|
||||
/** @typedef {import("estree").Identifier} Identifier */
|
||||
/** @typedef {import("estree").SimpleCallExpression} CallExpression */
|
||||
/** @typedef {import("estree").Program} Program */
|
||||
/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
|
||||
/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
|
||||
/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
|
||||
/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
|
||||
/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
|
||||
/** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */
|
||||
/** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */
|
||||
/** @typedef {import("estree").ExportSpecifier} ExportSpecifier */
|
||||
/** @typedef {import("estree").Property} Property */
|
||||
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
|
||||
/** @typedef {import("estree").Literal} Literal */
|
||||
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
|
||||
/** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TraceMap<T>} TraceMap
|
||||
*/
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TraceMapObject<T>} TraceMapObject
|
||||
*/
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {import("./types.mjs").TrackedReferences<T>} TrackedReferences
|
||||
*/
|
||||
|
||||
const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
|
||||
|
||||
/**
|
||||
* Check whether a given node is an import node or not.
|
||||
* @param {Node} node
|
||||
* @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.
|
||||
*/
|
||||
function isHasSource(node) {
|
||||
return (
|
||||
IMPORT_TYPE.test(node.type) &&
|
||||
/** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (
|
||||
node
|
||||
).source != null
|
||||
)
|
||||
}
|
||||
const has =
|
||||
/** @type {<T>(traceMap: TraceMap<unknown>, v: T) => v is (string extends T ? string : T)} */ (
|
||||
Function.call.bind(Object.hasOwnProperty)
|
||||
);
|
||||
|
||||
const READ = Symbol("read");
|
||||
const CALL = Symbol("call");
|
||||
const CONSTRUCT = Symbol("construct");
|
||||
const ESM = Symbol("esm");
|
||||
|
||||
const requireCall = { require: { [CALL]: true } };
|
||||
|
||||
/**
|
||||
* Check whether a given variable is modified or not.
|
||||
* @param {Variable|undefined} variable The variable to check.
|
||||
* @returns {boolean} `true` if the variable is modified.
|
||||
*/
|
||||
function isModifiedGlobal(variable) {
|
||||
return (
|
||||
variable == null ||
|
||||
variable.defs.length !== 0 ||
|
||||
variable.references.some((r) => r.isWrite())
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the value of a given node is passed through to the parent syntax as-is.
|
||||
* For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
|
||||
* @param {Node} node A node to check.
|
||||
* @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.
|
||||
*/
|
||||
function isPassThrough(node) {
|
||||
const parent = /** @type {TSESTreeNode} */ (node).parent;
|
||||
|
||||
if (parent) {
|
||||
switch (parent.type) {
|
||||
case "ConditionalExpression":
|
||||
return parent.consequent === node || parent.alternate === node
|
||||
case "LogicalExpression":
|
||||
return true
|
||||
case "SequenceExpression":
|
||||
return (
|
||||
parent.expressions[parent.expressions.length - 1] === node
|
||||
)
|
||||
case "ChainExpression":
|
||||
return true
|
||||
case "TSAsExpression":
|
||||
case "TSSatisfiesExpression":
|
||||
case "TSTypeAssertion":
|
||||
case "TSNonNullExpression":
|
||||
case "TSInstantiationExpression":
|
||||
return true
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference tracker.
|
||||
*/
|
||||
class ReferenceTracker {
|
||||
/**
|
||||
* Initialize this tracker.
|
||||
* @param {Scope} globalScope The global scope.
|
||||
* @param {object} [options] The options.
|
||||
* @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
|
||||
* @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
|
||||
*/
|
||||
constructor(globalScope, options = {}) {
|
||||
const {
|
||||
mode = "strict",
|
||||
globalObjectNames = ["global", "globalThis", "self", "window"],
|
||||
} = options;
|
||||
/** @private @type {Variable[]} */
|
||||
this.variableStack = [];
|
||||
/** @private */
|
||||
this.globalScope = globalScope;
|
||||
/** @private */
|
||||
this.mode = mode;
|
||||
/** @private */
|
||||
this.globalObjectNames = globalObjectNames.slice(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of global variables.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateGlobalReferences(traceMap) {
|
||||
for (const key of Object.keys(traceMap)) {
|
||||
const nextTraceMap = traceMap[key];
|
||||
const path = [key];
|
||||
const variable = this.globalScope.set.get(key);
|
||||
|
||||
if (isModifiedGlobal(variable)) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (variable),
|
||||
path,
|
||||
nextTraceMap,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
for (const key of this.globalObjectNames) {
|
||||
/** @type {string[]} */
|
||||
const path = [];
|
||||
const variable = this.globalScope.set.get(key);
|
||||
|
||||
if (isModifiedGlobal(variable)) {
|
||||
continue
|
||||
}
|
||||
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (variable),
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of CommonJS modules.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateCjsReferences(traceMap) {
|
||||
for (const { node } of this.iterateGlobalReferences(requireCall)) {
|
||||
const key = getStringIfConstant(
|
||||
/** @type {CallExpression} */ (node).arguments[0],
|
||||
);
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const nextTraceMap = traceMap[key];
|
||||
const path = [key];
|
||||
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node,
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iteratePropertyReferences(
|
||||
/** @type {CallExpression} */ (node),
|
||||
path,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references of ES modules.
|
||||
* @template T
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*iterateEsmReferences(traceMap) {
|
||||
const programNode = /** @type {Program} */ (this.globalScope.block);
|
||||
|
||||
for (const node of programNode.body) {
|
||||
if (!isHasSource(node)) {
|
||||
continue
|
||||
}
|
||||
const moduleId = /** @type {string} */ (node.source.value);
|
||||
|
||||
if (!has(traceMap, moduleId)) {
|
||||
continue
|
||||
}
|
||||
const nextTraceMap = traceMap[moduleId];
|
||||
const path = [moduleId];
|
||||
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
// eslint-disable-next-line object-shorthand -- apply type
|
||||
node: /** @type {RuleNode} */ (node),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
|
||||
if (node.type === "ExportAllDeclaration") {
|
||||
for (const key of Object.keys(nextTraceMap)) {
|
||||
const exportTraceMap = nextTraceMap[key];
|
||||
if (exportTraceMap[READ]) {
|
||||
yield {
|
||||
// eslint-disable-next-line object-shorthand -- apply type
|
||||
node: /** @type {RuleNode} */ (node),
|
||||
path: path.concat(key),
|
||||
type: READ,
|
||||
info: exportTraceMap[READ],
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const specifier of node.specifiers) {
|
||||
const esm = has(nextTraceMap, ESM);
|
||||
const it = this._iterateImportReferences(
|
||||
specifier,
|
||||
path,
|
||||
esm
|
||||
? nextTraceMap
|
||||
: this.mode === "legacy"
|
||||
? { default: nextTraceMap, ...nextTraceMap }
|
||||
: { default: nextTraceMap },
|
||||
);
|
||||
|
||||
if (esm) {
|
||||
yield* it;
|
||||
} else {
|
||||
for (const report of it) {
|
||||
report.path = report.path.filter(exceptDefault);
|
||||
if (
|
||||
report.path.length >= 2 ||
|
||||
report.type !== READ
|
||||
) {
|
||||
yield report;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the property references for a given expression AST node.
|
||||
* @template T
|
||||
* @param {Expression} node The expression AST node to iterate property references.
|
||||
* @param {TraceMap<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate property references.
|
||||
*/
|
||||
*iteratePropertyReferences(node, traceMap) {
|
||||
yield* this._iteratePropertyReferences(node, [], traceMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given variable.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Variable} variable The variable to iterate that references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @param {boolean} shouldReport = The flag to report those references.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateVariableReferences(variable, path, traceMap, shouldReport) {
|
||||
if (this.variableStack.includes(variable)) {
|
||||
return
|
||||
}
|
||||
this.variableStack.push(variable);
|
||||
try {
|
||||
for (const reference of variable.references) {
|
||||
if (!reference.isRead()) {
|
||||
continue
|
||||
}
|
||||
const node = /** @type {RuleNode & Identifier} */ (
|
||||
reference.identifier
|
||||
);
|
||||
|
||||
if (shouldReport && traceMap[READ]) {
|
||||
yield { node, path, type: READ, info: traceMap[READ] };
|
||||
}
|
||||
yield* this._iteratePropertyReferences(node, path, traceMap);
|
||||
}
|
||||
} finally {
|
||||
this.variableStack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given AST node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Expression} rootNode The AST node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
//eslint-disable-next-line complexity
|
||||
*_iteratePropertyReferences(rootNode, path, traceMap) {
|
||||
let node = rootNode;
|
||||
while (isPassThrough(node)) {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
const parent = /** @type {RuleNode} */ (node).parent;
|
||||
if (!parent) {
|
||||
return
|
||||
}
|
||||
if (parent.type === "MemberExpression") {
|
||||
if (parent.object === node) {
|
||||
const key = getPropertyName(parent);
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: parent,
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iteratePropertyReferences(
|
||||
parent,
|
||||
path,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "CallExpression") {
|
||||
if (parent.callee === node && traceMap[CALL]) {
|
||||
yield { node: parent, path, type: CALL, info: traceMap[CALL] };
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "NewExpression") {
|
||||
if (parent.callee === node && traceMap[CONSTRUCT]) {
|
||||
yield {
|
||||
node: parent,
|
||||
path,
|
||||
type: CONSTRUCT,
|
||||
info: traceMap[CONSTRUCT],
|
||||
};
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "AssignmentExpression") {
|
||||
if (parent.right === node) {
|
||||
yield* this._iterateLhsReferences(parent.left, path, traceMap);
|
||||
yield* this._iteratePropertyReferences(parent, path, traceMap);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "AssignmentPattern") {
|
||||
if (parent.right === node) {
|
||||
yield* this._iterateLhsReferences(parent.left, path, traceMap);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (parent.type === "VariableDeclarator") {
|
||||
if (parent.init === node) {
|
||||
yield* this._iterateLhsReferences(parent.id, path, traceMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given Pattern node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {Pattern} patternNode The Pattern node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateLhsReferences(patternNode, path, traceMap) {
|
||||
if (patternNode.type === "Identifier") {
|
||||
const variable = findVariable(this.globalScope, patternNode);
|
||||
if (variable != null) {
|
||||
yield* this._iterateVariableReferences(
|
||||
variable,
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (patternNode.type === "ObjectPattern") {
|
||||
for (const property of patternNode.properties) {
|
||||
const key = getPropertyName(
|
||||
/** @type {AssignmentProperty} */ (property),
|
||||
);
|
||||
|
||||
if (key == null || !has(traceMap, key)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const nextPath = path.concat(key);
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (property),
|
||||
path: nextPath,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iterateLhsReferences(
|
||||
/** @type {AssignmentProperty} */ (property).value,
|
||||
nextPath,
|
||||
nextTraceMap,
|
||||
);
|
||||
}
|
||||
return
|
||||
}
|
||||
if (patternNode.type === "AssignmentPattern") {
|
||||
yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the references for a given ModuleSpecifier node.
|
||||
* @private
|
||||
* @template T
|
||||
* @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.
|
||||
* @param {string[]} path The current path.
|
||||
* @param {TraceMapObject<T>} traceMap The trace map.
|
||||
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
|
||||
*/
|
||||
*_iterateImportReferences(specifierNode, path, traceMap) {
|
||||
const type = specifierNode.type;
|
||||
|
||||
if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
|
||||
const key =
|
||||
type === "ImportDefaultSpecifier"
|
||||
? "default"
|
||||
: specifierNode.imported.type === "Identifier"
|
||||
? specifierNode.imported.name
|
||||
: specifierNode.imported.value;
|
||||
if (!has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (specifierNode),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (
|
||||
findVariable(this.globalScope, specifierNode.local)
|
||||
),
|
||||
path,
|
||||
nextTraceMap,
|
||||
false,
|
||||
);
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (type === "ImportNamespaceSpecifier") {
|
||||
yield* this._iterateVariableReferences(
|
||||
/** @type {Variable} */ (
|
||||
findVariable(this.globalScope, specifierNode.local)
|
||||
),
|
||||
path,
|
||||
traceMap,
|
||||
false,
|
||||
);
|
||||
return
|
||||
}
|
||||
|
||||
if (type === "ExportSpecifier") {
|
||||
const key =
|
||||
specifierNode.local.type === "Identifier"
|
||||
? specifierNode.local.name
|
||||
: specifierNode.local.value;
|
||||
if (!has(traceMap, key)) {
|
||||
return
|
||||
}
|
||||
|
||||
path = path.concat(key); //eslint-disable-line no-param-reassign
|
||||
const nextTraceMap = traceMap[key];
|
||||
if (nextTraceMap[READ]) {
|
||||
yield {
|
||||
node: /** @type {RuleNode} */ (specifierNode),
|
||||
path,
|
||||
type: READ,
|
||||
info: nextTraceMap[READ],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReferenceTracker.READ = READ;
|
||||
ReferenceTracker.CALL = CALL;
|
||||
ReferenceTracker.CONSTRUCT = CONSTRUCT;
|
||||
ReferenceTracker.ESM = ESM;
|
||||
|
||||
/**
|
||||
* This is a predicate function for Array#filter.
|
||||
* @param {string} name A name part.
|
||||
* @param {number} index The index of the name.
|
||||
* @returns {boolean} `false` if it's default.
|
||||
*/
|
||||
function exceptDefault(name, index) {
|
||||
return !(index === 1 && name === "default")
|
||||
}
|
||||
|
||||
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
|
||||
|
||||
var index = {
|
||||
CALL,
|
||||
CONSTRUCT,
|
||||
ESM,
|
||||
findVariable,
|
||||
getFunctionHeadLocation,
|
||||
getFunctionNameWithKind,
|
||||
getInnermostScope,
|
||||
getPropertyName,
|
||||
getStaticValue,
|
||||
getStringIfConstant,
|
||||
hasSideEffect,
|
||||
isArrowToken,
|
||||
isClosingBraceToken,
|
||||
isClosingBracketToken,
|
||||
isClosingParenToken,
|
||||
isColonToken,
|
||||
isCommaToken,
|
||||
isCommentToken,
|
||||
isNotArrowToken,
|
||||
isNotClosingBraceToken,
|
||||
isNotClosingBracketToken,
|
||||
isNotClosingParenToken,
|
||||
isNotColonToken,
|
||||
isNotCommaToken,
|
||||
isNotCommentToken,
|
||||
isNotOpeningBraceToken,
|
||||
isNotOpeningBracketToken,
|
||||
isNotOpeningParenToken,
|
||||
isNotSemicolonToken,
|
||||
isOpeningBraceToken,
|
||||
isOpeningBracketToken,
|
||||
isOpeningParenToken,
|
||||
isParenthesized,
|
||||
isSemicolonToken,
|
||||
PatternMatcher,
|
||||
READ,
|
||||
ReferenceTracker,
|
||||
};
|
||||
|
||||
export { CALL, CONSTRUCT, ESM, PatternMatcher, READ, ReferenceTracker, index as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
//# sourceMappingURL=index.mjs.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+89
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"name": "@eslint-community/eslint-utils",
|
||||
"version": "4.9.1",
|
||||
"description": "Utilities for ESLint plugins.",
|
||||
"keywords": [
|
||||
"eslint"
|
||||
],
|
||||
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint-community/eslint-utils/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint-community/eslint-utils"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Toru Nagashima",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.mjs",
|
||||
"require": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "index",
|
||||
"module": "index.mjs",
|
||||
"files": [
|
||||
"index.*"
|
||||
],
|
||||
"scripts": {
|
||||
"prebuild": "npm run -s clean",
|
||||
"build": "npm run build:dts && npm run build:rollup",
|
||||
"build:dts": "tsc -p tsconfig.build.json",
|
||||
"build:rollup": "rollup -c",
|
||||
"clean": "rimraf .nyc_output coverage index.* dist",
|
||||
"coverage": "opener ./coverage/lcov-report/index.html",
|
||||
"docs:build": "vitepress build docs",
|
||||
"docs:watch": "vitepress dev docs",
|
||||
"format": "npm run -s format:prettier -- --write",
|
||||
"format:prettier": "prettier .",
|
||||
"format:check": "npm run -s format:prettier -- --check",
|
||||
"lint:eslint": "eslint .",
|
||||
"lint:format": "npm run -s format:check",
|
||||
"lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts",
|
||||
"lint:knip": "knip",
|
||||
"lint": "run-p lint:*",
|
||||
"test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"",
|
||||
"test": "mocha --reporter dot \"test/*.mjs\"",
|
||||
"preversion": "npm run test-coverage && npm run -s build",
|
||||
"postversion": "git push && git push --tags",
|
||||
"prewatch": "npm run -s clean",
|
||||
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"eslint-visitor-keys": "^3.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-mysticatea": "^15.6.1",
|
||||
"@types/eslint": "^9.6.1",
|
||||
"@types/estree": "^1.0.7",
|
||||
"@typescript-eslint/parser": "^5.62.0",
|
||||
"@typescript-eslint/types": "^5.62.0",
|
||||
"c8": "^8.0.1",
|
||||
"dot-prop": "^7.2.0",
|
||||
"eslint": "^8.57.1",
|
||||
"installed-check": "^8.0.1",
|
||||
"knip": "^5.33.3",
|
||||
"mocha": "^9.2.2",
|
||||
"npm-run-all2": "^6.2.3",
|
||||
"opener": "^1.5.2",
|
||||
"prettier": "2.8.8",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.79.2",
|
||||
"rollup-plugin-dts": "^4.2.3",
|
||||
"rollup-plugin-sourcemaps": "^0.6.3",
|
||||
"semver": "^7.6.3",
|
||||
"typescript": "^4.9.5",
|
||||
"vitepress": "^1.4.1",
|
||||
"warun": "^1.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": "https://opencollective.com/eslint"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# @eslint-community/regexpp
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/regexpp)
|
||||
[](http://www.npmtrends.com/@eslint-community/regexpp)
|
||||
[](https://github.com/eslint-community/regexpp/actions)
|
||||
[](https://codecov.io/gh/eslint-community/regexpp)
|
||||
|
||||
A regular expression parser for ECMAScript.
|
||||
|
||||
## 💿 Installation
|
||||
|
||||
```bash
|
||||
$ npm install @eslint-community/regexpp
|
||||
```
|
||||
|
||||
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
```ts
|
||||
import {
|
||||
AST,
|
||||
RegExpParser,
|
||||
RegExpValidator,
|
||||
RegExpVisitor,
|
||||
parseRegExpLiteral,
|
||||
validateRegExpLiteral,
|
||||
visitRegExpAST
|
||||
} from "@eslint-community/regexpp"
|
||||
```
|
||||
|
||||
### parseRegExpLiteral(source, options?)
|
||||
|
||||
Parse a given regular expression literal then make AST object.
|
||||
|
||||
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string | RegExp`) The source code to parse.
|
||||
- `options?` ([`RegExpParser.Options`]) The options to parse.
|
||||
- **Return:**
|
||||
- The AST of the regular expression.
|
||||
|
||||
### validateRegExpLiteral(source, options?)
|
||||
|
||||
Validate a given regular expression literal.
|
||||
|
||||
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `options?` ([`RegExpValidator.Options`]) The options to validate.
|
||||
|
||||
### visitRegExpAST(ast, handlers)
|
||||
|
||||
Visit each node of a given AST.
|
||||
|
||||
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `ast` ([`AST.Node`]) The AST to visit.
|
||||
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
|
||||
|
||||
### RegExpParser
|
||||
|
||||
#### new RegExpParser(options?)
|
||||
|
||||
- **Parameters:**
|
||||
- `options?` ([`RegExpParser.Options`]) The options to parse.
|
||||
|
||||
#### parser.parseLiteral(source, start?, end?)
|
||||
|
||||
Parse a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- **Return:**
|
||||
- The AST of the regular expression.
|
||||
|
||||
#### parser.parsePattern(source, start?, end?, flags?)
|
||||
|
||||
Parse a regular expression pattern.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"abc"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
|
||||
- **Return:**
|
||||
- The AST of the regular expression pattern.
|
||||
|
||||
#### parser.parseFlags(source, start?, end?)
|
||||
|
||||
Parse a regular expression flags.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"gim"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- **Return:**
|
||||
- The AST of the regular expression flags.
|
||||
|
||||
### RegExpValidator
|
||||
|
||||
#### new RegExpValidator(options)
|
||||
|
||||
- **Parameters:**
|
||||
- `options` ([`RegExpValidator.Options`]) The options to validate.
|
||||
|
||||
#### validator.validateLiteral(source, start, end)
|
||||
|
||||
Validate a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
|
||||
#### validator.validatePattern(source, start, end, flags)
|
||||
|
||||
Validate a regular expression pattern.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
|
||||
|
||||
#### validator.validateFlags(source, start, end)
|
||||
|
||||
Validate a regular expression flags.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
|
||||
### RegExpVisitor
|
||||
|
||||
#### new RegExpVisitor(handlers)
|
||||
|
||||
- **Parameters:**
|
||||
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
|
||||
|
||||
#### visitor.visit(ast)
|
||||
|
||||
Validate a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `ast` ([`AST.Node`]) The AST to visit.
|
||||
|
||||
## 📰 Changelog
|
||||
|
||||
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
|
||||
|
||||
## 🍻 Contributing
|
||||
|
||||
Welcome contributing!
|
||||
|
||||
Please use GitHub's Issues/PRs.
|
||||
|
||||
### Development Tools
|
||||
|
||||
- `npm test` runs tests and measures coverage.
|
||||
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
|
||||
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
|
||||
- `npm run lint` runs ESLint.
|
||||
- `npm run update:test` updates test fixtures.
|
||||
- `npm run update:ids` updates `src/unicode/ids.ts`.
|
||||
- `npm run watch` runs tests with `--watch` option.
|
||||
|
||||
[`AST.Node`]: src/ast.ts#L4
|
||||
[`RegExpParser.Options`]: src/parser.ts#L743
|
||||
[`RegExpValidator.Options`]: src/validator.ts#L220
|
||||
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291
|
||||
+1163
@@ -0,0 +1,1163 @@
|
||||
// Generated by dts-bundle v0.7.3
|
||||
|
||||
declare module "@eslint-community/regexpp" {
|
||||
import * as AST from "@eslint-community/regexpp/ast";
|
||||
import { RegExpParser } from "@eslint-community/regexpp/parser";
|
||||
import { RegExpValidator } from "@eslint-community/regexpp/validator";
|
||||
import { RegExpVisitor } from "@eslint-community/regexpp/visitor";
|
||||
export { RegExpSyntaxError } from "@eslint-community/regexpp/regexp-syntax-error";
|
||||
export { AST, RegExpParser, RegExpValidator };
|
||||
/**
|
||||
* Parse a given regular expression literal then make AST object.
|
||||
* @param source The source code to parse.
|
||||
* @param options The options to parse.
|
||||
* @returns The AST of the regular expression.
|
||||
*/
|
||||
export function parseRegExpLiteral(
|
||||
source: RegExp | string,
|
||||
options?: RegExpParser.Options
|
||||
): AST.RegExpLiteral;
|
||||
/**
|
||||
* Validate a given regular expression literal.
|
||||
* @param source The source code to validate.
|
||||
* @param options The options to validate.
|
||||
*/
|
||||
export function validateRegExpLiteral(
|
||||
source: string,
|
||||
options?: RegExpValidator.Options
|
||||
): void;
|
||||
export function visitRegExpAST(
|
||||
node: AST.Node,
|
||||
handlers: RegExpVisitor.Handlers
|
||||
): void;
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/ast" {
|
||||
/**
|
||||
* The type which includes all nodes.
|
||||
*/
|
||||
export type Node = BranchNode | LeafNode;
|
||||
/**
|
||||
* The type which includes all branch nodes.
|
||||
*/
|
||||
export type BranchNode =
|
||||
| Alternative
|
||||
| CapturingGroup
|
||||
| CharacterClass
|
||||
| CharacterClassRange
|
||||
| ClassIntersection
|
||||
| ClassStringDisjunction
|
||||
| ClassSubtraction
|
||||
| ExpressionCharacterClass
|
||||
| Group
|
||||
| LookaroundAssertion
|
||||
| Modifiers
|
||||
| Pattern
|
||||
| Quantifier
|
||||
| RegExpLiteral
|
||||
| StringAlternative;
|
||||
/**
|
||||
* The type which includes all leaf nodes.
|
||||
*/
|
||||
export type LeafNode =
|
||||
| Backreference
|
||||
| BoundaryAssertion
|
||||
| Character
|
||||
| CharacterSet
|
||||
| Flags
|
||||
| ModifierFlags;
|
||||
/**
|
||||
* The type which includes all atom nodes.
|
||||
*/
|
||||
export type Element = Assertion | QuantifiableElement | Quantifier;
|
||||
/**
|
||||
* The type which includes all atom nodes that Quantifier node can have as children.
|
||||
*/
|
||||
export type QuantifiableElement =
|
||||
| Backreference
|
||||
| CapturingGroup
|
||||
| Character
|
||||
| CharacterClass
|
||||
| CharacterSet
|
||||
| ExpressionCharacterClass
|
||||
| Group
|
||||
| LookaheadAssertion;
|
||||
/**
|
||||
* The type which includes all character class atom nodes.
|
||||
*/
|
||||
export type CharacterClassElement =
|
||||
| ClassRangesCharacterClassElement
|
||||
| UnicodeSetsCharacterClassElement;
|
||||
export type ClassRangesCharacterClassElement =
|
||||
| Character
|
||||
| CharacterClassRange
|
||||
| CharacterUnicodePropertyCharacterSet
|
||||
| EscapeCharacterSet;
|
||||
export type UnicodeSetsCharacterClassElement =
|
||||
| Character
|
||||
| CharacterClassRange
|
||||
| ClassStringDisjunction
|
||||
| EscapeCharacterSet
|
||||
| ExpressionCharacterClass
|
||||
| UnicodePropertyCharacterSet
|
||||
| UnicodeSetsCharacterClass;
|
||||
/**
|
||||
* The type which defines common properties for all node types.
|
||||
*/
|
||||
export interface NodeBase {
|
||||
/** The node type. */
|
||||
type: Node["type"];
|
||||
/** The parent node. */
|
||||
parent: Node["parent"];
|
||||
/** The 0-based index that this node starts. */
|
||||
start: number;
|
||||
/** The 0-based index that this node ends. */
|
||||
end: number;
|
||||
/** The raw text of this node. */
|
||||
raw: string;
|
||||
}
|
||||
/**
|
||||
* The root node.
|
||||
*/
|
||||
export interface RegExpLiteral extends NodeBase {
|
||||
type: "RegExpLiteral";
|
||||
parent: null;
|
||||
pattern: Pattern;
|
||||
flags: Flags;
|
||||
}
|
||||
/**
|
||||
* The pattern.
|
||||
*/
|
||||
export interface Pattern extends NodeBase {
|
||||
type: "Pattern";
|
||||
parent: RegExpLiteral | null;
|
||||
alternatives: Alternative[];
|
||||
}
|
||||
/**
|
||||
* The alternative.
|
||||
* E.g. `a|b`
|
||||
*/
|
||||
export interface Alternative extends NodeBase {
|
||||
type: "Alternative";
|
||||
parent: CapturingGroup | Group | LookaroundAssertion | Pattern;
|
||||
elements: Element[];
|
||||
}
|
||||
/**
|
||||
* The uncapturing group.
|
||||
* E.g. `(?:ab)`
|
||||
*/
|
||||
export interface Group extends NodeBase {
|
||||
type: "Group";
|
||||
parent: Alternative | Quantifier;
|
||||
modifiers: Modifiers | null;
|
||||
alternatives: Alternative[];
|
||||
}
|
||||
/**
|
||||
* The capturing group.
|
||||
* E.g. `(ab)`, `(?<name>ab)`
|
||||
*/
|
||||
export interface CapturingGroup extends NodeBase {
|
||||
type: "CapturingGroup";
|
||||
parent: Alternative | Quantifier;
|
||||
name: string | null;
|
||||
alternatives: Alternative[];
|
||||
references: Backreference[];
|
||||
}
|
||||
/**
|
||||
* The lookaround assertion.
|
||||
*/
|
||||
export type LookaroundAssertion = LookaheadAssertion | LookbehindAssertion;
|
||||
/**
|
||||
* The lookahead assertion.
|
||||
* E.g. `(?=ab)`, `(?!ab)`
|
||||
*/
|
||||
export interface LookaheadAssertion extends NodeBase {
|
||||
type: "Assertion";
|
||||
parent: Alternative | Quantifier;
|
||||
kind: "lookahead";
|
||||
negate: boolean;
|
||||
alternatives: Alternative[];
|
||||
}
|
||||
/**
|
||||
* The lookbehind assertion.
|
||||
* E.g. `(?<=ab)`, `(?<!ab)`
|
||||
*/
|
||||
export interface LookbehindAssertion extends NodeBase {
|
||||
type: "Assertion";
|
||||
parent: Alternative;
|
||||
kind: "lookbehind";
|
||||
negate: boolean;
|
||||
alternatives: Alternative[];
|
||||
}
|
||||
/**
|
||||
* The quantifier.
|
||||
* E.g. `a?`, `a*`, `a+`, `a{1,2}`, `a??`, `a*?`, `a+?`, `a{1,2}?`
|
||||
*/
|
||||
export interface Quantifier extends NodeBase {
|
||||
type: "Quantifier";
|
||||
parent: Alternative;
|
||||
min: number;
|
||||
max: number;
|
||||
greedy: boolean;
|
||||
element: QuantifiableElement;
|
||||
}
|
||||
/**
|
||||
* The character class.
|
||||
* E.g. `[ab]`, `[^ab]`
|
||||
*/
|
||||
export type CharacterClass =
|
||||
| ClassRangesCharacterClass
|
||||
| UnicodeSetsCharacterClass;
|
||||
interface BaseCharacterClass extends NodeBase {
|
||||
type: "CharacterClass";
|
||||
parent:
|
||||
| Alternative
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier
|
||||
| UnicodeSetsCharacterClass;
|
||||
unicodeSets: boolean;
|
||||
negate: boolean;
|
||||
elements: CharacterClassElement[];
|
||||
}
|
||||
/**
|
||||
* The character class used in legacy (neither `u` nor `v` flag) and Unicode mode (`u` flag).
|
||||
*
|
||||
* This character class is guaranteed to **not** contain strings.
|
||||
*
|
||||
* In Unicode sets mode (`v` flag), {@link UnicodeSetsCharacterClass} is used.
|
||||
*/
|
||||
export interface ClassRangesCharacterClass extends BaseCharacterClass {
|
||||
parent: Alternative | Quantifier;
|
||||
unicodeSets: false;
|
||||
elements: ClassRangesCharacterClassElement[];
|
||||
}
|
||||
/**
|
||||
* The character class used in Unicode sets mode (`v` flag).
|
||||
*
|
||||
* This character class may contain strings.
|
||||
*/
|
||||
export interface UnicodeSetsCharacterClass extends BaseCharacterClass {
|
||||
parent:
|
||||
| Alternative
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier
|
||||
| UnicodeSetsCharacterClass;
|
||||
unicodeSets: true;
|
||||
elements: UnicodeSetsCharacterClassElement[];
|
||||
}
|
||||
/**
|
||||
* The character class.
|
||||
* E.g. `[a-b]`
|
||||
*/
|
||||
export interface CharacterClassRange extends NodeBase {
|
||||
type: "CharacterClassRange";
|
||||
parent: CharacterClass;
|
||||
min: Character;
|
||||
max: Character;
|
||||
}
|
||||
/**
|
||||
* The assertion.
|
||||
*/
|
||||
export type Assertion = BoundaryAssertion | LookaroundAssertion;
|
||||
/**
|
||||
* The boundary assertion.
|
||||
*/
|
||||
export type BoundaryAssertion = EdgeAssertion | WordBoundaryAssertion;
|
||||
/**
|
||||
* The edge boundary assertion.
|
||||
* E.g. `^`, `$`
|
||||
*/
|
||||
export interface EdgeAssertion extends NodeBase {
|
||||
type: "Assertion";
|
||||
parent: Alternative | Quantifier;
|
||||
kind: "end" | "start";
|
||||
}
|
||||
/**
|
||||
* The word bondary assertion.
|
||||
* E.g. `\b`, `\B`
|
||||
*/
|
||||
export interface WordBoundaryAssertion extends NodeBase {
|
||||
type: "Assertion";
|
||||
parent: Alternative | Quantifier;
|
||||
kind: "word";
|
||||
negate: boolean;
|
||||
}
|
||||
/**
|
||||
* The character set.
|
||||
*/
|
||||
export type CharacterSet =
|
||||
| AnyCharacterSet
|
||||
| EscapeCharacterSet
|
||||
| UnicodePropertyCharacterSet;
|
||||
/**
|
||||
* The dot.
|
||||
* E.g. `.`
|
||||
*/
|
||||
export interface AnyCharacterSet extends NodeBase {
|
||||
type: "CharacterSet";
|
||||
parent: Alternative | Quantifier;
|
||||
kind: "any";
|
||||
}
|
||||
/**
|
||||
* The character class escape.
|
||||
* E.g. `\d`, `\s`, `\w`, `\D`, `\S`, `\W`
|
||||
*/
|
||||
export interface EscapeCharacterSet extends NodeBase {
|
||||
type: "CharacterSet";
|
||||
parent:
|
||||
| Alternative
|
||||
| CharacterClass
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier;
|
||||
kind: "digit" | "space" | "word";
|
||||
negate: boolean;
|
||||
}
|
||||
/**
|
||||
* The unicode property escape.
|
||||
* E.g. `\p{ASCII}`, `\P{ASCII}`, `\p{Script=Hiragana}`
|
||||
*/
|
||||
export type UnicodePropertyCharacterSet =
|
||||
| CharacterUnicodePropertyCharacterSet
|
||||
| StringsUnicodePropertyCharacterSet;
|
||||
interface BaseUnicodePropertyCharacterSet extends NodeBase {
|
||||
type: "CharacterSet";
|
||||
parent:
|
||||
| Alternative
|
||||
| CharacterClass
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier;
|
||||
kind: "property";
|
||||
strings: boolean;
|
||||
key: string;
|
||||
value: string | null;
|
||||
negate: boolean;
|
||||
}
|
||||
export interface CharacterUnicodePropertyCharacterSet
|
||||
extends BaseUnicodePropertyCharacterSet {
|
||||
strings: false;
|
||||
value: string | null;
|
||||
negate: boolean;
|
||||
}
|
||||
/** StringsUnicodePropertyCharacterSet is Unicode property escape with property of strings. */
|
||||
export interface StringsUnicodePropertyCharacterSet
|
||||
extends BaseUnicodePropertyCharacterSet {
|
||||
parent:
|
||||
| Alternative
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier
|
||||
| UnicodeSetsCharacterClass;
|
||||
strings: true;
|
||||
value: null;
|
||||
negate: false;
|
||||
}
|
||||
/**
|
||||
* The expression character class.
|
||||
* E.g. `[a--b]`, `[a&&b]`,`[^a--b]`, `[^a&&b]`
|
||||
*/
|
||||
export interface ExpressionCharacterClass extends NodeBase {
|
||||
type: "ExpressionCharacterClass";
|
||||
parent:
|
||||
| Alternative
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier
|
||||
| UnicodeSetsCharacterClass;
|
||||
negate: boolean;
|
||||
expression: ClassIntersection | ClassSubtraction;
|
||||
}
|
||||
export type ClassSetOperand =
|
||||
| Character
|
||||
| ClassStringDisjunction
|
||||
| EscapeCharacterSet
|
||||
| ExpressionCharacterClass
|
||||
| UnicodePropertyCharacterSet
|
||||
| UnicodeSetsCharacterClass;
|
||||
/**
|
||||
* The character class intersection.
|
||||
* E.g. `a&&b`
|
||||
*/
|
||||
export interface ClassIntersection extends NodeBase {
|
||||
type: "ClassIntersection";
|
||||
parent: ClassIntersection | ExpressionCharacterClass;
|
||||
left: ClassIntersection | ClassSetOperand;
|
||||
right: ClassSetOperand;
|
||||
}
|
||||
/**
|
||||
* The character class subtraction.
|
||||
* E.g. `a--b`
|
||||
*/
|
||||
export interface ClassSubtraction extends NodeBase {
|
||||
type: "ClassSubtraction";
|
||||
parent: ClassSubtraction | ExpressionCharacterClass;
|
||||
left: ClassSetOperand | ClassSubtraction;
|
||||
right: ClassSetOperand;
|
||||
}
|
||||
/**
|
||||
* The character class string disjunction.
|
||||
* E.g. `\q{a|b}`
|
||||
*/
|
||||
export interface ClassStringDisjunction extends NodeBase {
|
||||
type: "ClassStringDisjunction";
|
||||
parent: ClassIntersection | ClassSubtraction | UnicodeSetsCharacterClass;
|
||||
alternatives: StringAlternative[];
|
||||
}
|
||||
/** StringAlternative is only used for `\q{alt}`({@link ClassStringDisjunction}). */
|
||||
export interface StringAlternative extends NodeBase {
|
||||
type: "StringAlternative";
|
||||
parent: ClassStringDisjunction;
|
||||
elements: Character[];
|
||||
}
|
||||
/**
|
||||
* The character.
|
||||
* This includes escape sequences which mean a character.
|
||||
* E.g. `a`, `あ`, `✿`, `\x65`, `\u0065`, `\u{65}`, `\/`
|
||||
*/
|
||||
export interface Character extends NodeBase {
|
||||
type: "Character";
|
||||
parent:
|
||||
| Alternative
|
||||
| CharacterClass
|
||||
| CharacterClassRange
|
||||
| ClassIntersection
|
||||
| ClassSubtraction
|
||||
| Quantifier
|
||||
| StringAlternative;
|
||||
value: number;
|
||||
}
|
||||
/**
|
||||
* The backreference.
|
||||
* E.g. `\1`, `\k<name>`
|
||||
*/
|
||||
export type Backreference = AmbiguousBackreference | UnambiguousBackreference;
|
||||
interface BaseBackreference extends NodeBase {
|
||||
type: "Backreference";
|
||||
parent: Alternative | Quantifier;
|
||||
ref: number | string;
|
||||
ambiguous: boolean;
|
||||
resolved: CapturingGroup | CapturingGroup[];
|
||||
}
|
||||
export interface AmbiguousBackreference extends BaseBackreference {
|
||||
ref: string;
|
||||
ambiguous: true;
|
||||
resolved: CapturingGroup[];
|
||||
}
|
||||
export interface UnambiguousBackreference extends BaseBackreference {
|
||||
ambiguous: false;
|
||||
resolved: CapturingGroup;
|
||||
}
|
||||
/**
|
||||
* The modifiers.
|
||||
*/
|
||||
export interface Modifiers extends NodeBase {
|
||||
type: "Modifiers";
|
||||
parent: Group;
|
||||
/**
|
||||
* The add modifier flags.
|
||||
*/
|
||||
add: ModifierFlags;
|
||||
/**
|
||||
* The remove modifier flags.
|
||||
*
|
||||
* `null` means no remove modifier flags. e.g. `(?ims:x)`
|
||||
* The reason for `null` is that there is no position where the remove modifier flags appears. Must be behind the minus mark.
|
||||
*/
|
||||
remove: ModifierFlags | null;
|
||||
}
|
||||
/**
|
||||
* The modifier flags.
|
||||
*/
|
||||
export interface ModifierFlags extends NodeBase {
|
||||
type: "ModifierFlags";
|
||||
parent: Modifiers;
|
||||
dotAll: boolean;
|
||||
ignoreCase: boolean;
|
||||
multiline: boolean;
|
||||
}
|
||||
/**
|
||||
* The flags.
|
||||
*/
|
||||
export interface Flags extends NodeBase {
|
||||
type: "Flags";
|
||||
parent: RegExpLiteral | null;
|
||||
dotAll: boolean;
|
||||
global: boolean;
|
||||
hasIndices: boolean;
|
||||
ignoreCase: boolean;
|
||||
multiline: boolean;
|
||||
sticky: boolean;
|
||||
unicode: boolean;
|
||||
unicodeSets: boolean;
|
||||
}
|
||||
export {};
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/parser" {
|
||||
import type {
|
||||
Flags,
|
||||
RegExpLiteral,
|
||||
Pattern,
|
||||
} from "@eslint-community/regexpp/ast";
|
||||
import type { EcmaVersion } from "@eslint-community/regexpp/ecma-versions";
|
||||
export namespace RegExpParser {
|
||||
/**
|
||||
* The options for RegExpParser construction.
|
||||
*/
|
||||
interface Options {
|
||||
/**
|
||||
* The flag to disable Annex B syntax. Default is `false`.
|
||||
*/
|
||||
strict?: boolean;
|
||||
/**
|
||||
* ECMAScript version. Default is `2025`.
|
||||
* - `2015` added `u` and `y` flags.
|
||||
* - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion,
|
||||
* and Unicode Property Escape.
|
||||
* - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes.
|
||||
* - `2022` added `d` flag.
|
||||
* - `2023` added more valid Unicode Property Escapes.
|
||||
* - `2024` added `v` flag.
|
||||
* - `2025` added duplicate named capturing groups, modifiers.
|
||||
*/
|
||||
ecmaVersion?: EcmaVersion;
|
||||
}
|
||||
}
|
||||
export class RegExpParser {
|
||||
/**
|
||||
* Initialize this parser.
|
||||
* @param options The options of parser.
|
||||
*/
|
||||
constructor(options?: RegExpParser.Options);
|
||||
/**
|
||||
* Parse a regular expression literal. E.g. "/abc/g"
|
||||
* @param source The source code to parse.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @returns The AST of the given regular expression.
|
||||
*/
|
||||
parseLiteral(source: string, start?: number, end?: number): RegExpLiteral;
|
||||
/**
|
||||
* Parse a regular expression flags. E.g. "gim"
|
||||
* @param source The source code to parse.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @returns The AST of the given flags.
|
||||
*/
|
||||
parseFlags(source: string, start?: number, end?: number): Flags;
|
||||
/**
|
||||
* Parse a regular expression pattern. E.g. "abc"
|
||||
* @param source The source code to parse.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @param flags The flags.
|
||||
* @returns The AST of the given pattern.
|
||||
*/
|
||||
parsePattern(
|
||||
source: string,
|
||||
start?: number,
|
||||
end?: number,
|
||||
flags?: {
|
||||
unicode?: boolean;
|
||||
unicodeSets?: boolean;
|
||||
}
|
||||
): Pattern;
|
||||
/**
|
||||
* @deprecated Backward compatibility
|
||||
* Use object `flags` instead of boolean `uFlag`.
|
||||
*
|
||||
* @param source The source code to parse.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @param uFlag The flag to set unicode mode.
|
||||
* @returns The AST of the given pattern.
|
||||
*/
|
||||
parsePattern(
|
||||
source: string,
|
||||
start?: number,
|
||||
end?: number,
|
||||
uFlag?: boolean
|
||||
): Pattern;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/validator" {
|
||||
import type { EcmaVersion } from "@eslint-community/regexpp/ecma-versions";
|
||||
export type RegExpValidatorSourceContext = {
|
||||
readonly source: string;
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
readonly kind: "flags" | "literal" | "pattern";
|
||||
};
|
||||
export namespace RegExpValidator {
|
||||
/**
|
||||
* The options for RegExpValidator construction.
|
||||
*/
|
||||
interface Options {
|
||||
/**
|
||||
* The flag to disable Annex B syntax. Default is `false`.
|
||||
*/
|
||||
strict?: boolean;
|
||||
/**
|
||||
* ECMAScript version. Default is `2025`.
|
||||
* - `2015` added `u` and `y` flags.
|
||||
* - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion,
|
||||
* and Unicode Property Escape.
|
||||
* - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes.
|
||||
* - `2022` added `d` flag.
|
||||
* - `2023` added more valid Unicode Property Escapes.
|
||||
* - `2024` added `v` flag.
|
||||
* - `2025` added duplicate named capturing groups, modifiers.
|
||||
*/
|
||||
ecmaVersion?: EcmaVersion;
|
||||
/**
|
||||
* A function that is called when the validator entered a RegExp literal.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onLiteralEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a RegExp literal.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onLiteralLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator found flags.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param flags.global `g` flag.
|
||||
* @param flags.ignoreCase `i` flag.
|
||||
* @param flags.multiline `m` flag.
|
||||
* @param flags.unicode `u` flag.
|
||||
* @param flags.sticky `y` flag.
|
||||
* @param flags.dotAll `s` flag.
|
||||
* @param flags.hasIndices `d` flag.
|
||||
* @param flags.unicodeSets `v` flag.
|
||||
*/
|
||||
onRegExpFlags?: (
|
||||
start: number,
|
||||
end: number,
|
||||
flags: {
|
||||
global: boolean;
|
||||
ignoreCase: boolean;
|
||||
multiline: boolean;
|
||||
unicode: boolean;
|
||||
sticky: boolean;
|
||||
dotAll: boolean;
|
||||
hasIndices: boolean;
|
||||
unicodeSets: boolean;
|
||||
}
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found flags.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param global `g` flag.
|
||||
* @param ignoreCase `i` flag.
|
||||
* @param multiline `m` flag.
|
||||
* @param unicode `u` flag.
|
||||
* @param sticky `y` flag.
|
||||
* @param dotAll `s` flag.
|
||||
* @param hasIndices `d` flag.
|
||||
*
|
||||
* @deprecated Use `onRegExpFlags` instead.
|
||||
*/
|
||||
onFlags?: (
|
||||
start: number,
|
||||
end: number,
|
||||
global: boolean,
|
||||
ignoreCase: boolean,
|
||||
multiline: boolean,
|
||||
unicode: boolean,
|
||||
sticky: boolean,
|
||||
dotAll: boolean,
|
||||
hasIndices: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a pattern.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onPatternEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a pattern.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onPatternLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a disjunction.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onDisjunctionEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a disjunction.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onDisjunctionLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered an alternative.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param index The 0-based index of alternatives in a disjunction.
|
||||
*/
|
||||
onAlternativeEnter?: (start: number, index: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left an alternative.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param index The 0-based index of alternatives in a disjunction.
|
||||
*/
|
||||
onAlternativeLeave?: (start: number, end: number, index: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered an uncapturing group.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onGroupEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left an uncapturing group.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onGroupLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a modifiers.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onModifiersEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a modifiers.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onModifiersLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator found an add modifiers.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param flags flags.
|
||||
* @param flags.ignoreCase `i` flag.
|
||||
* @param flags.multiline `m` flag.
|
||||
* @param flags.dotAll `s` flag.
|
||||
*/
|
||||
onAddModifiers?: (
|
||||
start: number,
|
||||
end: number,
|
||||
flags: {
|
||||
ignoreCase: boolean;
|
||||
multiline: boolean;
|
||||
dotAll: boolean;
|
||||
}
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a remove modifiers.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param flags flags.
|
||||
* @param flags.ignoreCase `i` flag.
|
||||
* @param flags.multiline `m` flag.
|
||||
* @param flags.dotAll `s` flag.
|
||||
*/
|
||||
onRemoveModifiers?: (
|
||||
start: number,
|
||||
end: number,
|
||||
flags: {
|
||||
ignoreCase: boolean;
|
||||
multiline: boolean;
|
||||
dotAll: boolean;
|
||||
}
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a capturing group.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param name The group name.
|
||||
*/
|
||||
onCapturingGroupEnter?: (start: number, name: string | null) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a capturing group.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param name The group name.
|
||||
*/
|
||||
onCapturingGroupLeave?: (
|
||||
start: number,
|
||||
end: number,
|
||||
name: string | null
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a quantifier.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param min The minimum number of repeating.
|
||||
* @param max The maximum number of repeating.
|
||||
* @param greedy The flag to choose the longest matching.
|
||||
*/
|
||||
onQuantifier?: (
|
||||
start: number,
|
||||
end: number,
|
||||
min: number,
|
||||
max: number,
|
||||
greedy: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a lookahead/lookbehind assertion.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param kind The kind of the assertion.
|
||||
* @param negate The flag which represents that the assertion is negative.
|
||||
*/
|
||||
onLookaroundAssertionEnter?: (
|
||||
start: number,
|
||||
kind: "lookahead" | "lookbehind",
|
||||
negate: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a lookahead/lookbehind assertion.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the assertion.
|
||||
* @param negate The flag which represents that the assertion is negative.
|
||||
*/
|
||||
onLookaroundAssertionLeave?: (
|
||||
start: number,
|
||||
end: number,
|
||||
kind: "lookahead" | "lookbehind",
|
||||
negate: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found an edge boundary assertion.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the assertion.
|
||||
*/
|
||||
onEdgeAssertion?: (
|
||||
start: number,
|
||||
end: number,
|
||||
kind: "end" | "start"
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a word boundary assertion.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the assertion.
|
||||
* @param negate The flag which represents that the assertion is negative.
|
||||
*/
|
||||
onWordBoundaryAssertion?: (
|
||||
start: number,
|
||||
end: number,
|
||||
kind: "word",
|
||||
negate: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a dot.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the character set.
|
||||
*/
|
||||
onAnyCharacterSet?: (start: number, end: number, kind: "any") => void;
|
||||
/**
|
||||
* A function that is called when the validator found a character set escape.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the character set.
|
||||
* @param negate The flag which represents that the character set is negative.
|
||||
*/
|
||||
onEscapeCharacterSet?: (
|
||||
start: number,
|
||||
end: number,
|
||||
kind: "digit" | "space" | "word",
|
||||
negate: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a Unicode proerty escape.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param kind The kind of the character set.
|
||||
* @param key The property name.
|
||||
* @param value The property value.
|
||||
* @param negate The flag which represents that the character set is negative.
|
||||
* @param strings If true, the given property is property of strings.
|
||||
*/
|
||||
onUnicodePropertyCharacterSet?: (
|
||||
start: number,
|
||||
end: number,
|
||||
kind: "property",
|
||||
key: string,
|
||||
value: string | null,
|
||||
negate: boolean,
|
||||
strings: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a character.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param value The code point of the character.
|
||||
*/
|
||||
onCharacter?: (start: number, end: number, value: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a backreference.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param ref The key of the referred capturing group.
|
||||
*/
|
||||
onBackreference?: (
|
||||
start: number,
|
||||
end: number,
|
||||
ref: number | string
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a character class.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param negate The flag which represents that the character class is negative.
|
||||
* @param unicodeSets `true` if unicodeSets mode.
|
||||
*/
|
||||
onCharacterClassEnter?: (
|
||||
start: number,
|
||||
negate: boolean,
|
||||
unicodeSets: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a character class.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param negate The flag which represents that the character class is negative.
|
||||
*/
|
||||
onCharacterClassLeave?: (
|
||||
start: number,
|
||||
end: number,
|
||||
negate: boolean
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a character class range.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param min The minimum code point of the range.
|
||||
* @param max The maximum code point of the range.
|
||||
*/
|
||||
onCharacterClassRange?: (
|
||||
start: number,
|
||||
end: number,
|
||||
min: number,
|
||||
max: number
|
||||
) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a class intersection.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onClassIntersection?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator found a class subtraction.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onClassSubtraction?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a class string disjunction.
|
||||
* @param start The 0-based index of the first character.
|
||||
*/
|
||||
onClassStringDisjunctionEnter?: (start: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a class string disjunction.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
*/
|
||||
onClassStringDisjunctionLeave?: (start: number, end: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator entered a string alternative.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param index The 0-based index of alternatives in a disjunction.
|
||||
*/
|
||||
onStringAlternativeEnter?: (start: number, index: number) => void;
|
||||
/**
|
||||
* A function that is called when the validator left a string alternative.
|
||||
* @param start The 0-based index of the first character.
|
||||
* @param end The next 0-based index of the last character.
|
||||
* @param index The 0-based index of alternatives in a disjunction.
|
||||
*/
|
||||
onStringAlternativeLeave?: (
|
||||
start: number,
|
||||
end: number,
|
||||
index: number
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The regular expression validator.
|
||||
*/
|
||||
export class RegExpValidator {
|
||||
/**
|
||||
* Initialize this validator.
|
||||
* @param options The options of validator.
|
||||
*/
|
||||
constructor(options?: RegExpValidator.Options);
|
||||
/**
|
||||
* Validate a regular expression literal. E.g. "/abc/g"
|
||||
* @param source The source code to validate.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
*/
|
||||
validateLiteral(source: string, start?: number, end?: number): void;
|
||||
/**
|
||||
* Validate a regular expression flags. E.g. "gim"
|
||||
* @param source The source code to validate.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
*/
|
||||
validateFlags(source: string, start?: number, end?: number): void;
|
||||
/**
|
||||
* Validate a regular expression pattern. E.g. "abc"
|
||||
* @param source The source code to validate.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @param flags The flags.
|
||||
*/
|
||||
validatePattern(
|
||||
source: string,
|
||||
start?: number,
|
||||
end?: number,
|
||||
flags?: {
|
||||
unicode?: boolean;
|
||||
unicodeSets?: boolean;
|
||||
}
|
||||
): void;
|
||||
/**
|
||||
* @deprecated Backward compatibility
|
||||
* Use object `flags` instead of boolean `uFlag`.
|
||||
* @param source The source code to validate.
|
||||
* @param start The start index in the source code.
|
||||
* @param end The end index in the source code.
|
||||
* @param uFlag The flag to set unicode mode.
|
||||
*/
|
||||
validatePattern(
|
||||
source: string,
|
||||
start?: number,
|
||||
end?: number,
|
||||
uFlag?: boolean
|
||||
): void;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/visitor" {
|
||||
import type {
|
||||
Alternative,
|
||||
Assertion,
|
||||
Backreference,
|
||||
CapturingGroup,
|
||||
Character,
|
||||
CharacterClass,
|
||||
CharacterClassRange,
|
||||
CharacterSet,
|
||||
ClassIntersection,
|
||||
ClassStringDisjunction,
|
||||
ClassSubtraction,
|
||||
ExpressionCharacterClass,
|
||||
Flags,
|
||||
Group,
|
||||
ModifierFlags,
|
||||
Modifiers,
|
||||
Node,
|
||||
Pattern,
|
||||
Quantifier,
|
||||
RegExpLiteral,
|
||||
StringAlternative,
|
||||
} from "@eslint-community/regexpp/ast";
|
||||
/**
|
||||
* The visitor to walk on AST.
|
||||
*/
|
||||
export class RegExpVisitor {
|
||||
/**
|
||||
* Initialize this visitor.
|
||||
* @param handlers Callbacks for each node.
|
||||
*/
|
||||
constructor(handlers: RegExpVisitor.Handlers);
|
||||
/**
|
||||
* Visit a given node and descendant nodes.
|
||||
* @param node The root node to visit tree.
|
||||
*/
|
||||
visit(node: Node): void;
|
||||
}
|
||||
export namespace RegExpVisitor {
|
||||
interface Handlers {
|
||||
onAlternativeEnter?: (node: Alternative) => void;
|
||||
onAlternativeLeave?: (node: Alternative) => void;
|
||||
onAssertionEnter?: (node: Assertion) => void;
|
||||
onAssertionLeave?: (node: Assertion) => void;
|
||||
onBackreferenceEnter?: (node: Backreference) => void;
|
||||
onBackreferenceLeave?: (node: Backreference) => void;
|
||||
onCapturingGroupEnter?: (node: CapturingGroup) => void;
|
||||
onCapturingGroupLeave?: (node: CapturingGroup) => void;
|
||||
onCharacterEnter?: (node: Character) => void;
|
||||
onCharacterLeave?: (node: Character) => void;
|
||||
onCharacterClassEnter?: (node: CharacterClass) => void;
|
||||
onCharacterClassLeave?: (node: CharacterClass) => void;
|
||||
onCharacterClassRangeEnter?: (node: CharacterClassRange) => void;
|
||||
onCharacterClassRangeLeave?: (node: CharacterClassRange) => void;
|
||||
onCharacterSetEnter?: (node: CharacterSet) => void;
|
||||
onCharacterSetLeave?: (node: CharacterSet) => void;
|
||||
onClassIntersectionEnter?: (node: ClassIntersection) => void;
|
||||
onClassIntersectionLeave?: (node: ClassIntersection) => void;
|
||||
onClassStringDisjunctionEnter?: (node: ClassStringDisjunction) => void;
|
||||
onClassStringDisjunctionLeave?: (node: ClassStringDisjunction) => void;
|
||||
onClassSubtractionEnter?: (node: ClassSubtraction) => void;
|
||||
onClassSubtractionLeave?: (node: ClassSubtraction) => void;
|
||||
onExpressionCharacterClassEnter?: (
|
||||
node: ExpressionCharacterClass
|
||||
) => void;
|
||||
onExpressionCharacterClassLeave?: (
|
||||
node: ExpressionCharacterClass
|
||||
) => void;
|
||||
onFlagsEnter?: (node: Flags) => void;
|
||||
onFlagsLeave?: (node: Flags) => void;
|
||||
onGroupEnter?: (node: Group) => void;
|
||||
onGroupLeave?: (node: Group) => void;
|
||||
onModifierFlagsEnter?: (node: ModifierFlags) => void;
|
||||
onModifierFlagsLeave?: (node: ModifierFlags) => void;
|
||||
onModifiersEnter?: (node: Modifiers) => void;
|
||||
onModifiersLeave?: (node: Modifiers) => void;
|
||||
onPatternEnter?: (node: Pattern) => void;
|
||||
onPatternLeave?: (node: Pattern) => void;
|
||||
onQuantifierEnter?: (node: Quantifier) => void;
|
||||
onQuantifierLeave?: (node: Quantifier) => void;
|
||||
onRegExpLiteralEnter?: (node: RegExpLiteral) => void;
|
||||
onRegExpLiteralLeave?: (node: RegExpLiteral) => void;
|
||||
onStringAlternativeEnter?: (node: StringAlternative) => void;
|
||||
onStringAlternativeLeave?: (node: StringAlternative) => void;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/regexp-syntax-error" {
|
||||
import type { RegExpValidatorSourceContext } from "@eslint-community/regexpp/validator";
|
||||
export class RegExpSyntaxError extends SyntaxError {
|
||||
index: number;
|
||||
constructor(message: string, index: number);
|
||||
}
|
||||
export function newRegExpSyntaxError(
|
||||
srcCtx: RegExpValidatorSourceContext,
|
||||
flags: {
|
||||
unicode: boolean;
|
||||
unicodeSets: boolean;
|
||||
},
|
||||
index: number,
|
||||
message: string
|
||||
): RegExpSyntaxError;
|
||||
}
|
||||
|
||||
declare module "@eslint-community/regexpp/ecma-versions" {
|
||||
export type EcmaVersion =
|
||||
| 5
|
||||
| 2015
|
||||
| 2016
|
||||
| 2017
|
||||
| 2018
|
||||
| 2019
|
||||
| 2020
|
||||
| 2021
|
||||
| 2022
|
||||
| 2023
|
||||
| 2024
|
||||
| 2025;
|
||||
export const latestEcmaVersion = 2025;
|
||||
}
|
||||
+3042
@@ -0,0 +1,3042 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var ast = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null
|
||||
});
|
||||
|
||||
const latestEcmaVersion = 2025;
|
||||
|
||||
let largeIdStartRanges = undefined;
|
||||
let largeIdContinueRanges = undefined;
|
||||
function isIdStart(cp) {
|
||||
if (cp < 0x41)
|
||||
return false;
|
||||
if (cp < 0x5b)
|
||||
return true;
|
||||
if (cp < 0x61)
|
||||
return false;
|
||||
if (cp < 0x7b)
|
||||
return true;
|
||||
return isLargeIdStart(cp);
|
||||
}
|
||||
function isIdContinue(cp) {
|
||||
if (cp < 0x30)
|
||||
return false;
|
||||
if (cp < 0x3a)
|
||||
return true;
|
||||
if (cp < 0x41)
|
||||
return false;
|
||||
if (cp < 0x5b)
|
||||
return true;
|
||||
if (cp === 0x5f)
|
||||
return true;
|
||||
if (cp < 0x61)
|
||||
return false;
|
||||
if (cp < 0x7b)
|
||||
return true;
|
||||
return isLargeIdStart(cp) || isLargeIdContinue(cp);
|
||||
}
|
||||
function isLargeIdStart(cp) {
|
||||
return isInRange(cp, largeIdStartRanges !== null && largeIdStartRanges !== void 0 ? largeIdStartRanges : (largeIdStartRanges = initLargeIdStartRanges()));
|
||||
}
|
||||
function isLargeIdContinue(cp) {
|
||||
return isInRange(cp, largeIdContinueRanges !== null && largeIdContinueRanges !== void 0 ? largeIdContinueRanges : (largeIdContinueRanges = initLargeIdContinueRanges()));
|
||||
}
|
||||
function initLargeIdStartRanges() {
|
||||
return restoreRanges("4q 0 b 0 5 0 6 m 2 u 2 cp 5 b f 4 8 0 2 0 3m 4 2 1 3 3 2 0 7 0 2 2 2 0 2 j 2 2a 2 3u 9 4l 2 11 3 0 7 14 20 q 5 3 1a 16 10 1 2 2q 2 0 g 1 8 1 b 2 3 0 h 0 2 t u 2g c 0 p w a 1 5 0 6 l 5 0 a 0 4 0 o o 8 a 6 n 2 6 h 15 1n 1h 4 0 j 0 8 9 g f 5 7 3 1 3 l 2 6 2 0 4 3 4 0 h 0 e 1 2 2 f 1 b 0 9 5 5 1 3 l 2 6 2 1 2 1 2 1 w 3 2 0 k 2 h 8 2 2 2 l 2 6 2 1 2 4 4 0 j 0 g 1 o 0 c 7 3 1 3 l 2 6 2 1 2 4 4 0 v 1 2 2 g 0 i 0 2 5 4 2 2 3 4 1 2 0 2 1 4 1 4 2 4 b n 0 1h 7 2 2 2 m 2 f 4 0 r 2 2 1 3 1 v 0 5 7 2 2 2 m 2 9 2 4 4 0 v 2 2 1 g 1 i 8 2 2 2 14 3 0 h 0 6 2 9 2 p 5 6 h 4 n 2 8 2 0 3 6 1n 1b 2 1 d 6 1n 1 2 0 2 4 2 n 2 0 2 9 2 1 a 0 3 4 2 0 m 3 x 0 1s 7 2 z s 4 38 16 l 0 h 5 5 3 4 0 4 1 8 2 5 c d 0 i 11 2 0 6 0 3 16 2 98 2 3 3 6 2 0 2 3 3 14 2 3 3 w 2 3 3 6 2 0 2 3 3 e 2 1k 2 3 3 1u 12 f h 2d 3 5 4 h7 3 g 2 p 6 22 4 a 8 h e i f h f c 2 2 g 1f 10 0 5 0 1w 2g 8 14 2 0 6 1x b u 1e t 3 4 c 17 5 p 1j m a 1g 2b 0 2m 1a i 7 1j t e 1 b 17 r z 16 2 b z 3 a 6 16 3 2 16 3 2 5 2 1 4 0 6 5b 1t 7p 3 5 3 11 3 5 3 7 2 0 2 0 2 0 2 u 3 1g 2 6 2 0 4 2 2 6 4 3 3 5 5 c 6 2 2 6 39 0 e 0 h c 2u 0 5 0 3 9 2 0 3 5 7 0 2 0 2 0 2 f 3 3 6 4 5 0 i 14 22g 6c 7 3 4 1 d 11 2 0 6 0 3 1j 8 0 h m a 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 fb 2 q 8 8 4 3 4 5 2d 5 4 2 2h 2 3 6 16 2 2l i v 1d f e9 533 1t h3g 1w 19 3 7g 4 f b 1 l 1a h u 3 27 14 8 3 2u 3 29 l g 2 2 2 3 2 m u 1f f 1d 1r 5 4 0 2 1 c r b m q s 8 1a t 0 h 4 2 9 b 4 2 14 o 2 2 7 l m 4 0 4 1d 2 0 4 1 3 4 3 0 2 0 p 2 3 a 8 2 d 5 3 5 3 5 a 6 2 6 2 16 2 d 7 36 u 8mb d m 5 1c 6it a5 3 2x 13 6 d 4 6 0 2 9 2 c 2 4 2 0 2 1 2 1 2 2z y a2 j 1r 3 1h 15 b 39 4 2 3q 11 p 7 p c 2g 4 5 3 5 3 5 3 2 10 b 2 p 2 i 2 1 2 e 3 d z 3e 1y 1g 7g s 4 1c 1c v e t 6 11 b t 3 z 5 7 2 4 17 4d j z 5 z 5 13 9 1f d a 2 e 2 6 2 1 2 a 2 e 2 6 2 1 4 1f d 8m a l b 7 p 5 2 15 2 8 1y 5 3 0 2 17 2 1 4 0 3 m b m a u 1u i 2 1 b l b p 7 p 13 1j 7 1 1t 0 g 3 2 2 2 s 17 s 4 s 10 7 2 r s 1h b l b i e h 33 20 1k 1e e 1e e z 13 r a m 6z 15 7 1 h 5 1l s b 0 9 l 17 h 1b k s m d 1g 1m 1 3 0 e 18 x o r z u 0 3 0 9 y 4 0 d 1b f 3 m 0 2 0 10 h 2 o k 1 1s 6 2 0 2 3 2 e 2 9 8 1a 13 7 3 1 3 l 2 6 2 1 2 4 4 0 j 0 d 4 v 9 2 0 3 0 2 11 2 0 q 0 2 0 19 1g j 3 l 2 v 1b l 1 2 0 55 1a 16 3 11 1b l 0 1o 16 e 0 20 q 12 6 56 17 39 1r w 7 3 0 3 7 2 1 2 n g 0 2 0 2n 7 3 12 h 0 2 0 t 0 b 13 8 0 m 0 c 19 k 0 j 20 5k w w 8 2 10 i 0 1e t 35 6 2 1 2 11 m 0 q 5 2 1 2 v f 0 o 17 79 i g 0 2 c 2 x 3h 0 28 pl 2v 32 i 5f 219 2o g tr i 5 q 32y 6 g6 5a2 t 1cz fs 8 u i 26 i t j 1b h 3 w k 6 i c1 18 5w 1r x o 3 o 19 22 6 0 1v c 1t 1 2 0 f 4 a 5p1 16 v 2q 36 6pq 3 2 6 2 1 2 82 g 0 u 2 3 0 f 3 9 az 1s5 2y 6 c 4 8 8 9 4mf 2c 2 1y 2 1 3 0 3 1 3 3 2 b 2 0 2 6 2 1s 2 3 3 7 2 6 2 r 2 3 2 4 2 0 4 6 2 9f 3 o 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 7 1f9 u 7 5 7a 1p 43 18 b 6 h 0 8y t j 17 dh r 6d t 3 0 5s u 2 2 2 1 2 6 3 4 a 1 69 6 2 3 2 1 2 e 2 5g 1o 1v 8 0 xh 3 2 q 2 1 2 0 3 0 2 9 2 3 2 0 2 0 7 0 5 0 2 0 2 0 2 2 2 1 2 0 3 0 2 0 2 0 2 0 2 0 2 1 2 0 3 3 2 6 2 3 2 3 2 0 2 9 2 g 6 2 2 4 2 g 3et wyn x 3dp 3 4gd 3 5rk g h9 1wj f1 15v 3t6 6 6jt");
|
||||
}
|
||||
function initLargeIdContinueRanges() {
|
||||
return restoreRanges("53 0 g9 33 o 0 70 4 7e 18 2 0 2 1 2 1 2 0 21 a 1d u 7 0 2u 6 3 5 3 1 2 3 3 9 o 0 v q 2k a g 9 y 8 a 0 p 3 2 8 2 2 2 4 18 2 1o 8 17 n 2 w 1j 2 2 h 2 6 b 1 3 9 i 2 1l 0 2 6 3 1 3 2 a 0 b 1 3 9 f 0 3 2 1l 0 2 4 5 1 3 2 4 0 l b 4 0 c 2 1l 0 2 7 2 2 2 2 l 1 3 9 b 5 2 2 1l 0 2 6 3 1 3 2 8 2 b 1 3 9 j 0 1o 4 4 2 2 3 a 0 f 9 h 4 1k 0 2 6 2 2 2 3 8 1 c 1 3 9 i 2 1l 0 2 6 2 2 2 3 8 1 c 1 3 9 4 0 d 3 1k 1 2 6 2 2 2 3 a 0 b 1 3 9 i 2 1z 0 5 5 2 0 2 7 7 9 3 1 1q 0 3 6 d 7 2 9 2g 0 3 8 c 6 2 9 1r 1 7 9 c 0 2 0 2 0 5 1 1e j 2 1 6 a 2 z a 0 2t j 2 9 d 3 5 2 2 2 3 6 4 3 e b 2 e jk 2 a 8 pt 3 t 2 u 1 v 1 1t v a 0 3 9 y 2 2 a 40 0 3b b 5 b b 9 3l a 1p 4 1m 9 2 s 3 a 7 9 n d 2 u 3 b l 4 1c g c 9 i 8 d 2 v c 3 9 19 d 1d j 9 9 7 9 3b 2 2 k 5 0 7 0 3 2 5j 1r el 1 1e 1 k 0 3g c 5 0 4 b 2db 2 3y 0 2p v ff 5 2y 1 2p 0 n51 9 1y 0 5 9 x 1 29 1 7l 0 4 0 5 0 o 4 5 0 2c 1 1f h b 9 7 h e a t 7 q c 19 3 1c d g 9 c 0 b 9 1c d d 0 9 1 3 9 y 2 1f 0 2 2 3 1 6 1 2 0 16 4 6 1 6l 7 2 1 3 9 fmt 0 ki f h f 4 1 p 2 5d 9 12 0 12 0 ig 0 6b 0 46 4 86 9 120 2 2 1 6 3 15 2 5 0 4m 1 fy 3 9 9 7 9 w 4 8u 1 26 5 1z a 1e 3 3f 2 1i e w a 3 1 b 3 1a a 8 0 1a 9 7 2 11 d 2 9 6 1 19 0 d 2 1d d 9 3 2 b 2b b 7 0 3 0 4e b 6 9 7 3 1k 1 2 6 3 1 3 2 a 0 b 1 3 6 4 4 1w 8 2 0 3 0 2 3 2 4 2 0 f 1 2b h a 9 5 0 2a j d 9 5y 6 3 8 s 1 2b g g 9 2a c 9 9 7 j 1m e 5 9 6r e 4m 9 1z 5 2 1 3 3 2 0 2 1 d 9 3c 6 3 6 4 0 t 9 15 6 2 3 9 0 a a 1b f 5j 7 3t 9 1i 7 2 7 h 9 1l l 2 d 3f 5 4 0 2 1 2 6 2 0 9 9 1d 4 2 1 2 4 9 9 1j 9 7e 3 a 1 2 0 1d 6 4 4 e a 44m 0 7 e 8uh r 1t3 9 2f 9 13 4 1o 6 q 9 ev 9 d2 0 2 1i 8 3 2a 0 c 1 f58 1 382 9 ef 19 3 m f3 4 4 5 9 7 3 6 v 3 45 2 13e 1d e9 1i 5 1d 9 0 f 0 n 4 2 e 11t 6 2 g 3 6 2 1 2 4 2t 0 4h 6 a 9 9x 0 1q d dv d 6t 1 2 9 6h 0 3 0 8 1 6 0 d7 6 32 6 6 9 3o7 9 gvt3 6n");
|
||||
}
|
||||
function isInRange(cp, ranges) {
|
||||
let l = 0, r = (ranges.length / 2) | 0, i = 0, min = 0, max = 0;
|
||||
while (l < r) {
|
||||
i = ((l + r) / 2) | 0;
|
||||
min = ranges[2 * i];
|
||||
max = ranges[2 * i + 1];
|
||||
if (cp < min) {
|
||||
r = i;
|
||||
}
|
||||
else if (cp > max) {
|
||||
l = i + 1;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function restoreRanges(data) {
|
||||
let last = 0;
|
||||
return data.split(" ").map((s) => (last += parseInt(s, 36) | 0));
|
||||
}
|
||||
|
||||
class DataSet {
|
||||
constructor(raw2018, raw2019, raw2020, raw2021, raw2022, raw2023, raw2024, raw2025, raw2026) {
|
||||
this._raw2018 = raw2018;
|
||||
this._raw2019 = raw2019;
|
||||
this._raw2020 = raw2020;
|
||||
this._raw2021 = raw2021;
|
||||
this._raw2022 = raw2022;
|
||||
this._raw2023 = raw2023;
|
||||
this._raw2024 = raw2024;
|
||||
this._raw2025 = raw2025;
|
||||
this._raw2026 = raw2026;
|
||||
}
|
||||
get es2018() {
|
||||
var _a;
|
||||
return ((_a = this._set2018) !== null && _a !== void 0 ? _a : (this._set2018 = new Set(this._raw2018.split(" "))));
|
||||
}
|
||||
get es2019() {
|
||||
var _a;
|
||||
return ((_a = this._set2019) !== null && _a !== void 0 ? _a : (this._set2019 = new Set(this._raw2019.split(" "))));
|
||||
}
|
||||
get es2020() {
|
||||
var _a;
|
||||
return ((_a = this._set2020) !== null && _a !== void 0 ? _a : (this._set2020 = new Set(this._raw2020.split(" "))));
|
||||
}
|
||||
get es2021() {
|
||||
var _a;
|
||||
return ((_a = this._set2021) !== null && _a !== void 0 ? _a : (this._set2021 = new Set(this._raw2021.split(" "))));
|
||||
}
|
||||
get es2022() {
|
||||
var _a;
|
||||
return ((_a = this._set2022) !== null && _a !== void 0 ? _a : (this._set2022 = new Set(this._raw2022.split(" "))));
|
||||
}
|
||||
get es2023() {
|
||||
var _a;
|
||||
return ((_a = this._set2023) !== null && _a !== void 0 ? _a : (this._set2023 = new Set(this._raw2023.split(" "))));
|
||||
}
|
||||
get es2024() {
|
||||
var _a;
|
||||
return ((_a = this._set2024) !== null && _a !== void 0 ? _a : (this._set2024 = new Set(this._raw2024.split(" "))));
|
||||
}
|
||||
get es2025() {
|
||||
var _a;
|
||||
return ((_a = this._set2025) !== null && _a !== void 0 ? _a : (this._set2025 = new Set(this._raw2025.split(" "))));
|
||||
}
|
||||
get es2026() {
|
||||
var _a;
|
||||
return ((_a = this._set2026) !== null && _a !== void 0 ? _a : (this._set2026 = new Set(this._raw2026.split(" "))));
|
||||
}
|
||||
}
|
||||
const gcNameSet = new Set(["General_Category", "gc"]);
|
||||
const scNameSet = new Set(["Script", "Script_Extensions", "sc", "scx"]);
|
||||
const gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "", "", "", "", "", "");
|
||||
const scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi", "Cpmn Cypro_Minoan Old_Uyghur Ougr Tangsa Tnsa Toto Vith Vithkuqi", "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz", "", "", "");
|
||||
const binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict", "", "", "", "", "");
|
||||
const binPropertyOfStringsSets = new DataSet("", "", "", "", "", "", "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji RGI_Emoji_Flag_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence", "", "");
|
||||
function isValidUnicodeProperty(version, name, value) {
|
||||
if (gcNameSet.has(name)) {
|
||||
return version >= 2018 && gcValueSets.es2018.has(value);
|
||||
}
|
||||
if (scNameSet.has(name)) {
|
||||
return ((version >= 2018 && scValueSets.es2018.has(value)) ||
|
||||
(version >= 2019 && scValueSets.es2019.has(value)) ||
|
||||
(version >= 2020 && scValueSets.es2020.has(value)) ||
|
||||
(version >= 2021 && scValueSets.es2021.has(value)) ||
|
||||
(version >= 2022 && scValueSets.es2022.has(value)) ||
|
||||
(version >= 2023 && scValueSets.es2023.has(value)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isValidLoneUnicodeProperty(version, value) {
|
||||
return ((version >= 2018 && binPropertySets.es2018.has(value)) ||
|
||||
(version >= 2019 && binPropertySets.es2019.has(value)) ||
|
||||
(version >= 2021 && binPropertySets.es2021.has(value)));
|
||||
}
|
||||
function isValidLoneUnicodePropertyOfString(version, value) {
|
||||
return version >= 2024 && binPropertyOfStringsSets.es2024.has(value);
|
||||
}
|
||||
|
||||
const BACKSPACE = 0x08;
|
||||
const CHARACTER_TABULATION = 0x09;
|
||||
const LINE_FEED = 0x0a;
|
||||
const LINE_TABULATION = 0x0b;
|
||||
const FORM_FEED = 0x0c;
|
||||
const CARRIAGE_RETURN = 0x0d;
|
||||
const EXCLAMATION_MARK = 0x21;
|
||||
const NUMBER_SIGN = 0x23;
|
||||
const DOLLAR_SIGN = 0x24;
|
||||
const PERCENT_SIGN = 0x25;
|
||||
const AMPERSAND = 0x26;
|
||||
const LEFT_PARENTHESIS = 0x28;
|
||||
const RIGHT_PARENTHESIS = 0x29;
|
||||
const ASTERISK = 0x2a;
|
||||
const PLUS_SIGN = 0x2b;
|
||||
const COMMA = 0x2c;
|
||||
const HYPHEN_MINUS = 0x2d;
|
||||
const FULL_STOP = 0x2e;
|
||||
const SOLIDUS = 0x2f;
|
||||
const DIGIT_ZERO = 0x30;
|
||||
const DIGIT_ONE = 0x31;
|
||||
const DIGIT_SEVEN = 0x37;
|
||||
const DIGIT_NINE = 0x39;
|
||||
const COLON = 0x3a;
|
||||
const SEMICOLON = 0x3b;
|
||||
const LESS_THAN_SIGN = 0x3c;
|
||||
const EQUALS_SIGN = 0x3d;
|
||||
const GREATER_THAN_SIGN = 0x3e;
|
||||
const QUESTION_MARK = 0x3f;
|
||||
const COMMERCIAL_AT = 0x40;
|
||||
const LATIN_CAPITAL_LETTER_A = 0x41;
|
||||
const LATIN_CAPITAL_LETTER_B = 0x42;
|
||||
const LATIN_CAPITAL_LETTER_D = 0x44;
|
||||
const LATIN_CAPITAL_LETTER_F = 0x46;
|
||||
const LATIN_CAPITAL_LETTER_P = 0x50;
|
||||
const LATIN_CAPITAL_LETTER_S = 0x53;
|
||||
const LATIN_CAPITAL_LETTER_W = 0x57;
|
||||
const LATIN_CAPITAL_LETTER_Z = 0x5a;
|
||||
const LOW_LINE = 0x5f;
|
||||
const LATIN_SMALL_LETTER_A = 0x61;
|
||||
const LATIN_SMALL_LETTER_B = 0x62;
|
||||
const LATIN_SMALL_LETTER_C = 0x63;
|
||||
const LATIN_SMALL_LETTER_D = 0x64;
|
||||
const LATIN_SMALL_LETTER_F = 0x66;
|
||||
const LATIN_SMALL_LETTER_G = 0x67;
|
||||
const LATIN_SMALL_LETTER_I = 0x69;
|
||||
const LATIN_SMALL_LETTER_K = 0x6b;
|
||||
const LATIN_SMALL_LETTER_M = 0x6d;
|
||||
const LATIN_SMALL_LETTER_N = 0x6e;
|
||||
const LATIN_SMALL_LETTER_P = 0x70;
|
||||
const LATIN_SMALL_LETTER_Q = 0x71;
|
||||
const LATIN_SMALL_LETTER_R = 0x72;
|
||||
const LATIN_SMALL_LETTER_S = 0x73;
|
||||
const LATIN_SMALL_LETTER_T = 0x74;
|
||||
const LATIN_SMALL_LETTER_U = 0x75;
|
||||
const LATIN_SMALL_LETTER_V = 0x76;
|
||||
const LATIN_SMALL_LETTER_W = 0x77;
|
||||
const LATIN_SMALL_LETTER_X = 0x78;
|
||||
const LATIN_SMALL_LETTER_Y = 0x79;
|
||||
const LATIN_SMALL_LETTER_Z = 0x7a;
|
||||
const LEFT_SQUARE_BRACKET = 0x5b;
|
||||
const REVERSE_SOLIDUS = 0x5c;
|
||||
const RIGHT_SQUARE_BRACKET = 0x5d;
|
||||
const CIRCUMFLEX_ACCENT = 0x5e;
|
||||
const GRAVE_ACCENT = 0x60;
|
||||
const LEFT_CURLY_BRACKET = 0x7b;
|
||||
const VERTICAL_LINE = 0x7c;
|
||||
const RIGHT_CURLY_BRACKET = 0x7d;
|
||||
const TILDE = 0x7e;
|
||||
const ZERO_WIDTH_NON_JOINER = 0x200c;
|
||||
const ZERO_WIDTH_JOINER = 0x200d;
|
||||
const LINE_SEPARATOR = 0x2028;
|
||||
const PARAGRAPH_SEPARATOR = 0x2029;
|
||||
const MIN_CODE_POINT = 0x00;
|
||||
const MAX_CODE_POINT = 0x10ffff;
|
||||
function isLatinLetter(code) {
|
||||
return ((code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_Z) ||
|
||||
(code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_Z));
|
||||
}
|
||||
function isDecimalDigit(code) {
|
||||
return code >= DIGIT_ZERO && code <= DIGIT_NINE;
|
||||
}
|
||||
function isOctalDigit(code) {
|
||||
return code >= DIGIT_ZERO && code <= DIGIT_SEVEN;
|
||||
}
|
||||
function isHexDigit(code) {
|
||||
return ((code >= DIGIT_ZERO && code <= DIGIT_NINE) ||
|
||||
(code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) ||
|
||||
(code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F));
|
||||
}
|
||||
function isLineTerminator(code) {
|
||||
return (code === LINE_FEED ||
|
||||
code === CARRIAGE_RETURN ||
|
||||
code === LINE_SEPARATOR ||
|
||||
code === PARAGRAPH_SEPARATOR);
|
||||
}
|
||||
function isValidUnicode(code) {
|
||||
return code >= MIN_CODE_POINT && code <= MAX_CODE_POINT;
|
||||
}
|
||||
function digitToInt(code) {
|
||||
if (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F) {
|
||||
return code - LATIN_SMALL_LETTER_A + 10;
|
||||
}
|
||||
if (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) {
|
||||
return code - LATIN_CAPITAL_LETTER_A + 10;
|
||||
}
|
||||
return code - DIGIT_ZERO;
|
||||
}
|
||||
function isLeadSurrogate(code) {
|
||||
return code >= 0xd800 && code <= 0xdbff;
|
||||
}
|
||||
function isTrailSurrogate(code) {
|
||||
return code >= 0xdc00 && code <= 0xdfff;
|
||||
}
|
||||
function combineSurrogatePair(lead, trail) {
|
||||
return (lead - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000;
|
||||
}
|
||||
|
||||
class GroupSpecifiersAsES2018 {
|
||||
constructor() {
|
||||
this.groupName = new Set();
|
||||
}
|
||||
clear() {
|
||||
this.groupName.clear();
|
||||
}
|
||||
isEmpty() {
|
||||
return !this.groupName.size;
|
||||
}
|
||||
hasInPattern(name) {
|
||||
return this.groupName.has(name);
|
||||
}
|
||||
hasInScope(name) {
|
||||
return this.hasInPattern(name);
|
||||
}
|
||||
addToScope(name) {
|
||||
this.groupName.add(name);
|
||||
}
|
||||
enterDisjunction() {
|
||||
}
|
||||
enterAlternative() {
|
||||
}
|
||||
leaveDisjunction() {
|
||||
}
|
||||
}
|
||||
class BranchID {
|
||||
constructor(parent, base) {
|
||||
this.parent = parent;
|
||||
this.base = base !== null && base !== void 0 ? base : this;
|
||||
}
|
||||
separatedFrom(other) {
|
||||
var _a, _b;
|
||||
if (this.base === other.base && this !== other) {
|
||||
return true;
|
||||
}
|
||||
if (other.parent && this.separatedFrom(other.parent)) {
|
||||
return true;
|
||||
}
|
||||
return (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.separatedFrom(other)) !== null && _b !== void 0 ? _b : false;
|
||||
}
|
||||
child() {
|
||||
return new BranchID(this, null);
|
||||
}
|
||||
sibling() {
|
||||
return new BranchID(this.parent, this.base);
|
||||
}
|
||||
}
|
||||
class GroupSpecifiersAsES2025 {
|
||||
constructor() {
|
||||
this.branchID = new BranchID(null, null);
|
||||
this.groupNames = new Map();
|
||||
}
|
||||
clear() {
|
||||
this.branchID = new BranchID(null, null);
|
||||
this.groupNames.clear();
|
||||
}
|
||||
isEmpty() {
|
||||
return !this.groupNames.size;
|
||||
}
|
||||
enterDisjunction() {
|
||||
this.branchID = this.branchID.child();
|
||||
}
|
||||
enterAlternative(index) {
|
||||
if (index === 0) {
|
||||
return;
|
||||
}
|
||||
this.branchID = this.branchID.sibling();
|
||||
}
|
||||
leaveDisjunction() {
|
||||
this.branchID = this.branchID.parent;
|
||||
}
|
||||
hasInPattern(name) {
|
||||
return this.groupNames.has(name);
|
||||
}
|
||||
hasInScope(name) {
|
||||
const branches = this.groupNames.get(name);
|
||||
if (!branches) {
|
||||
return false;
|
||||
}
|
||||
for (const branch of branches) {
|
||||
if (!branch.separatedFrom(this.branchID)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
addToScope(name) {
|
||||
const branches = this.groupNames.get(name);
|
||||
if (branches) {
|
||||
branches.push(this.branchID);
|
||||
return;
|
||||
}
|
||||
this.groupNames.set(name, [this.branchID]);
|
||||
}
|
||||
}
|
||||
|
||||
const legacyImpl = {
|
||||
at(s, end, i) {
|
||||
return i < end ? s.charCodeAt(i) : -1;
|
||||
},
|
||||
width(c) {
|
||||
return 1;
|
||||
},
|
||||
};
|
||||
const unicodeImpl = {
|
||||
at(s, end, i) {
|
||||
return i < end ? s.codePointAt(i) : -1;
|
||||
},
|
||||
width(c) {
|
||||
return c > 0xffff ? 2 : 1;
|
||||
},
|
||||
};
|
||||
class Reader {
|
||||
constructor() {
|
||||
this._impl = legacyImpl;
|
||||
this._s = "";
|
||||
this._i = 0;
|
||||
this._end = 0;
|
||||
this._cp1 = -1;
|
||||
this._w1 = 1;
|
||||
this._cp2 = -1;
|
||||
this._w2 = 1;
|
||||
this._cp3 = -1;
|
||||
this._w3 = 1;
|
||||
this._cp4 = -1;
|
||||
}
|
||||
get source() {
|
||||
return this._s;
|
||||
}
|
||||
get index() {
|
||||
return this._i;
|
||||
}
|
||||
get currentCodePoint() {
|
||||
return this._cp1;
|
||||
}
|
||||
get nextCodePoint() {
|
||||
return this._cp2;
|
||||
}
|
||||
get nextCodePoint2() {
|
||||
return this._cp3;
|
||||
}
|
||||
get nextCodePoint3() {
|
||||
return this._cp4;
|
||||
}
|
||||
reset(source, start, end, uFlag) {
|
||||
this._impl = uFlag ? unicodeImpl : legacyImpl;
|
||||
this._s = source;
|
||||
this._end = end;
|
||||
this.rewind(start);
|
||||
}
|
||||
rewind(index) {
|
||||
const impl = this._impl;
|
||||
this._i = index;
|
||||
this._cp1 = impl.at(this._s, this._end, index);
|
||||
this._w1 = impl.width(this._cp1);
|
||||
this._cp2 = impl.at(this._s, this._end, index + this._w1);
|
||||
this._w2 = impl.width(this._cp2);
|
||||
this._cp3 = impl.at(this._s, this._end, index + this._w1 + this._w2);
|
||||
this._w3 = impl.width(this._cp3);
|
||||
this._cp4 = impl.at(this._s, this._end, index + this._w1 + this._w2 + this._w3);
|
||||
}
|
||||
advance() {
|
||||
if (this._cp1 !== -1) {
|
||||
const impl = this._impl;
|
||||
this._i += this._w1;
|
||||
this._cp1 = this._cp2;
|
||||
this._w1 = this._w2;
|
||||
this._cp2 = this._cp3;
|
||||
this._w2 = impl.width(this._cp2);
|
||||
this._cp3 = this._cp4;
|
||||
this._w3 = impl.width(this._cp3);
|
||||
this._cp4 = impl.at(this._s, this._end, this._i + this._w1 + this._w2 + this._w3);
|
||||
}
|
||||
}
|
||||
eat(cp) {
|
||||
if (this._cp1 === cp) {
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eat2(cp1, cp2) {
|
||||
if (this._cp1 === cp1 && this._cp2 === cp2) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eat3(cp1, cp2, cp3) {
|
||||
if (this._cp1 === cp1 && this._cp2 === cp2 && this._cp3 === cp3) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class RegExpSyntaxError extends SyntaxError {
|
||||
constructor(message, index) {
|
||||
super(message);
|
||||
this.index = index;
|
||||
}
|
||||
}
|
||||
function newRegExpSyntaxError(srcCtx, flags, index, message) {
|
||||
let source = "";
|
||||
if (srcCtx.kind === "literal") {
|
||||
const literal = srcCtx.source.slice(srcCtx.start, srcCtx.end);
|
||||
if (literal) {
|
||||
source = `: ${literal}`;
|
||||
}
|
||||
}
|
||||
else if (srcCtx.kind === "pattern") {
|
||||
const pattern = srcCtx.source.slice(srcCtx.start, srcCtx.end);
|
||||
const flagsText = `${flags.unicode ? "u" : ""}${flags.unicodeSets ? "v" : ""}`;
|
||||
source = `: /${pattern}/${flagsText}`;
|
||||
}
|
||||
return new RegExpSyntaxError(`Invalid regular expression${source}: ${message}`, index);
|
||||
}
|
||||
|
||||
const SYNTAX_CHARACTER = new Set([
|
||||
CIRCUMFLEX_ACCENT,
|
||||
DOLLAR_SIGN,
|
||||
REVERSE_SOLIDUS,
|
||||
FULL_STOP,
|
||||
ASTERISK,
|
||||
PLUS_SIGN,
|
||||
QUESTION_MARK,
|
||||
LEFT_PARENTHESIS,
|
||||
RIGHT_PARENTHESIS,
|
||||
LEFT_SQUARE_BRACKET,
|
||||
RIGHT_SQUARE_BRACKET,
|
||||
LEFT_CURLY_BRACKET,
|
||||
RIGHT_CURLY_BRACKET,
|
||||
VERTICAL_LINE,
|
||||
]);
|
||||
const CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER = new Set([
|
||||
AMPERSAND,
|
||||
EXCLAMATION_MARK,
|
||||
NUMBER_SIGN,
|
||||
DOLLAR_SIGN,
|
||||
PERCENT_SIGN,
|
||||
ASTERISK,
|
||||
PLUS_SIGN,
|
||||
COMMA,
|
||||
FULL_STOP,
|
||||
COLON,
|
||||
SEMICOLON,
|
||||
LESS_THAN_SIGN,
|
||||
EQUALS_SIGN,
|
||||
GREATER_THAN_SIGN,
|
||||
QUESTION_MARK,
|
||||
COMMERCIAL_AT,
|
||||
CIRCUMFLEX_ACCENT,
|
||||
GRAVE_ACCENT,
|
||||
TILDE,
|
||||
]);
|
||||
const CLASS_SET_SYNTAX_CHARACTER = new Set([
|
||||
LEFT_PARENTHESIS,
|
||||
RIGHT_PARENTHESIS,
|
||||
LEFT_SQUARE_BRACKET,
|
||||
RIGHT_SQUARE_BRACKET,
|
||||
LEFT_CURLY_BRACKET,
|
||||
RIGHT_CURLY_BRACKET,
|
||||
SOLIDUS,
|
||||
HYPHEN_MINUS,
|
||||
REVERSE_SOLIDUS,
|
||||
VERTICAL_LINE,
|
||||
]);
|
||||
const CLASS_SET_RESERVED_PUNCTUATOR = new Set([
|
||||
AMPERSAND,
|
||||
HYPHEN_MINUS,
|
||||
EXCLAMATION_MARK,
|
||||
NUMBER_SIGN,
|
||||
PERCENT_SIGN,
|
||||
COMMA,
|
||||
COLON,
|
||||
SEMICOLON,
|
||||
LESS_THAN_SIGN,
|
||||
EQUALS_SIGN,
|
||||
GREATER_THAN_SIGN,
|
||||
COMMERCIAL_AT,
|
||||
GRAVE_ACCENT,
|
||||
TILDE,
|
||||
]);
|
||||
const FLAG_PROP_TO_CODEPOINT = {
|
||||
global: LATIN_SMALL_LETTER_G,
|
||||
ignoreCase: LATIN_SMALL_LETTER_I,
|
||||
multiline: LATIN_SMALL_LETTER_M,
|
||||
unicode: LATIN_SMALL_LETTER_U,
|
||||
sticky: LATIN_SMALL_LETTER_Y,
|
||||
dotAll: LATIN_SMALL_LETTER_S,
|
||||
hasIndices: LATIN_SMALL_LETTER_D,
|
||||
unicodeSets: LATIN_SMALL_LETTER_V,
|
||||
};
|
||||
const FLAG_CODEPOINT_TO_PROP = Object.fromEntries(Object.entries(FLAG_PROP_TO_CODEPOINT).map(([k, v]) => [v, k]));
|
||||
function isSyntaxCharacter(cp) {
|
||||
return SYNTAX_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetReservedDoublePunctuatorCharacter(cp) {
|
||||
return CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetSyntaxCharacter(cp) {
|
||||
return CLASS_SET_SYNTAX_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetReservedPunctuator(cp) {
|
||||
return CLASS_SET_RESERVED_PUNCTUATOR.has(cp);
|
||||
}
|
||||
function isIdentifierStartChar(cp) {
|
||||
return isIdStart(cp) || cp === DOLLAR_SIGN || cp === LOW_LINE;
|
||||
}
|
||||
function isIdentifierPartChar(cp) {
|
||||
return (isIdContinue(cp) ||
|
||||
cp === DOLLAR_SIGN ||
|
||||
cp === ZERO_WIDTH_NON_JOINER ||
|
||||
cp === ZERO_WIDTH_JOINER);
|
||||
}
|
||||
function isUnicodePropertyNameCharacter(cp) {
|
||||
return isLatinLetter(cp) || cp === LOW_LINE;
|
||||
}
|
||||
function isUnicodePropertyValueCharacter(cp) {
|
||||
return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp);
|
||||
}
|
||||
function isRegularExpressionModifier(ch) {
|
||||
return (ch === LATIN_SMALL_LETTER_I ||
|
||||
ch === LATIN_SMALL_LETTER_M ||
|
||||
ch === LATIN_SMALL_LETTER_S);
|
||||
}
|
||||
class RegExpValidator {
|
||||
constructor(options) {
|
||||
this._reader = new Reader();
|
||||
this._unicodeMode = false;
|
||||
this._unicodeSetsMode = false;
|
||||
this._nFlag = false;
|
||||
this._lastIntValue = 0;
|
||||
this._lastRange = {
|
||||
min: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
this._lastStrValue = "";
|
||||
this._lastAssertionIsQuantifiable = false;
|
||||
this._numCapturingParens = 0;
|
||||
this._backreferenceNames = new Set();
|
||||
this._srcCtx = null;
|
||||
this._options = options !== null && options !== void 0 ? options : {};
|
||||
this._groupSpecifiers =
|
||||
this.ecmaVersion >= 2025
|
||||
? new GroupSpecifiersAsES2025()
|
||||
: new GroupSpecifiersAsES2018();
|
||||
}
|
||||
validateLiteral(source, start = 0, end = source.length) {
|
||||
this._srcCtx = { source, start, end, kind: "literal" };
|
||||
this._unicodeSetsMode = this._unicodeMode = this._nFlag = false;
|
||||
this.reset(source, start, end);
|
||||
this.onLiteralEnter(start);
|
||||
if (this.eat(SOLIDUS) && this.eatRegExpBody() && this.eat(SOLIDUS)) {
|
||||
const flagStart = this.index;
|
||||
const unicode = source.includes("u", flagStart);
|
||||
const unicodeSets = source.includes("v", flagStart);
|
||||
this.validateFlagsInternal(source, flagStart, end);
|
||||
this.validatePatternInternal(source, start + 1, flagStart - 1, {
|
||||
unicode,
|
||||
unicodeSets,
|
||||
});
|
||||
}
|
||||
else if (start >= end) {
|
||||
this.raise("Empty");
|
||||
}
|
||||
else {
|
||||
const c = String.fromCodePoint(this.currentCodePoint);
|
||||
this.raise(`Unexpected character '${c}'`);
|
||||
}
|
||||
this.onLiteralLeave(start, end);
|
||||
}
|
||||
validateFlags(source, start = 0, end = source.length) {
|
||||
this._srcCtx = { source, start, end, kind: "flags" };
|
||||
this.validateFlagsInternal(source, start, end);
|
||||
}
|
||||
validatePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
this._srcCtx = { source, start, end, kind: "pattern" };
|
||||
this.validatePatternInternal(source, start, end, uFlagOrFlags);
|
||||
}
|
||||
validatePatternInternal(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
const mode = this._parseFlagsOptionToMode(uFlagOrFlags, end);
|
||||
this._unicodeMode = mode.unicodeMode;
|
||||
this._nFlag = mode.nFlag;
|
||||
this._unicodeSetsMode = mode.unicodeSetsMode;
|
||||
this.reset(source, start, end);
|
||||
this.consumePattern();
|
||||
if (!this._nFlag &&
|
||||
this.ecmaVersion >= 2018 &&
|
||||
!this._groupSpecifiers.isEmpty()) {
|
||||
this._nFlag = true;
|
||||
this.rewind(start);
|
||||
this.consumePattern();
|
||||
}
|
||||
}
|
||||
validateFlagsInternal(source, start, end) {
|
||||
const flags = this.parseFlags(source, start, end);
|
||||
this.onRegExpFlags(start, end, flags);
|
||||
}
|
||||
_parseFlagsOptionToMode(uFlagOrFlags, sourceEnd) {
|
||||
let unicode = false;
|
||||
let unicodeSets = false;
|
||||
if (uFlagOrFlags && this.ecmaVersion >= 2015) {
|
||||
if (typeof uFlagOrFlags === "object") {
|
||||
unicode = Boolean(uFlagOrFlags.unicode);
|
||||
if (this.ecmaVersion >= 2024) {
|
||||
unicodeSets = Boolean(uFlagOrFlags.unicodeSets);
|
||||
}
|
||||
}
|
||||
else {
|
||||
unicode = uFlagOrFlags;
|
||||
}
|
||||
}
|
||||
if (unicode && unicodeSets) {
|
||||
this.raise("Invalid regular expression flags", {
|
||||
index: sourceEnd + 1,
|
||||
unicode,
|
||||
unicodeSets,
|
||||
});
|
||||
}
|
||||
const unicodeMode = unicode || unicodeSets;
|
||||
const nFlag = (unicode && this.ecmaVersion >= 2018) ||
|
||||
unicodeSets ||
|
||||
Boolean(this._options.strict && this.ecmaVersion >= 2023);
|
||||
const unicodeSetsMode = unicodeSets;
|
||||
return { unicodeMode, nFlag, unicodeSetsMode };
|
||||
}
|
||||
get strict() {
|
||||
return Boolean(this._options.strict) || this._unicodeMode;
|
||||
}
|
||||
get ecmaVersion() {
|
||||
var _a;
|
||||
return (_a = this._options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion;
|
||||
}
|
||||
onLiteralEnter(start) {
|
||||
if (this._options.onLiteralEnter) {
|
||||
this._options.onLiteralEnter(start);
|
||||
}
|
||||
}
|
||||
onLiteralLeave(start, end) {
|
||||
if (this._options.onLiteralLeave) {
|
||||
this._options.onLiteralLeave(start, end);
|
||||
}
|
||||
}
|
||||
onRegExpFlags(start, end, flags) {
|
||||
if (this._options.onRegExpFlags) {
|
||||
this._options.onRegExpFlags(start, end, flags);
|
||||
}
|
||||
if (this._options.onFlags) {
|
||||
this._options.onFlags(start, end, flags.global, flags.ignoreCase, flags.multiline, flags.unicode, flags.sticky, flags.dotAll, flags.hasIndices);
|
||||
}
|
||||
}
|
||||
onPatternEnter(start) {
|
||||
if (this._options.onPatternEnter) {
|
||||
this._options.onPatternEnter(start);
|
||||
}
|
||||
}
|
||||
onPatternLeave(start, end) {
|
||||
if (this._options.onPatternLeave) {
|
||||
this._options.onPatternLeave(start, end);
|
||||
}
|
||||
}
|
||||
onDisjunctionEnter(start) {
|
||||
if (this._options.onDisjunctionEnter) {
|
||||
this._options.onDisjunctionEnter(start);
|
||||
}
|
||||
}
|
||||
onDisjunctionLeave(start, end) {
|
||||
if (this._options.onDisjunctionLeave) {
|
||||
this._options.onDisjunctionLeave(start, end);
|
||||
}
|
||||
}
|
||||
onAlternativeEnter(start, index) {
|
||||
if (this._options.onAlternativeEnter) {
|
||||
this._options.onAlternativeEnter(start, index);
|
||||
}
|
||||
}
|
||||
onAlternativeLeave(start, end, index) {
|
||||
if (this._options.onAlternativeLeave) {
|
||||
this._options.onAlternativeLeave(start, end, index);
|
||||
}
|
||||
}
|
||||
onGroupEnter(start) {
|
||||
if (this._options.onGroupEnter) {
|
||||
this._options.onGroupEnter(start);
|
||||
}
|
||||
}
|
||||
onGroupLeave(start, end) {
|
||||
if (this._options.onGroupLeave) {
|
||||
this._options.onGroupLeave(start, end);
|
||||
}
|
||||
}
|
||||
onModifiersEnter(start) {
|
||||
if (this._options.onModifiersEnter) {
|
||||
this._options.onModifiersEnter(start);
|
||||
}
|
||||
}
|
||||
onModifiersLeave(start, end) {
|
||||
if (this._options.onModifiersLeave) {
|
||||
this._options.onModifiersLeave(start, end);
|
||||
}
|
||||
}
|
||||
onAddModifiers(start, end, flags) {
|
||||
if (this._options.onAddModifiers) {
|
||||
this._options.onAddModifiers(start, end, flags);
|
||||
}
|
||||
}
|
||||
onRemoveModifiers(start, end, flags) {
|
||||
if (this._options.onRemoveModifiers) {
|
||||
this._options.onRemoveModifiers(start, end, flags);
|
||||
}
|
||||
}
|
||||
onCapturingGroupEnter(start, name) {
|
||||
if (this._options.onCapturingGroupEnter) {
|
||||
this._options.onCapturingGroupEnter(start, name);
|
||||
}
|
||||
}
|
||||
onCapturingGroupLeave(start, end, name) {
|
||||
if (this._options.onCapturingGroupLeave) {
|
||||
this._options.onCapturingGroupLeave(start, end, name);
|
||||
}
|
||||
}
|
||||
onQuantifier(start, end, min, max, greedy) {
|
||||
if (this._options.onQuantifier) {
|
||||
this._options.onQuantifier(start, end, min, max, greedy);
|
||||
}
|
||||
}
|
||||
onLookaroundAssertionEnter(start, kind, negate) {
|
||||
if (this._options.onLookaroundAssertionEnter) {
|
||||
this._options.onLookaroundAssertionEnter(start, kind, negate);
|
||||
}
|
||||
}
|
||||
onLookaroundAssertionLeave(start, end, kind, negate) {
|
||||
if (this._options.onLookaroundAssertionLeave) {
|
||||
this._options.onLookaroundAssertionLeave(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onEdgeAssertion(start, end, kind) {
|
||||
if (this._options.onEdgeAssertion) {
|
||||
this._options.onEdgeAssertion(start, end, kind);
|
||||
}
|
||||
}
|
||||
onWordBoundaryAssertion(start, end, kind, negate) {
|
||||
if (this._options.onWordBoundaryAssertion) {
|
||||
this._options.onWordBoundaryAssertion(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onAnyCharacterSet(start, end, kind) {
|
||||
if (this._options.onAnyCharacterSet) {
|
||||
this._options.onAnyCharacterSet(start, end, kind);
|
||||
}
|
||||
}
|
||||
onEscapeCharacterSet(start, end, kind, negate) {
|
||||
if (this._options.onEscapeCharacterSet) {
|
||||
this._options.onEscapeCharacterSet(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) {
|
||||
if (this._options.onUnicodePropertyCharacterSet) {
|
||||
this._options.onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings);
|
||||
}
|
||||
}
|
||||
onCharacter(start, end, value) {
|
||||
if (this._options.onCharacter) {
|
||||
this._options.onCharacter(start, end, value);
|
||||
}
|
||||
}
|
||||
onBackreference(start, end, ref) {
|
||||
if (this._options.onBackreference) {
|
||||
this._options.onBackreference(start, end, ref);
|
||||
}
|
||||
}
|
||||
onCharacterClassEnter(start, negate, unicodeSets) {
|
||||
if (this._options.onCharacterClassEnter) {
|
||||
this._options.onCharacterClassEnter(start, negate, unicodeSets);
|
||||
}
|
||||
}
|
||||
onCharacterClassLeave(start, end, negate) {
|
||||
if (this._options.onCharacterClassLeave) {
|
||||
this._options.onCharacterClassLeave(start, end, negate);
|
||||
}
|
||||
}
|
||||
onCharacterClassRange(start, end, min, max) {
|
||||
if (this._options.onCharacterClassRange) {
|
||||
this._options.onCharacterClassRange(start, end, min, max);
|
||||
}
|
||||
}
|
||||
onClassIntersection(start, end) {
|
||||
if (this._options.onClassIntersection) {
|
||||
this._options.onClassIntersection(start, end);
|
||||
}
|
||||
}
|
||||
onClassSubtraction(start, end) {
|
||||
if (this._options.onClassSubtraction) {
|
||||
this._options.onClassSubtraction(start, end);
|
||||
}
|
||||
}
|
||||
onClassStringDisjunctionEnter(start) {
|
||||
if (this._options.onClassStringDisjunctionEnter) {
|
||||
this._options.onClassStringDisjunctionEnter(start);
|
||||
}
|
||||
}
|
||||
onClassStringDisjunctionLeave(start, end) {
|
||||
if (this._options.onClassStringDisjunctionLeave) {
|
||||
this._options.onClassStringDisjunctionLeave(start, end);
|
||||
}
|
||||
}
|
||||
onStringAlternativeEnter(start, index) {
|
||||
if (this._options.onStringAlternativeEnter) {
|
||||
this._options.onStringAlternativeEnter(start, index);
|
||||
}
|
||||
}
|
||||
onStringAlternativeLeave(start, end, index) {
|
||||
if (this._options.onStringAlternativeLeave) {
|
||||
this._options.onStringAlternativeLeave(start, end, index);
|
||||
}
|
||||
}
|
||||
get index() {
|
||||
return this._reader.index;
|
||||
}
|
||||
get currentCodePoint() {
|
||||
return this._reader.currentCodePoint;
|
||||
}
|
||||
get nextCodePoint() {
|
||||
return this._reader.nextCodePoint;
|
||||
}
|
||||
get nextCodePoint2() {
|
||||
return this._reader.nextCodePoint2;
|
||||
}
|
||||
get nextCodePoint3() {
|
||||
return this._reader.nextCodePoint3;
|
||||
}
|
||||
reset(source, start, end) {
|
||||
this._reader.reset(source, start, end, this._unicodeMode);
|
||||
}
|
||||
rewind(index) {
|
||||
this._reader.rewind(index);
|
||||
}
|
||||
advance() {
|
||||
this._reader.advance();
|
||||
}
|
||||
eat(cp) {
|
||||
return this._reader.eat(cp);
|
||||
}
|
||||
eat2(cp1, cp2) {
|
||||
return this._reader.eat2(cp1, cp2);
|
||||
}
|
||||
eat3(cp1, cp2, cp3) {
|
||||
return this._reader.eat3(cp1, cp2, cp3);
|
||||
}
|
||||
raise(message, context) {
|
||||
var _a, _b, _c;
|
||||
throw newRegExpSyntaxError(this._srcCtx, {
|
||||
unicode: (_a = context === null || context === void 0 ? void 0 : context.unicode) !== null && _a !== void 0 ? _a : (this._unicodeMode && !this._unicodeSetsMode),
|
||||
unicodeSets: (_b = context === null || context === void 0 ? void 0 : context.unicodeSets) !== null && _b !== void 0 ? _b : this._unicodeSetsMode,
|
||||
}, (_c = context === null || context === void 0 ? void 0 : context.index) !== null && _c !== void 0 ? _c : this.index, message);
|
||||
}
|
||||
eatRegExpBody() {
|
||||
const start = this.index;
|
||||
let inClass = false;
|
||||
let escaped = false;
|
||||
for (;;) {
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp === -1 || isLineTerminator(cp)) {
|
||||
const kind = inClass ? "character class" : "regular expression";
|
||||
this.raise(`Unterminated ${kind}`);
|
||||
}
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
}
|
||||
else if (cp === REVERSE_SOLIDUS) {
|
||||
escaped = true;
|
||||
}
|
||||
else if (cp === LEFT_SQUARE_BRACKET) {
|
||||
inClass = true;
|
||||
}
|
||||
else if (cp === RIGHT_SQUARE_BRACKET) {
|
||||
inClass = false;
|
||||
}
|
||||
else if ((cp === SOLIDUS && !inClass) ||
|
||||
(cp === ASTERISK && this.index === start)) {
|
||||
break;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
consumePattern() {
|
||||
const start = this.index;
|
||||
this._numCapturingParens = this.countCapturingParens();
|
||||
this._groupSpecifiers.clear();
|
||||
this._backreferenceNames.clear();
|
||||
this.onPatternEnter(start);
|
||||
this.consumeDisjunction();
|
||||
const cp = this.currentCodePoint;
|
||||
if (this.currentCodePoint !== -1) {
|
||||
if (cp === RIGHT_PARENTHESIS) {
|
||||
this.raise("Unmatched ')'");
|
||||
}
|
||||
if (cp === REVERSE_SOLIDUS) {
|
||||
this.raise("\\ at end of pattern");
|
||||
}
|
||||
if (cp === RIGHT_SQUARE_BRACKET || cp === RIGHT_CURLY_BRACKET) {
|
||||
this.raise("Lone quantifier brackets");
|
||||
}
|
||||
const c = String.fromCodePoint(cp);
|
||||
this.raise(`Unexpected character '${c}'`);
|
||||
}
|
||||
for (const name of this._backreferenceNames) {
|
||||
if (!this._groupSpecifiers.hasInPattern(name)) {
|
||||
this.raise("Invalid named capture referenced");
|
||||
}
|
||||
}
|
||||
this.onPatternLeave(start, this.index);
|
||||
}
|
||||
countCapturingParens() {
|
||||
const start = this.index;
|
||||
let inClass = false;
|
||||
let escaped = false;
|
||||
let count = 0;
|
||||
let cp = 0;
|
||||
while ((cp = this.currentCodePoint) !== -1) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
}
|
||||
else if (cp === REVERSE_SOLIDUS) {
|
||||
escaped = true;
|
||||
}
|
||||
else if (cp === LEFT_SQUARE_BRACKET) {
|
||||
inClass = true;
|
||||
}
|
||||
else if (cp === RIGHT_SQUARE_BRACKET) {
|
||||
inClass = false;
|
||||
}
|
||||
else if (cp === LEFT_PARENTHESIS &&
|
||||
!inClass &&
|
||||
(this.nextCodePoint !== QUESTION_MARK ||
|
||||
(this.nextCodePoint2 === LESS_THAN_SIGN &&
|
||||
this.nextCodePoint3 !== EQUALS_SIGN &&
|
||||
this.nextCodePoint3 !== EXCLAMATION_MARK))) {
|
||||
count += 1;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
this.rewind(start);
|
||||
return count;
|
||||
}
|
||||
consumeDisjunction() {
|
||||
const start = this.index;
|
||||
let i = 0;
|
||||
this._groupSpecifiers.enterDisjunction();
|
||||
this.onDisjunctionEnter(start);
|
||||
do {
|
||||
this.consumeAlternative(i++);
|
||||
} while (this.eat(VERTICAL_LINE));
|
||||
if (this.consumeQuantifier(true)) {
|
||||
this.raise("Nothing to repeat");
|
||||
}
|
||||
if (this.eat(LEFT_CURLY_BRACKET)) {
|
||||
this.raise("Lone quantifier brackets");
|
||||
}
|
||||
this.onDisjunctionLeave(start, this.index);
|
||||
this._groupSpecifiers.leaveDisjunction();
|
||||
}
|
||||
consumeAlternative(i) {
|
||||
const start = this.index;
|
||||
this._groupSpecifiers.enterAlternative(i);
|
||||
this.onAlternativeEnter(start, i);
|
||||
while (this.currentCodePoint !== -1 && this.consumeTerm()) {
|
||||
}
|
||||
this.onAlternativeLeave(start, this.index, i);
|
||||
}
|
||||
consumeTerm() {
|
||||
if (this._unicodeMode || this.strict) {
|
||||
return (this.consumeAssertion() ||
|
||||
(this.consumeAtom() && this.consumeOptionalQuantifier()));
|
||||
}
|
||||
return ((this.consumeAssertion() &&
|
||||
(!this._lastAssertionIsQuantifiable ||
|
||||
this.consumeOptionalQuantifier())) ||
|
||||
(this.consumeExtendedAtom() && this.consumeOptionalQuantifier()));
|
||||
}
|
||||
consumeOptionalQuantifier() {
|
||||
this.consumeQuantifier();
|
||||
return true;
|
||||
}
|
||||
consumeAssertion() {
|
||||
const start = this.index;
|
||||
this._lastAssertionIsQuantifiable = false;
|
||||
if (this.eat(CIRCUMFLEX_ACCENT)) {
|
||||
this.onEdgeAssertion(start, this.index, "start");
|
||||
return true;
|
||||
}
|
||||
if (this.eat(DOLLAR_SIGN)) {
|
||||
this.onEdgeAssertion(start, this.index, "end");
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(REVERSE_SOLIDUS, LATIN_CAPITAL_LETTER_B)) {
|
||||
this.onWordBoundaryAssertion(start, this.index, "word", true);
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_B)) {
|
||||
this.onWordBoundaryAssertion(start, this.index, "word", false);
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) {
|
||||
const lookbehind = this.ecmaVersion >= 2018 && this.eat(LESS_THAN_SIGN);
|
||||
let negate = false;
|
||||
if (this.eat(EQUALS_SIGN) ||
|
||||
(negate = this.eat(EXCLAMATION_MARK))) {
|
||||
const kind = lookbehind ? "lookbehind" : "lookahead";
|
||||
this.onLookaroundAssertionEnter(start, kind, negate);
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this._lastAssertionIsQuantifiable = !lookbehind && !this.strict;
|
||||
this.onLookaroundAssertionLeave(start, this.index, kind, negate);
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeQuantifier(noConsume = false) {
|
||||
const start = this.index;
|
||||
let min = 0;
|
||||
let max = 0;
|
||||
let greedy = false;
|
||||
if (this.eat(ASTERISK)) {
|
||||
min = 0;
|
||||
max = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
else if (this.eat(PLUS_SIGN)) {
|
||||
min = 1;
|
||||
max = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
else if (this.eat(QUESTION_MARK)) {
|
||||
min = 0;
|
||||
max = 1;
|
||||
}
|
||||
else if (this.eatBracedQuantifier(noConsume)) {
|
||||
({ min, max } = this._lastRange);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
greedy = !this.eat(QUESTION_MARK);
|
||||
if (!noConsume) {
|
||||
this.onQuantifier(start, this.index, min, max, greedy);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
eatBracedQuantifier(noError) {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_CURLY_BRACKET)) {
|
||||
if (this.eatDecimalDigits()) {
|
||||
const min = this._lastIntValue;
|
||||
let max = min;
|
||||
if (this.eat(COMMA)) {
|
||||
max = this.eatDecimalDigits()
|
||||
? this._lastIntValue
|
||||
: Number.POSITIVE_INFINITY;
|
||||
}
|
||||
if (this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
if (!noError && max < min) {
|
||||
this.raise("numbers out of order in {} quantifier");
|
||||
}
|
||||
this._lastRange = { min, max };
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!noError && (this._unicodeMode || this.strict)) {
|
||||
this.raise("Incomplete quantifier");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeAtom() {
|
||||
return (this.consumePatternCharacter() ||
|
||||
this.consumeDot() ||
|
||||
this.consumeReverseSolidusAtomEscape() ||
|
||||
Boolean(this.consumeCharacterClass()) ||
|
||||
this.consumeCapturingGroup() ||
|
||||
this.consumeUncapturingGroup());
|
||||
}
|
||||
consumeDot() {
|
||||
if (this.eat(FULL_STOP)) {
|
||||
this.onAnyCharacterSet(this.index - 1, this.index, "any");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeReverseSolidusAtomEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeAtomEscape()) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeUncapturingGroup() {
|
||||
const start = this.index;
|
||||
if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) {
|
||||
this.onGroupEnter(start);
|
||||
if (this.ecmaVersion >= 2025) {
|
||||
this.consumeModifiers();
|
||||
}
|
||||
if (!this.eat(COLON)) {
|
||||
this.rewind(start + 1);
|
||||
this.raise("Invalid group");
|
||||
}
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this.onGroupLeave(start, this.index);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeModifiers() {
|
||||
const start = this.index;
|
||||
const hasAddModifiers = this.eatModifiers();
|
||||
const addModifiersEnd = this.index;
|
||||
const hasHyphen = this.eat(HYPHEN_MINUS);
|
||||
if (!hasAddModifiers && !hasHyphen) {
|
||||
return false;
|
||||
}
|
||||
this.onModifiersEnter(start);
|
||||
const addModifiers = this.parseModifiers(start, addModifiersEnd);
|
||||
this.onAddModifiers(start, addModifiersEnd, addModifiers);
|
||||
if (hasHyphen) {
|
||||
const modifiersStart = this.index;
|
||||
if (!this.eatModifiers() &&
|
||||
!hasAddModifiers &&
|
||||
this.currentCodePoint === COLON) {
|
||||
this.raise("Invalid empty flags");
|
||||
}
|
||||
const modifiers = this.parseModifiers(modifiersStart, this.index);
|
||||
for (const [flagName] of Object.entries(modifiers).filter(([, enable]) => enable)) {
|
||||
if (addModifiers[flagName]) {
|
||||
this.raise(`Duplicated flag '${String.fromCodePoint(FLAG_PROP_TO_CODEPOINT[flagName])}'`);
|
||||
}
|
||||
}
|
||||
this.onRemoveModifiers(modifiersStart, this.index, modifiers);
|
||||
}
|
||||
this.onModifiersLeave(start, this.index);
|
||||
return true;
|
||||
}
|
||||
consumeCapturingGroup() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_PARENTHESIS)) {
|
||||
let name = null;
|
||||
if (this.ecmaVersion >= 2018) {
|
||||
if (this.consumeGroupSpecifier()) {
|
||||
name = this._lastStrValue;
|
||||
}
|
||||
else if (this.currentCodePoint === QUESTION_MARK) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.currentCodePoint === QUESTION_MARK) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
this.onCapturingGroupEnter(start, name);
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this.onCapturingGroupLeave(start, this.index, name);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeExtendedAtom() {
|
||||
return (this.consumeDot() ||
|
||||
this.consumeReverseSolidusAtomEscape() ||
|
||||
this.consumeReverseSolidusFollowedByC() ||
|
||||
Boolean(this.consumeCharacterClass()) ||
|
||||
this.consumeCapturingGroup() ||
|
||||
this.consumeUncapturingGroup() ||
|
||||
this.consumeInvalidBracedQuantifier() ||
|
||||
this.consumeExtendedPatternCharacter());
|
||||
}
|
||||
consumeReverseSolidusFollowedByC() {
|
||||
const start = this.index;
|
||||
if (this.currentCodePoint === REVERSE_SOLIDUS &&
|
||||
this.nextCodePoint === LATIN_SMALL_LETTER_C) {
|
||||
this._lastIntValue = this.currentCodePoint;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, REVERSE_SOLIDUS);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeInvalidBracedQuantifier() {
|
||||
if (this.eatBracedQuantifier(true)) {
|
||||
this.raise("Nothing to repeat");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumePatternCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 && !isSyntaxCharacter(cp)) {
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, cp);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeExtendedPatternCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 &&
|
||||
cp !== CIRCUMFLEX_ACCENT &&
|
||||
cp !== DOLLAR_SIGN &&
|
||||
cp !== REVERSE_SOLIDUS &&
|
||||
cp !== FULL_STOP &&
|
||||
cp !== ASTERISK &&
|
||||
cp !== PLUS_SIGN &&
|
||||
cp !== QUESTION_MARK &&
|
||||
cp !== LEFT_PARENTHESIS &&
|
||||
cp !== RIGHT_PARENTHESIS &&
|
||||
cp !== LEFT_SQUARE_BRACKET &&
|
||||
cp !== VERTICAL_LINE) {
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, cp);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeGroupSpecifier() {
|
||||
const start = this.index;
|
||||
if (this.eat(QUESTION_MARK)) {
|
||||
if (this.eatGroupName()) {
|
||||
if (!this._groupSpecifiers.hasInScope(this._lastStrValue)) {
|
||||
this._groupSpecifiers.addToScope(this._lastStrValue);
|
||||
return true;
|
||||
}
|
||||
this.raise("Duplicate capture group name");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeAtomEscape() {
|
||||
if (this.consumeBackreference() ||
|
||||
this.consumeCharacterClassEscape() ||
|
||||
this.consumeCharacterEscape() ||
|
||||
(this._nFlag && this.consumeKGroupName())) {
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeBackreference() {
|
||||
const start = this.index;
|
||||
if (this.eatDecimalEscape()) {
|
||||
const n = this._lastIntValue;
|
||||
if (n <= this._numCapturingParens) {
|
||||
this.onBackreference(start - 1, this.index, n);
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeCharacterClassEscape() {
|
||||
var _a;
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_D)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "digit", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_D)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "digit", true);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_S)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "space", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_S)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "space", true);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_W)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "word", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_W)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "word", true);
|
||||
return {};
|
||||
}
|
||||
let negate = false;
|
||||
if (this._unicodeMode &&
|
||||
this.ecmaVersion >= 2018 &&
|
||||
(this.eat(LATIN_SMALL_LETTER_P) ||
|
||||
(negate = this.eat(LATIN_CAPITAL_LETTER_P)))) {
|
||||
this._lastIntValue = -1;
|
||||
let result = null;
|
||||
if (this.eat(LEFT_CURLY_BRACKET) &&
|
||||
(result = this.eatUnicodePropertyValueExpression()) &&
|
||||
this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
if (negate && result.strings) {
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
this.onUnicodePropertyCharacterSet(start - 1, this.index, "property", result.key, result.value, negate, (_a = result.strings) !== null && _a !== void 0 ? _a : false);
|
||||
return { mayContainStrings: result.strings };
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeCharacterEscape() {
|
||||
const start = this.index;
|
||||
if (this.eatControlEscape() ||
|
||||
this.eatCControlLetter() ||
|
||||
this.eatZero() ||
|
||||
this.eatHexEscapeSequence() ||
|
||||
this.eatRegExpUnicodeEscapeSequence() ||
|
||||
(!this.strict &&
|
||||
!this._unicodeMode &&
|
||||
this.eatLegacyOctalEscapeSequence()) ||
|
||||
this.eatIdentityEscape()) {
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeKGroupName() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_K)) {
|
||||
if (this.eatGroupName()) {
|
||||
const groupName = this._lastStrValue;
|
||||
this._backreferenceNames.add(groupName);
|
||||
this.onBackreference(start - 1, this.index, groupName);
|
||||
return true;
|
||||
}
|
||||
this.raise("Invalid named reference");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeCharacterClass() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_SQUARE_BRACKET)) {
|
||||
const negate = this.eat(CIRCUMFLEX_ACCENT);
|
||||
this.onCharacterClassEnter(start, negate, this._unicodeSetsMode);
|
||||
const result = this.consumeClassContents();
|
||||
if (!this.eat(RIGHT_SQUARE_BRACKET)) {
|
||||
if (this.currentCodePoint === -1) {
|
||||
this.raise("Unterminated character class");
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (negate && result.mayContainStrings) {
|
||||
this.raise("Negated character class may contain strings");
|
||||
}
|
||||
this.onCharacterClassLeave(start, this.index, negate);
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassContents() {
|
||||
if (this._unicodeSetsMode) {
|
||||
if (this.currentCodePoint === RIGHT_SQUARE_BRACKET) {
|
||||
return {};
|
||||
}
|
||||
const result = this.consumeClassSetExpression();
|
||||
return result;
|
||||
}
|
||||
const strict = this.strict || this._unicodeMode;
|
||||
for (;;) {
|
||||
const rangeStart = this.index;
|
||||
if (!this.consumeClassAtom()) {
|
||||
break;
|
||||
}
|
||||
const min = this._lastIntValue;
|
||||
if (!this.eat(HYPHEN_MINUS)) {
|
||||
continue;
|
||||
}
|
||||
this.onCharacter(this.index - 1, this.index, HYPHEN_MINUS);
|
||||
if (!this.consumeClassAtom()) {
|
||||
break;
|
||||
}
|
||||
const max = this._lastIntValue;
|
||||
if (min === -1 || max === -1) {
|
||||
if (strict) {
|
||||
this.raise("Invalid character class");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (min > max) {
|
||||
this.raise("Range out of order in character class");
|
||||
}
|
||||
this.onCharacterClassRange(rangeStart, this.index, min, max);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
consumeClassAtom() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 &&
|
||||
cp !== REVERSE_SOLIDUS &&
|
||||
cp !== RIGHT_SQUARE_BRACKET) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeClassEscape()) {
|
||||
return true;
|
||||
}
|
||||
if (!this.strict &&
|
||||
this.currentCodePoint === LATIN_SMALL_LETTER_C) {
|
||||
this._lastIntValue = REVERSE_SOLIDUS;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeClassEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_B)) {
|
||||
this._lastIntValue = BACKSPACE;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this._unicodeMode && this.eat(HYPHEN_MINUS)) {
|
||||
this._lastIntValue = HYPHEN_MINUS;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
let cp = 0;
|
||||
if (!this.strict &&
|
||||
!this._unicodeMode &&
|
||||
this.currentCodePoint === LATIN_SMALL_LETTER_C &&
|
||||
(isDecimalDigit((cp = this.nextCodePoint)) || cp === LOW_LINE)) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
this._lastIntValue = cp % 0x20;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
return (Boolean(this.consumeCharacterClassEscape()) ||
|
||||
this.consumeCharacterEscape());
|
||||
}
|
||||
consumeClassSetExpression() {
|
||||
const start = this.index;
|
||||
let mayContainStrings = false;
|
||||
let result = null;
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
if (this.consumeClassSetRangeFromOperator(start)) {
|
||||
this.consumeClassUnionRight({});
|
||||
return {};
|
||||
}
|
||||
mayContainStrings = false;
|
||||
}
|
||||
else if ((result = this.consumeClassSetOperand())) {
|
||||
mayContainStrings = result.mayContainStrings;
|
||||
}
|
||||
else {
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp === REVERSE_SOLIDUS) {
|
||||
this.advance();
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
if (cp === this.nextCodePoint &&
|
||||
isClassSetReservedDoublePunctuatorCharacter(cp)) {
|
||||
this.raise("Invalid set operation in character class");
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (this.eat2(AMPERSAND, AMPERSAND)) {
|
||||
while (this.currentCodePoint !== AMPERSAND &&
|
||||
(result = this.consumeClassSetOperand())) {
|
||||
this.onClassIntersection(start, this.index);
|
||||
if (!result.mayContainStrings) {
|
||||
mayContainStrings = false;
|
||||
}
|
||||
if (this.eat2(AMPERSAND, AMPERSAND)) {
|
||||
continue;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) {
|
||||
while (this.consumeClassSetOperand()) {
|
||||
this.onClassSubtraction(start, this.index);
|
||||
if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) {
|
||||
continue;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
return this.consumeClassUnionRight({ mayContainStrings });
|
||||
}
|
||||
consumeClassUnionRight(leftResult) {
|
||||
let mayContainStrings = leftResult.mayContainStrings;
|
||||
for (;;) {
|
||||
const start = this.index;
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
this.consumeClassSetRangeFromOperator(start);
|
||||
continue;
|
||||
}
|
||||
const result = this.consumeClassSetOperand();
|
||||
if (result) {
|
||||
if (result.mayContainStrings) {
|
||||
mayContainStrings = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
consumeClassSetRangeFromOperator(start) {
|
||||
const currentStart = this.index;
|
||||
const min = this._lastIntValue;
|
||||
if (this.eat(HYPHEN_MINUS)) {
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
const max = this._lastIntValue;
|
||||
if (min === -1 || max === -1) {
|
||||
this.raise("Invalid character class");
|
||||
}
|
||||
if (min > max) {
|
||||
this.raise("Range out of order in character class");
|
||||
}
|
||||
this.onCharacterClassRange(start, this.index, min, max);
|
||||
return true;
|
||||
}
|
||||
this.rewind(currentStart);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeClassSetOperand() {
|
||||
let result = null;
|
||||
if ((result = this.consumeNestedClass())) {
|
||||
return result;
|
||||
}
|
||||
if ((result = this.consumeClassStringDisjunction())) {
|
||||
return result;
|
||||
}
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
return {};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeNestedClass() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_SQUARE_BRACKET)) {
|
||||
const negate = this.eat(CIRCUMFLEX_ACCENT);
|
||||
this.onCharacterClassEnter(start, negate, true);
|
||||
const result = this.consumeClassContents();
|
||||
if (!this.eat(RIGHT_SQUARE_BRACKET)) {
|
||||
this.raise("Unterminated character class");
|
||||
}
|
||||
if (negate && result.mayContainStrings) {
|
||||
this.raise("Negated character class may contain strings");
|
||||
}
|
||||
this.onCharacterClassLeave(start, this.index, negate);
|
||||
return result;
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
const result = this.consumeCharacterClassEscape();
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassStringDisjunction() {
|
||||
const start = this.index;
|
||||
if (this.eat3(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_Q, LEFT_CURLY_BRACKET)) {
|
||||
this.onClassStringDisjunctionEnter(start);
|
||||
let i = 0;
|
||||
let mayContainStrings = false;
|
||||
do {
|
||||
if (this.consumeClassString(i++).mayContainStrings) {
|
||||
mayContainStrings = true;
|
||||
}
|
||||
} while (this.eat(VERTICAL_LINE));
|
||||
if (this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
this.onClassStringDisjunctionLeave(start, this.index);
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Unterminated class string disjunction");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassString(i) {
|
||||
const start = this.index;
|
||||
let count = 0;
|
||||
this.onStringAlternativeEnter(start, i);
|
||||
while (this.currentCodePoint !== -1 &&
|
||||
this.consumeClassSetCharacter()) {
|
||||
count++;
|
||||
}
|
||||
this.onStringAlternativeLeave(start, this.index, i);
|
||||
return { mayContainStrings: count !== 1 };
|
||||
}
|
||||
consumeClassSetCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== this.nextCodePoint ||
|
||||
!isClassSetReservedDoublePunctuatorCharacter(cp)) {
|
||||
if (cp !== -1 && !isClassSetSyntaxCharacter(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeCharacterEscape()) {
|
||||
return true;
|
||||
}
|
||||
if (isClassSetReservedPunctuator(this.currentCodePoint)) {
|
||||
this._lastIntValue = this.currentCodePoint;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_B)) {
|
||||
this._lastIntValue = BACKSPACE;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatGroupName() {
|
||||
if (this.eat(LESS_THAN_SIGN)) {
|
||||
if (this.eatRegExpIdentifierName() && this.eat(GREATER_THAN_SIGN)) {
|
||||
return true;
|
||||
}
|
||||
this.raise("Invalid capture group name");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierName() {
|
||||
if (this.eatRegExpIdentifierStart()) {
|
||||
this._lastStrValue = String.fromCodePoint(this._lastIntValue);
|
||||
while (this.eatRegExpIdentifierPart()) {
|
||||
this._lastStrValue += String.fromCodePoint(this._lastIntValue);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierStart() {
|
||||
const start = this.index;
|
||||
const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020;
|
||||
let cp = this.currentCodePoint;
|
||||
this.advance();
|
||||
if (cp === REVERSE_SOLIDUS &&
|
||||
this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
|
||||
cp = this._lastIntValue;
|
||||
}
|
||||
else if (forceUFlag &&
|
||||
isLeadSurrogate(cp) &&
|
||||
isTrailSurrogate(this.currentCodePoint)) {
|
||||
cp = combineSurrogatePair(cp, this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
if (isIdentifierStartChar(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
return true;
|
||||
}
|
||||
if (this.index !== start) {
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierPart() {
|
||||
const start = this.index;
|
||||
const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020;
|
||||
let cp = this.currentCodePoint;
|
||||
this.advance();
|
||||
if (cp === REVERSE_SOLIDUS &&
|
||||
this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
|
||||
cp = this._lastIntValue;
|
||||
}
|
||||
else if (forceUFlag &&
|
||||
isLeadSurrogate(cp) &&
|
||||
isTrailSurrogate(this.currentCodePoint)) {
|
||||
cp = combineSurrogatePair(cp, this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
if (isIdentifierPartChar(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
return true;
|
||||
}
|
||||
if (this.index !== start) {
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatCControlLetter() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_C)) {
|
||||
if (this.eatControlLetter()) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatZero() {
|
||||
if (this.currentCodePoint === DIGIT_ZERO &&
|
||||
!isDecimalDigit(this.nextCodePoint)) {
|
||||
this._lastIntValue = 0;
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatControlEscape() {
|
||||
if (this.eat(LATIN_SMALL_LETTER_F)) {
|
||||
this._lastIntValue = FORM_FEED;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_N)) {
|
||||
this._lastIntValue = LINE_FEED;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_R)) {
|
||||
this._lastIntValue = CARRIAGE_RETURN;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_T)) {
|
||||
this._lastIntValue = CHARACTER_TABULATION;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_V)) {
|
||||
this._lastIntValue = LINE_TABULATION;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatControlLetter() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (isLatinLetter(cp)) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp % 0x20;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeEscapeSequence(forceUFlag = false) {
|
||||
const start = this.index;
|
||||
const uFlag = forceUFlag || this._unicodeMode;
|
||||
if (this.eat(LATIN_SMALL_LETTER_U)) {
|
||||
if ((uFlag && this.eatRegExpUnicodeSurrogatePairEscape()) ||
|
||||
this.eatFixedHexDigits(4) ||
|
||||
(uFlag && this.eatRegExpUnicodeCodePointEscape())) {
|
||||
return true;
|
||||
}
|
||||
if (this.strict || uFlag) {
|
||||
this.raise("Invalid unicode escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeSurrogatePairEscape() {
|
||||
const start = this.index;
|
||||
if (this.eatFixedHexDigits(4)) {
|
||||
const lead = this._lastIntValue;
|
||||
if (isLeadSurrogate(lead) &&
|
||||
this.eat(REVERSE_SOLIDUS) &&
|
||||
this.eat(LATIN_SMALL_LETTER_U) &&
|
||||
this.eatFixedHexDigits(4)) {
|
||||
const trail = this._lastIntValue;
|
||||
if (isTrailSurrogate(trail)) {
|
||||
this._lastIntValue = combineSurrogatePair(lead, trail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeCodePointEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_CURLY_BRACKET) &&
|
||||
this.eatHexDigits() &&
|
||||
this.eat(RIGHT_CURLY_BRACKET) &&
|
||||
isValidUnicode(this._lastIntValue)) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
eatIdentityEscape() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (this.isValidIdentityEscape(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
isValidIdentityEscape(cp) {
|
||||
if (cp === -1) {
|
||||
return false;
|
||||
}
|
||||
if (this._unicodeMode) {
|
||||
return isSyntaxCharacter(cp) || cp === SOLIDUS;
|
||||
}
|
||||
if (this.strict) {
|
||||
return !isIdContinue(cp);
|
||||
}
|
||||
if (this._nFlag) {
|
||||
return !(cp === LATIN_SMALL_LETTER_C || cp === LATIN_SMALL_LETTER_K);
|
||||
}
|
||||
return cp !== LATIN_SMALL_LETTER_C;
|
||||
}
|
||||
eatDecimalEscape() {
|
||||
this._lastIntValue = 0;
|
||||
let cp = this.currentCodePoint;
|
||||
if (cp >= DIGIT_ONE && cp <= DIGIT_NINE) {
|
||||
do {
|
||||
this._lastIntValue = 10 * this._lastIntValue + (cp - DIGIT_ZERO);
|
||||
this.advance();
|
||||
} while ((cp = this.currentCodePoint) >= DIGIT_ZERO &&
|
||||
cp <= DIGIT_NINE);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatUnicodePropertyValueExpression() {
|
||||
const start = this.index;
|
||||
if (this.eatUnicodePropertyName() && this.eat(EQUALS_SIGN)) {
|
||||
const key = this._lastStrValue;
|
||||
if (this.eatUnicodePropertyValue()) {
|
||||
const value = this._lastStrValue;
|
||||
if (isValidUnicodeProperty(this.ecmaVersion, key, value)) {
|
||||
return {
|
||||
key,
|
||||
value: value || null,
|
||||
};
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
}
|
||||
this.rewind(start);
|
||||
if (this.eatLoneUnicodePropertyNameOrValue()) {
|
||||
const nameOrValue = this._lastStrValue;
|
||||
if (isValidUnicodeProperty(this.ecmaVersion, "General_Category", nameOrValue)) {
|
||||
return {
|
||||
key: "General_Category",
|
||||
value: nameOrValue || null,
|
||||
};
|
||||
}
|
||||
if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) {
|
||||
return {
|
||||
key: nameOrValue,
|
||||
value: null,
|
||||
};
|
||||
}
|
||||
if (this._unicodeSetsMode &&
|
||||
isValidLoneUnicodePropertyOfString(this.ecmaVersion, nameOrValue)) {
|
||||
return {
|
||||
key: nameOrValue,
|
||||
value: null,
|
||||
strings: true,
|
||||
};
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
eatUnicodePropertyName() {
|
||||
this._lastStrValue = "";
|
||||
while (isUnicodePropertyNameCharacter(this.currentCodePoint)) {
|
||||
this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this._lastStrValue !== "";
|
||||
}
|
||||
eatUnicodePropertyValue() {
|
||||
this._lastStrValue = "";
|
||||
while (isUnicodePropertyValueCharacter(this.currentCodePoint)) {
|
||||
this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this._lastStrValue !== "";
|
||||
}
|
||||
eatLoneUnicodePropertyNameOrValue() {
|
||||
return this.eatUnicodePropertyValue();
|
||||
}
|
||||
eatHexEscapeSequence() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_X)) {
|
||||
if (this.eatFixedHexDigits(2)) {
|
||||
return true;
|
||||
}
|
||||
if (this._unicodeMode || this.strict) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatDecimalDigits() {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
while (isDecimalDigit(this.currentCodePoint)) {
|
||||
this._lastIntValue =
|
||||
10 * this._lastIntValue + digitToInt(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
eatHexDigits() {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
while (isHexDigit(this.currentCodePoint)) {
|
||||
this._lastIntValue =
|
||||
16 * this._lastIntValue + digitToInt(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
eatLegacyOctalEscapeSequence() {
|
||||
if (this.eatOctalDigit()) {
|
||||
const n1 = this._lastIntValue;
|
||||
if (this.eatOctalDigit()) {
|
||||
const n2 = this._lastIntValue;
|
||||
if (n1 <= 3 && this.eatOctalDigit()) {
|
||||
this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue;
|
||||
}
|
||||
else {
|
||||
this._lastIntValue = n1 * 8 + n2;
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._lastIntValue = n1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatOctalDigit() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (isOctalDigit(cp)) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp - DIGIT_ZERO;
|
||||
return true;
|
||||
}
|
||||
this._lastIntValue = 0;
|
||||
return false;
|
||||
}
|
||||
eatFixedHexDigits(length) {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
for (let i = 0; i < length; ++i) {
|
||||
const cp = this.currentCodePoint;
|
||||
if (!isHexDigit(cp)) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp);
|
||||
this.advance();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
eatModifiers() {
|
||||
let ate = false;
|
||||
while (isRegularExpressionModifier(this.currentCodePoint)) {
|
||||
this.advance();
|
||||
ate = true;
|
||||
}
|
||||
return ate;
|
||||
}
|
||||
parseModifiers(start, end) {
|
||||
const { ignoreCase, multiline, dotAll } = this.parseFlags(this._reader.source, start, end);
|
||||
return { ignoreCase, multiline, dotAll };
|
||||
}
|
||||
parseFlags(source, start, end) {
|
||||
const flags = {
|
||||
global: false,
|
||||
ignoreCase: false,
|
||||
multiline: false,
|
||||
unicode: false,
|
||||
sticky: false,
|
||||
dotAll: false,
|
||||
hasIndices: false,
|
||||
unicodeSets: false,
|
||||
};
|
||||
const validFlags = new Set();
|
||||
validFlags.add(LATIN_SMALL_LETTER_G);
|
||||
validFlags.add(LATIN_SMALL_LETTER_I);
|
||||
validFlags.add(LATIN_SMALL_LETTER_M);
|
||||
if (this.ecmaVersion >= 2015) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_U);
|
||||
validFlags.add(LATIN_SMALL_LETTER_Y);
|
||||
if (this.ecmaVersion >= 2018) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_S);
|
||||
if (this.ecmaVersion >= 2022) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_D);
|
||||
if (this.ecmaVersion >= 2024) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_V);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = start; i < end; ++i) {
|
||||
const flag = source.charCodeAt(i);
|
||||
if (validFlags.has(flag)) {
|
||||
const prop = FLAG_CODEPOINT_TO_PROP[flag];
|
||||
if (flags[prop]) {
|
||||
this.raise(`Duplicated flag '${source[i]}'`, {
|
||||
index: start,
|
||||
});
|
||||
}
|
||||
flags[prop] = true;
|
||||
}
|
||||
else {
|
||||
this.raise(`Invalid flag '${source[i]}'`, { index: start });
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
|
||||
const DUMMY_PATTERN = {};
|
||||
const DUMMY_FLAGS = {};
|
||||
const DUMMY_CAPTURING_GROUP = {};
|
||||
function isClassSetOperand(node) {
|
||||
return (node.type === "Character" ||
|
||||
node.type === "CharacterSet" ||
|
||||
node.type === "CharacterClass" ||
|
||||
node.type === "ExpressionCharacterClass" ||
|
||||
node.type === "ClassStringDisjunction");
|
||||
}
|
||||
class RegExpParserState {
|
||||
constructor(options) {
|
||||
var _a;
|
||||
this._node = DUMMY_PATTERN;
|
||||
this._expressionBufferMap = new Map();
|
||||
this._flags = DUMMY_FLAGS;
|
||||
this._backreferences = [];
|
||||
this._capturingGroups = [];
|
||||
this.source = "";
|
||||
this.strict = Boolean(options === null || options === void 0 ? void 0 : options.strict);
|
||||
this.ecmaVersion = (_a = options === null || options === void 0 ? void 0 : options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion;
|
||||
}
|
||||
get pattern() {
|
||||
if (this._node.type !== "Pattern") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
return this._node;
|
||||
}
|
||||
get flags() {
|
||||
if (this._flags.type !== "Flags") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
return this._flags;
|
||||
}
|
||||
onRegExpFlags(start, end, { global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, unicodeSets, }) {
|
||||
this._flags = {
|
||||
type: "Flags",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
global,
|
||||
ignoreCase,
|
||||
multiline,
|
||||
unicode,
|
||||
sticky,
|
||||
dotAll,
|
||||
hasIndices,
|
||||
unicodeSets,
|
||||
};
|
||||
}
|
||||
onPatternEnter(start) {
|
||||
this._node = {
|
||||
type: "Pattern",
|
||||
parent: null,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
alternatives: [],
|
||||
};
|
||||
this._backreferences.length = 0;
|
||||
this._capturingGroups.length = 0;
|
||||
}
|
||||
onPatternLeave(start, end) {
|
||||
this._node.end = end;
|
||||
this._node.raw = this.source.slice(start, end);
|
||||
for (const reference of this._backreferences) {
|
||||
const ref = reference.ref;
|
||||
const groups = typeof ref === "number"
|
||||
? [this._capturingGroups[ref - 1]]
|
||||
: this._capturingGroups.filter((g) => g.name === ref);
|
||||
if (groups.length === 1) {
|
||||
const group = groups[0];
|
||||
reference.ambiguous = false;
|
||||
reference.resolved = group;
|
||||
}
|
||||
else {
|
||||
reference.ambiguous = true;
|
||||
reference.resolved = groups;
|
||||
}
|
||||
for (const group of groups) {
|
||||
group.references.push(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
onAlternativeEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Assertion" &&
|
||||
parent.type !== "CapturingGroup" &&
|
||||
parent.type !== "Group" &&
|
||||
parent.type !== "Pattern") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "Alternative",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
elements: [],
|
||||
};
|
||||
parent.alternatives.push(this._node);
|
||||
}
|
||||
onAlternativeLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onGroupEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const group = {
|
||||
type: "Group",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
modifiers: null,
|
||||
alternatives: [],
|
||||
};
|
||||
this._node = group;
|
||||
parent.elements.push(this._node);
|
||||
}
|
||||
onGroupLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Group" || node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onModifiersEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Group") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "Modifiers",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
add: null,
|
||||
remove: null,
|
||||
};
|
||||
parent.modifiers = this._node;
|
||||
}
|
||||
onModifiersLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Modifiers" || node.parent.type !== "Group") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onAddModifiers(start, end, { ignoreCase, multiline, dotAll, }) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Modifiers") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.add = {
|
||||
type: "ModifierFlags",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ignoreCase,
|
||||
multiline,
|
||||
dotAll,
|
||||
};
|
||||
}
|
||||
onRemoveModifiers(start, end, { ignoreCase, multiline, dotAll, }) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Modifiers") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.remove = {
|
||||
type: "ModifierFlags",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ignoreCase,
|
||||
multiline,
|
||||
dotAll,
|
||||
};
|
||||
}
|
||||
onCapturingGroupEnter(start, name) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "CapturingGroup",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
name,
|
||||
alternatives: [],
|
||||
references: [],
|
||||
};
|
||||
parent.elements.push(this._node);
|
||||
this._capturingGroups.push(this._node);
|
||||
}
|
||||
onCapturingGroupLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "CapturingGroup" ||
|
||||
node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onQuantifier(start, end, min, max, greedy) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const element = parent.elements.pop();
|
||||
if (element == null ||
|
||||
element.type === "Quantifier" ||
|
||||
(element.type === "Assertion" && element.kind !== "lookahead")) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "Quantifier",
|
||||
parent,
|
||||
start: element.start,
|
||||
end,
|
||||
raw: this.source.slice(element.start, end),
|
||||
min,
|
||||
max,
|
||||
greedy,
|
||||
element,
|
||||
};
|
||||
parent.elements.push(node);
|
||||
element.parent = node;
|
||||
}
|
||||
onLookaroundAssertionEnter(start, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = (this._node = {
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
kind,
|
||||
negate,
|
||||
alternatives: [],
|
||||
});
|
||||
parent.elements.push(node);
|
||||
}
|
||||
onLookaroundAssertionLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Assertion" || node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onEdgeAssertion(start, end, kind) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
onWordBoundaryAssertion(start, end, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
negate,
|
||||
});
|
||||
}
|
||||
onAnyCharacterSet(start, end, kind) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "CharacterSet",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
onEscapeCharacterSet(start, end, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "CharacterSet",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
negate,
|
||||
});
|
||||
}
|
||||
onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const base = {
|
||||
type: "CharacterSet",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
strings: null,
|
||||
key,
|
||||
};
|
||||
if (strings) {
|
||||
if ((parent.type === "CharacterClass" && !parent.unicodeSets) ||
|
||||
negate ||
|
||||
value !== null) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate }));
|
||||
}
|
||||
else {
|
||||
parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate }));
|
||||
}
|
||||
}
|
||||
onCharacter(start, end, value) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" &&
|
||||
parent.type !== "CharacterClass" &&
|
||||
parent.type !== "StringAlternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Character",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
value,
|
||||
});
|
||||
}
|
||||
onBackreference(start, end, ref) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "Backreference",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ref,
|
||||
ambiguous: false,
|
||||
resolved: DUMMY_CAPTURING_GROUP,
|
||||
};
|
||||
parent.elements.push(node);
|
||||
this._backreferences.push(node);
|
||||
}
|
||||
onCharacterClassEnter(start, negate, unicodeSets) {
|
||||
const parent = this._node;
|
||||
const base = {
|
||||
type: "CharacterClass",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
unicodeSets,
|
||||
negate,
|
||||
elements: [],
|
||||
};
|
||||
if (parent.type === "Alternative") {
|
||||
const node = Object.assign(Object.assign({}, base), { parent });
|
||||
this._node = node;
|
||||
parent.elements.push(node);
|
||||
}
|
||||
else if (parent.type === "CharacterClass" &&
|
||||
parent.unicodeSets &&
|
||||
unicodeSets) {
|
||||
const node = Object.assign(Object.assign({}, base), { parent,
|
||||
unicodeSets });
|
||||
this._node = node;
|
||||
parent.elements.push(node);
|
||||
}
|
||||
else {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
}
|
||||
onCharacterClassLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "CharacterClass" ||
|
||||
(node.parent.type !== "Alternative" &&
|
||||
node.parent.type !== "CharacterClass")) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const parent = node.parent;
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = parent;
|
||||
const expression = this._expressionBufferMap.get(node);
|
||||
if (!expression) {
|
||||
return;
|
||||
}
|
||||
if (node.elements.length > 0) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._expressionBufferMap.delete(node);
|
||||
const newNode = {
|
||||
type: "ExpressionCharacterClass",
|
||||
parent,
|
||||
start: node.start,
|
||||
end: node.end,
|
||||
raw: node.raw,
|
||||
negate: node.negate,
|
||||
expression,
|
||||
};
|
||||
expression.parent = newNode;
|
||||
if (node !== parent.elements.pop()) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push(newNode);
|
||||
}
|
||||
onCharacterClassRange(start, end) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const elements = parent.elements;
|
||||
const max = elements.pop();
|
||||
if (!max || max.type !== "Character") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
if (!parent.unicodeSets) {
|
||||
const hyphen = elements.pop();
|
||||
if (!hyphen ||
|
||||
hyphen.type !== "Character" ||
|
||||
hyphen.value !== HYPHEN_MINUS) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
}
|
||||
const min = elements.pop();
|
||||
if (!min || min.type !== "Character") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "CharacterClassRange",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
min,
|
||||
max,
|
||||
};
|
||||
min.parent = node;
|
||||
max.parent = node;
|
||||
elements.push(node);
|
||||
}
|
||||
onClassIntersection(start, end) {
|
||||
var _a;
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const right = parent.elements.pop();
|
||||
const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop();
|
||||
if (!left ||
|
||||
!right ||
|
||||
left.type === "ClassSubtraction" ||
|
||||
(left.type !== "ClassIntersection" && !isClassSetOperand(left)) ||
|
||||
!isClassSetOperand(right)) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "ClassIntersection",
|
||||
parent: parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
left,
|
||||
right,
|
||||
};
|
||||
left.parent = node;
|
||||
right.parent = node;
|
||||
this._expressionBufferMap.set(parent, node);
|
||||
}
|
||||
onClassSubtraction(start, end) {
|
||||
var _a;
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const right = parent.elements.pop();
|
||||
const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop();
|
||||
if (!left ||
|
||||
!right ||
|
||||
left.type === "ClassIntersection" ||
|
||||
(left.type !== "ClassSubtraction" && !isClassSetOperand(left)) ||
|
||||
!isClassSetOperand(right)) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "ClassSubtraction",
|
||||
parent: parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
left,
|
||||
right,
|
||||
};
|
||||
left.parent = node;
|
||||
right.parent = node;
|
||||
this._expressionBufferMap.set(parent, node);
|
||||
}
|
||||
onClassStringDisjunctionEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "ClassStringDisjunction",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
alternatives: [],
|
||||
};
|
||||
parent.elements.push(this._node);
|
||||
}
|
||||
onClassStringDisjunctionLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "ClassStringDisjunction" ||
|
||||
node.parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onStringAlternativeEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "ClassStringDisjunction") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "StringAlternative",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
elements: [],
|
||||
};
|
||||
parent.alternatives.push(this._node);
|
||||
}
|
||||
onStringAlternativeLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "StringAlternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
}
|
||||
class RegExpParser {
|
||||
constructor(options) {
|
||||
this._state = new RegExpParserState(options);
|
||||
this._validator = new RegExpValidator(this._state);
|
||||
}
|
||||
parseLiteral(source, start = 0, end = source.length) {
|
||||
this._state.source = source;
|
||||
this._validator.validateLiteral(source, start, end);
|
||||
const pattern = this._state.pattern;
|
||||
const flags = this._state.flags;
|
||||
const literal = {
|
||||
type: "RegExpLiteral",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: source,
|
||||
pattern,
|
||||
flags,
|
||||
};
|
||||
pattern.parent = literal;
|
||||
flags.parent = literal;
|
||||
return literal;
|
||||
}
|
||||
parseFlags(source, start = 0, end = source.length) {
|
||||
this._state.source = source;
|
||||
this._validator.validateFlags(source, start, end);
|
||||
return this._state.flags;
|
||||
}
|
||||
parsePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
this._state.source = source;
|
||||
this._validator.validatePattern(source, start, end, uFlagOrFlags);
|
||||
return this._state.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
class RegExpVisitor {
|
||||
constructor(handlers) {
|
||||
this._handlers = handlers;
|
||||
}
|
||||
visit(node) {
|
||||
switch (node.type) {
|
||||
case "Alternative":
|
||||
this.visitAlternative(node);
|
||||
break;
|
||||
case "Assertion":
|
||||
this.visitAssertion(node);
|
||||
break;
|
||||
case "Backreference":
|
||||
this.visitBackreference(node);
|
||||
break;
|
||||
case "CapturingGroup":
|
||||
this.visitCapturingGroup(node);
|
||||
break;
|
||||
case "Character":
|
||||
this.visitCharacter(node);
|
||||
break;
|
||||
case "CharacterClass":
|
||||
this.visitCharacterClass(node);
|
||||
break;
|
||||
case "CharacterClassRange":
|
||||
this.visitCharacterClassRange(node);
|
||||
break;
|
||||
case "CharacterSet":
|
||||
this.visitCharacterSet(node);
|
||||
break;
|
||||
case "ClassIntersection":
|
||||
this.visitClassIntersection(node);
|
||||
break;
|
||||
case "ClassStringDisjunction":
|
||||
this.visitClassStringDisjunction(node);
|
||||
break;
|
||||
case "ClassSubtraction":
|
||||
this.visitClassSubtraction(node);
|
||||
break;
|
||||
case "ExpressionCharacterClass":
|
||||
this.visitExpressionCharacterClass(node);
|
||||
break;
|
||||
case "Flags":
|
||||
this.visitFlags(node);
|
||||
break;
|
||||
case "Group":
|
||||
this.visitGroup(node);
|
||||
break;
|
||||
case "Modifiers":
|
||||
this.visitModifiers(node);
|
||||
break;
|
||||
case "ModifierFlags":
|
||||
this.visitModifierFlags(node);
|
||||
break;
|
||||
case "Pattern":
|
||||
this.visitPattern(node);
|
||||
break;
|
||||
case "Quantifier":
|
||||
this.visitQuantifier(node);
|
||||
break;
|
||||
case "RegExpLiteral":
|
||||
this.visitRegExpLiteral(node);
|
||||
break;
|
||||
case "StringAlternative":
|
||||
this.visitStringAlternative(node);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown type: ${node.type}`);
|
||||
}
|
||||
}
|
||||
visitAlternative(node) {
|
||||
if (this._handlers.onAlternativeEnter) {
|
||||
this._handlers.onAlternativeEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onAlternativeLeave) {
|
||||
this._handlers.onAlternativeLeave(node);
|
||||
}
|
||||
}
|
||||
visitAssertion(node) {
|
||||
if (this._handlers.onAssertionEnter) {
|
||||
this._handlers.onAssertionEnter(node);
|
||||
}
|
||||
if (node.kind === "lookahead" || node.kind === "lookbehind") {
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
}
|
||||
if (this._handlers.onAssertionLeave) {
|
||||
this._handlers.onAssertionLeave(node);
|
||||
}
|
||||
}
|
||||
visitBackreference(node) {
|
||||
if (this._handlers.onBackreferenceEnter) {
|
||||
this._handlers.onBackreferenceEnter(node);
|
||||
}
|
||||
if (this._handlers.onBackreferenceLeave) {
|
||||
this._handlers.onBackreferenceLeave(node);
|
||||
}
|
||||
}
|
||||
visitCapturingGroup(node) {
|
||||
if (this._handlers.onCapturingGroupEnter) {
|
||||
this._handlers.onCapturingGroupEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onCapturingGroupLeave) {
|
||||
this._handlers.onCapturingGroupLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacter(node) {
|
||||
if (this._handlers.onCharacterEnter) {
|
||||
this._handlers.onCharacterEnter(node);
|
||||
}
|
||||
if (this._handlers.onCharacterLeave) {
|
||||
this._handlers.onCharacterLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterClass(node) {
|
||||
if (this._handlers.onCharacterClassEnter) {
|
||||
this._handlers.onCharacterClassEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onCharacterClassLeave) {
|
||||
this._handlers.onCharacterClassLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterClassRange(node) {
|
||||
if (this._handlers.onCharacterClassRangeEnter) {
|
||||
this._handlers.onCharacterClassRangeEnter(node);
|
||||
}
|
||||
this.visitCharacter(node.min);
|
||||
this.visitCharacter(node.max);
|
||||
if (this._handlers.onCharacterClassRangeLeave) {
|
||||
this._handlers.onCharacterClassRangeLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterSet(node) {
|
||||
if (this._handlers.onCharacterSetEnter) {
|
||||
this._handlers.onCharacterSetEnter(node);
|
||||
}
|
||||
if (this._handlers.onCharacterSetLeave) {
|
||||
this._handlers.onCharacterSetLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassIntersection(node) {
|
||||
if (this._handlers.onClassIntersectionEnter) {
|
||||
this._handlers.onClassIntersectionEnter(node);
|
||||
}
|
||||
this.visit(node.left);
|
||||
this.visit(node.right);
|
||||
if (this._handlers.onClassIntersectionLeave) {
|
||||
this._handlers.onClassIntersectionLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassStringDisjunction(node) {
|
||||
if (this._handlers.onClassStringDisjunctionEnter) {
|
||||
this._handlers.onClassStringDisjunctionEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onClassStringDisjunctionLeave) {
|
||||
this._handlers.onClassStringDisjunctionLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassSubtraction(node) {
|
||||
if (this._handlers.onClassSubtractionEnter) {
|
||||
this._handlers.onClassSubtractionEnter(node);
|
||||
}
|
||||
this.visit(node.left);
|
||||
this.visit(node.right);
|
||||
if (this._handlers.onClassSubtractionLeave) {
|
||||
this._handlers.onClassSubtractionLeave(node);
|
||||
}
|
||||
}
|
||||
visitExpressionCharacterClass(node) {
|
||||
if (this._handlers.onExpressionCharacterClassEnter) {
|
||||
this._handlers.onExpressionCharacterClassEnter(node);
|
||||
}
|
||||
this.visit(node.expression);
|
||||
if (this._handlers.onExpressionCharacterClassLeave) {
|
||||
this._handlers.onExpressionCharacterClassLeave(node);
|
||||
}
|
||||
}
|
||||
visitFlags(node) {
|
||||
if (this._handlers.onFlagsEnter) {
|
||||
this._handlers.onFlagsEnter(node);
|
||||
}
|
||||
if (this._handlers.onFlagsLeave) {
|
||||
this._handlers.onFlagsLeave(node);
|
||||
}
|
||||
}
|
||||
visitGroup(node) {
|
||||
if (this._handlers.onGroupEnter) {
|
||||
this._handlers.onGroupEnter(node);
|
||||
}
|
||||
if (node.modifiers) {
|
||||
this.visit(node.modifiers);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onGroupLeave) {
|
||||
this._handlers.onGroupLeave(node);
|
||||
}
|
||||
}
|
||||
visitModifiers(node) {
|
||||
if (this._handlers.onModifiersEnter) {
|
||||
this._handlers.onModifiersEnter(node);
|
||||
}
|
||||
if (node.add) {
|
||||
this.visit(node.add);
|
||||
}
|
||||
if (node.remove) {
|
||||
this.visit(node.remove);
|
||||
}
|
||||
if (this._handlers.onModifiersLeave) {
|
||||
this._handlers.onModifiersLeave(node);
|
||||
}
|
||||
}
|
||||
visitModifierFlags(node) {
|
||||
if (this._handlers.onModifierFlagsEnter) {
|
||||
this._handlers.onModifierFlagsEnter(node);
|
||||
}
|
||||
if (this._handlers.onModifierFlagsLeave) {
|
||||
this._handlers.onModifierFlagsLeave(node);
|
||||
}
|
||||
}
|
||||
visitPattern(node) {
|
||||
if (this._handlers.onPatternEnter) {
|
||||
this._handlers.onPatternEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onPatternLeave) {
|
||||
this._handlers.onPatternLeave(node);
|
||||
}
|
||||
}
|
||||
visitQuantifier(node) {
|
||||
if (this._handlers.onQuantifierEnter) {
|
||||
this._handlers.onQuantifierEnter(node);
|
||||
}
|
||||
this.visit(node.element);
|
||||
if (this._handlers.onQuantifierLeave) {
|
||||
this._handlers.onQuantifierLeave(node);
|
||||
}
|
||||
}
|
||||
visitRegExpLiteral(node) {
|
||||
if (this._handlers.onRegExpLiteralEnter) {
|
||||
this._handlers.onRegExpLiteralEnter(node);
|
||||
}
|
||||
this.visitPattern(node.pattern);
|
||||
this.visitFlags(node.flags);
|
||||
if (this._handlers.onRegExpLiteralLeave) {
|
||||
this._handlers.onRegExpLiteralLeave(node);
|
||||
}
|
||||
}
|
||||
visitStringAlternative(node) {
|
||||
if (this._handlers.onStringAlternativeEnter) {
|
||||
this._handlers.onStringAlternativeEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onStringAlternativeLeave) {
|
||||
this._handlers.onStringAlternativeLeave(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseRegExpLiteral(source, options) {
|
||||
return new RegExpParser(options).parseLiteral(String(source));
|
||||
}
|
||||
function validateRegExpLiteral(source, options) {
|
||||
new RegExpValidator(options).validateLiteral(source);
|
||||
}
|
||||
function visitRegExpAST(node, handlers) {
|
||||
new RegExpVisitor(handlers).visit(node);
|
||||
}
|
||||
|
||||
exports.AST = ast;
|
||||
exports.RegExpParser = RegExpParser;
|
||||
exports.RegExpSyntaxError = RegExpSyntaxError;
|
||||
exports.RegExpValidator = RegExpValidator;
|
||||
exports.parseRegExpLiteral = parseRegExpLiteral;
|
||||
exports.validateRegExpLiteral = validateRegExpLiteral;
|
||||
exports.visitRegExpAST = visitRegExpAST;
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+3032
@@ -0,0 +1,3032 @@
|
||||
var ast = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null
|
||||
});
|
||||
|
||||
const latestEcmaVersion = 2025;
|
||||
|
||||
let largeIdStartRanges = undefined;
|
||||
let largeIdContinueRanges = undefined;
|
||||
function isIdStart(cp) {
|
||||
if (cp < 0x41)
|
||||
return false;
|
||||
if (cp < 0x5b)
|
||||
return true;
|
||||
if (cp < 0x61)
|
||||
return false;
|
||||
if (cp < 0x7b)
|
||||
return true;
|
||||
return isLargeIdStart(cp);
|
||||
}
|
||||
function isIdContinue(cp) {
|
||||
if (cp < 0x30)
|
||||
return false;
|
||||
if (cp < 0x3a)
|
||||
return true;
|
||||
if (cp < 0x41)
|
||||
return false;
|
||||
if (cp < 0x5b)
|
||||
return true;
|
||||
if (cp === 0x5f)
|
||||
return true;
|
||||
if (cp < 0x61)
|
||||
return false;
|
||||
if (cp < 0x7b)
|
||||
return true;
|
||||
return isLargeIdStart(cp) || isLargeIdContinue(cp);
|
||||
}
|
||||
function isLargeIdStart(cp) {
|
||||
return isInRange(cp, largeIdStartRanges !== null && largeIdStartRanges !== void 0 ? largeIdStartRanges : (largeIdStartRanges = initLargeIdStartRanges()));
|
||||
}
|
||||
function isLargeIdContinue(cp) {
|
||||
return isInRange(cp, largeIdContinueRanges !== null && largeIdContinueRanges !== void 0 ? largeIdContinueRanges : (largeIdContinueRanges = initLargeIdContinueRanges()));
|
||||
}
|
||||
function initLargeIdStartRanges() {
|
||||
return restoreRanges("4q 0 b 0 5 0 6 m 2 u 2 cp 5 b f 4 8 0 2 0 3m 4 2 1 3 3 2 0 7 0 2 2 2 0 2 j 2 2a 2 3u 9 4l 2 11 3 0 7 14 20 q 5 3 1a 16 10 1 2 2q 2 0 g 1 8 1 b 2 3 0 h 0 2 t u 2g c 0 p w a 1 5 0 6 l 5 0 a 0 4 0 o o 8 a 6 n 2 6 h 15 1n 1h 4 0 j 0 8 9 g f 5 7 3 1 3 l 2 6 2 0 4 3 4 0 h 0 e 1 2 2 f 1 b 0 9 5 5 1 3 l 2 6 2 1 2 1 2 1 w 3 2 0 k 2 h 8 2 2 2 l 2 6 2 1 2 4 4 0 j 0 g 1 o 0 c 7 3 1 3 l 2 6 2 1 2 4 4 0 v 1 2 2 g 0 i 0 2 5 4 2 2 3 4 1 2 0 2 1 4 1 4 2 4 b n 0 1h 7 2 2 2 m 2 f 4 0 r 2 2 1 3 1 v 0 5 7 2 2 2 m 2 9 2 4 4 0 v 2 2 1 g 1 i 8 2 2 2 14 3 0 h 0 6 2 9 2 p 5 6 h 4 n 2 8 2 0 3 6 1n 1b 2 1 d 6 1n 1 2 0 2 4 2 n 2 0 2 9 2 1 a 0 3 4 2 0 m 3 x 0 1s 7 2 z s 4 38 16 l 0 h 5 5 3 4 0 4 1 8 2 5 c d 0 i 11 2 0 6 0 3 16 2 98 2 3 3 6 2 0 2 3 3 14 2 3 3 w 2 3 3 6 2 0 2 3 3 e 2 1k 2 3 3 1u 12 f h 2d 3 5 4 h7 3 g 2 p 6 22 4 a 8 h e i f h f c 2 2 g 1f 10 0 5 0 1w 2g 8 14 2 0 6 1x b u 1e t 3 4 c 17 5 p 1j m a 1g 2b 0 2m 1a i 7 1j t e 1 b 17 r z 16 2 b z 3 a 6 16 3 2 16 3 2 5 2 1 4 0 6 5b 1t 7p 3 5 3 11 3 5 3 7 2 0 2 0 2 0 2 u 3 1g 2 6 2 0 4 2 2 6 4 3 3 5 5 c 6 2 2 6 39 0 e 0 h c 2u 0 5 0 3 9 2 0 3 5 7 0 2 0 2 0 2 f 3 3 6 4 5 0 i 14 22g 6c 7 3 4 1 d 11 2 0 6 0 3 1j 8 0 h m a 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 fb 2 q 8 8 4 3 4 5 2d 5 4 2 2h 2 3 6 16 2 2l i v 1d f e9 533 1t h3g 1w 19 3 7g 4 f b 1 l 1a h u 3 27 14 8 3 2u 3 29 l g 2 2 2 3 2 m u 1f f 1d 1r 5 4 0 2 1 c r b m q s 8 1a t 0 h 4 2 9 b 4 2 14 o 2 2 7 l m 4 0 4 1d 2 0 4 1 3 4 3 0 2 0 p 2 3 a 8 2 d 5 3 5 3 5 a 6 2 6 2 16 2 d 7 36 u 8mb d m 5 1c 6it a5 3 2x 13 6 d 4 6 0 2 9 2 c 2 4 2 0 2 1 2 1 2 2z y a2 j 1r 3 1h 15 b 39 4 2 3q 11 p 7 p c 2g 4 5 3 5 3 5 3 2 10 b 2 p 2 i 2 1 2 e 3 d z 3e 1y 1g 7g s 4 1c 1c v e t 6 11 b t 3 z 5 7 2 4 17 4d j z 5 z 5 13 9 1f d a 2 e 2 6 2 1 2 a 2 e 2 6 2 1 4 1f d 8m a l b 7 p 5 2 15 2 8 1y 5 3 0 2 17 2 1 4 0 3 m b m a u 1u i 2 1 b l b p 7 p 13 1j 7 1 1t 0 g 3 2 2 2 s 17 s 4 s 10 7 2 r s 1h b l b i e h 33 20 1k 1e e 1e e z 13 r a m 6z 15 7 1 h 5 1l s b 0 9 l 17 h 1b k s m d 1g 1m 1 3 0 e 18 x o r z u 0 3 0 9 y 4 0 d 1b f 3 m 0 2 0 10 h 2 o k 1 1s 6 2 0 2 3 2 e 2 9 8 1a 13 7 3 1 3 l 2 6 2 1 2 4 4 0 j 0 d 4 v 9 2 0 3 0 2 11 2 0 q 0 2 0 19 1g j 3 l 2 v 1b l 1 2 0 55 1a 16 3 11 1b l 0 1o 16 e 0 20 q 12 6 56 17 39 1r w 7 3 0 3 7 2 1 2 n g 0 2 0 2n 7 3 12 h 0 2 0 t 0 b 13 8 0 m 0 c 19 k 0 j 20 5k w w 8 2 10 i 0 1e t 35 6 2 1 2 11 m 0 q 5 2 1 2 v f 0 o 17 79 i g 0 2 c 2 x 3h 0 28 pl 2v 32 i 5f 219 2o g tr i 5 q 32y 6 g6 5a2 t 1cz fs 8 u i 26 i t j 1b h 3 w k 6 i c1 18 5w 1r x o 3 o 19 22 6 0 1v c 1t 1 2 0 f 4 a 5p1 16 v 2q 36 6pq 3 2 6 2 1 2 82 g 0 u 2 3 0 f 3 9 az 1s5 2y 6 c 4 8 8 9 4mf 2c 2 1y 2 1 3 0 3 1 3 3 2 b 2 0 2 6 2 1s 2 3 3 7 2 6 2 r 2 3 2 4 2 0 4 6 2 9f 3 o 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 u 2 o 2 7 1f9 u 7 5 7a 1p 43 18 b 6 h 0 8y t j 17 dh r 6d t 3 0 5s u 2 2 2 1 2 6 3 4 a 1 69 6 2 3 2 1 2 e 2 5g 1o 1v 8 0 xh 3 2 q 2 1 2 0 3 0 2 9 2 3 2 0 2 0 7 0 5 0 2 0 2 0 2 2 2 1 2 0 3 0 2 0 2 0 2 0 2 0 2 1 2 0 3 3 2 6 2 3 2 3 2 0 2 9 2 g 6 2 2 4 2 g 3et wyn x 3dp 3 4gd 3 5rk g h9 1wj f1 15v 3t6 6 6jt");
|
||||
}
|
||||
function initLargeIdContinueRanges() {
|
||||
return restoreRanges("53 0 g9 33 o 0 70 4 7e 18 2 0 2 1 2 1 2 0 21 a 1d u 7 0 2u 6 3 5 3 1 2 3 3 9 o 0 v q 2k a g 9 y 8 a 0 p 3 2 8 2 2 2 4 18 2 1o 8 17 n 2 w 1j 2 2 h 2 6 b 1 3 9 i 2 1l 0 2 6 3 1 3 2 a 0 b 1 3 9 f 0 3 2 1l 0 2 4 5 1 3 2 4 0 l b 4 0 c 2 1l 0 2 7 2 2 2 2 l 1 3 9 b 5 2 2 1l 0 2 6 3 1 3 2 8 2 b 1 3 9 j 0 1o 4 4 2 2 3 a 0 f 9 h 4 1k 0 2 6 2 2 2 3 8 1 c 1 3 9 i 2 1l 0 2 6 2 2 2 3 8 1 c 1 3 9 4 0 d 3 1k 1 2 6 2 2 2 3 a 0 b 1 3 9 i 2 1z 0 5 5 2 0 2 7 7 9 3 1 1q 0 3 6 d 7 2 9 2g 0 3 8 c 6 2 9 1r 1 7 9 c 0 2 0 2 0 5 1 1e j 2 1 6 a 2 z a 0 2t j 2 9 d 3 5 2 2 2 3 6 4 3 e b 2 e jk 2 a 8 pt 3 t 2 u 1 v 1 1t v a 0 3 9 y 2 2 a 40 0 3b b 5 b b 9 3l a 1p 4 1m 9 2 s 3 a 7 9 n d 2 u 3 b l 4 1c g c 9 i 8 d 2 v c 3 9 19 d 1d j 9 9 7 9 3b 2 2 k 5 0 7 0 3 2 5j 1r el 1 1e 1 k 0 3g c 5 0 4 b 2db 2 3y 0 2p v ff 5 2y 1 2p 0 n51 9 1y 0 5 9 x 1 29 1 7l 0 4 0 5 0 o 4 5 0 2c 1 1f h b 9 7 h e a t 7 q c 19 3 1c d g 9 c 0 b 9 1c d d 0 9 1 3 9 y 2 1f 0 2 2 3 1 6 1 2 0 16 4 6 1 6l 7 2 1 3 9 fmt 0 ki f h f 4 1 p 2 5d 9 12 0 12 0 ig 0 6b 0 46 4 86 9 120 2 2 1 6 3 15 2 5 0 4m 1 fy 3 9 9 7 9 w 4 8u 1 26 5 1z a 1e 3 3f 2 1i e w a 3 1 b 3 1a a 8 0 1a 9 7 2 11 d 2 9 6 1 19 0 d 2 1d d 9 3 2 b 2b b 7 0 3 0 4e b 6 9 7 3 1k 1 2 6 3 1 3 2 a 0 b 1 3 6 4 4 1w 8 2 0 3 0 2 3 2 4 2 0 f 1 2b h a 9 5 0 2a j d 9 5y 6 3 8 s 1 2b g g 9 2a c 9 9 7 j 1m e 5 9 6r e 4m 9 1z 5 2 1 3 3 2 0 2 1 d 9 3c 6 3 6 4 0 t 9 15 6 2 3 9 0 a a 1b f 5j 7 3t 9 1i 7 2 7 h 9 1l l 2 d 3f 5 4 0 2 1 2 6 2 0 9 9 1d 4 2 1 2 4 9 9 1j 9 7e 3 a 1 2 0 1d 6 4 4 e a 44m 0 7 e 8uh r 1t3 9 2f 9 13 4 1o 6 q 9 ev 9 d2 0 2 1i 8 3 2a 0 c 1 f58 1 382 9 ef 19 3 m f3 4 4 5 9 7 3 6 v 3 45 2 13e 1d e9 1i 5 1d 9 0 f 0 n 4 2 e 11t 6 2 g 3 6 2 1 2 4 2t 0 4h 6 a 9 9x 0 1q d dv d 6t 1 2 9 6h 0 3 0 8 1 6 0 d7 6 32 6 6 9 3o7 9 gvt3 6n");
|
||||
}
|
||||
function isInRange(cp, ranges) {
|
||||
let l = 0, r = (ranges.length / 2) | 0, i = 0, min = 0, max = 0;
|
||||
while (l < r) {
|
||||
i = ((l + r) / 2) | 0;
|
||||
min = ranges[2 * i];
|
||||
max = ranges[2 * i + 1];
|
||||
if (cp < min) {
|
||||
r = i;
|
||||
}
|
||||
else if (cp > max) {
|
||||
l = i + 1;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function restoreRanges(data) {
|
||||
let last = 0;
|
||||
return data.split(" ").map((s) => (last += parseInt(s, 36) | 0));
|
||||
}
|
||||
|
||||
class DataSet {
|
||||
constructor(raw2018, raw2019, raw2020, raw2021, raw2022, raw2023, raw2024, raw2025, raw2026) {
|
||||
this._raw2018 = raw2018;
|
||||
this._raw2019 = raw2019;
|
||||
this._raw2020 = raw2020;
|
||||
this._raw2021 = raw2021;
|
||||
this._raw2022 = raw2022;
|
||||
this._raw2023 = raw2023;
|
||||
this._raw2024 = raw2024;
|
||||
this._raw2025 = raw2025;
|
||||
this._raw2026 = raw2026;
|
||||
}
|
||||
get es2018() {
|
||||
var _a;
|
||||
return ((_a = this._set2018) !== null && _a !== void 0 ? _a : (this._set2018 = new Set(this._raw2018.split(" "))));
|
||||
}
|
||||
get es2019() {
|
||||
var _a;
|
||||
return ((_a = this._set2019) !== null && _a !== void 0 ? _a : (this._set2019 = new Set(this._raw2019.split(" "))));
|
||||
}
|
||||
get es2020() {
|
||||
var _a;
|
||||
return ((_a = this._set2020) !== null && _a !== void 0 ? _a : (this._set2020 = new Set(this._raw2020.split(" "))));
|
||||
}
|
||||
get es2021() {
|
||||
var _a;
|
||||
return ((_a = this._set2021) !== null && _a !== void 0 ? _a : (this._set2021 = new Set(this._raw2021.split(" "))));
|
||||
}
|
||||
get es2022() {
|
||||
var _a;
|
||||
return ((_a = this._set2022) !== null && _a !== void 0 ? _a : (this._set2022 = new Set(this._raw2022.split(" "))));
|
||||
}
|
||||
get es2023() {
|
||||
var _a;
|
||||
return ((_a = this._set2023) !== null && _a !== void 0 ? _a : (this._set2023 = new Set(this._raw2023.split(" "))));
|
||||
}
|
||||
get es2024() {
|
||||
var _a;
|
||||
return ((_a = this._set2024) !== null && _a !== void 0 ? _a : (this._set2024 = new Set(this._raw2024.split(" "))));
|
||||
}
|
||||
get es2025() {
|
||||
var _a;
|
||||
return ((_a = this._set2025) !== null && _a !== void 0 ? _a : (this._set2025 = new Set(this._raw2025.split(" "))));
|
||||
}
|
||||
get es2026() {
|
||||
var _a;
|
||||
return ((_a = this._set2026) !== null && _a !== void 0 ? _a : (this._set2026 = new Set(this._raw2026.split(" "))));
|
||||
}
|
||||
}
|
||||
const gcNameSet = new Set(["General_Category", "gc"]);
|
||||
const scNameSet = new Set(["Script", "Script_Extensions", "sc", "scx"]);
|
||||
const gcValueSets = new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "", "", "", "", "", "");
|
||||
const scValueSets = new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi", "Cpmn Cypro_Minoan Old_Uyghur Ougr Tangsa Tnsa Toto Vith Vithkuqi", "Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz", "", "", "");
|
||||
const binPropertySets = new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict", "", "", "", "", "");
|
||||
const binPropertyOfStringsSets = new DataSet("", "", "", "", "", "", "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji RGI_Emoji_Flag_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence", "", "");
|
||||
function isValidUnicodeProperty(version, name, value) {
|
||||
if (gcNameSet.has(name)) {
|
||||
return version >= 2018 && gcValueSets.es2018.has(value);
|
||||
}
|
||||
if (scNameSet.has(name)) {
|
||||
return ((version >= 2018 && scValueSets.es2018.has(value)) ||
|
||||
(version >= 2019 && scValueSets.es2019.has(value)) ||
|
||||
(version >= 2020 && scValueSets.es2020.has(value)) ||
|
||||
(version >= 2021 && scValueSets.es2021.has(value)) ||
|
||||
(version >= 2022 && scValueSets.es2022.has(value)) ||
|
||||
(version >= 2023 && scValueSets.es2023.has(value)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isValidLoneUnicodeProperty(version, value) {
|
||||
return ((version >= 2018 && binPropertySets.es2018.has(value)) ||
|
||||
(version >= 2019 && binPropertySets.es2019.has(value)) ||
|
||||
(version >= 2021 && binPropertySets.es2021.has(value)));
|
||||
}
|
||||
function isValidLoneUnicodePropertyOfString(version, value) {
|
||||
return version >= 2024 && binPropertyOfStringsSets.es2024.has(value);
|
||||
}
|
||||
|
||||
const BACKSPACE = 0x08;
|
||||
const CHARACTER_TABULATION = 0x09;
|
||||
const LINE_FEED = 0x0a;
|
||||
const LINE_TABULATION = 0x0b;
|
||||
const FORM_FEED = 0x0c;
|
||||
const CARRIAGE_RETURN = 0x0d;
|
||||
const EXCLAMATION_MARK = 0x21;
|
||||
const NUMBER_SIGN = 0x23;
|
||||
const DOLLAR_SIGN = 0x24;
|
||||
const PERCENT_SIGN = 0x25;
|
||||
const AMPERSAND = 0x26;
|
||||
const LEFT_PARENTHESIS = 0x28;
|
||||
const RIGHT_PARENTHESIS = 0x29;
|
||||
const ASTERISK = 0x2a;
|
||||
const PLUS_SIGN = 0x2b;
|
||||
const COMMA = 0x2c;
|
||||
const HYPHEN_MINUS = 0x2d;
|
||||
const FULL_STOP = 0x2e;
|
||||
const SOLIDUS = 0x2f;
|
||||
const DIGIT_ZERO = 0x30;
|
||||
const DIGIT_ONE = 0x31;
|
||||
const DIGIT_SEVEN = 0x37;
|
||||
const DIGIT_NINE = 0x39;
|
||||
const COLON = 0x3a;
|
||||
const SEMICOLON = 0x3b;
|
||||
const LESS_THAN_SIGN = 0x3c;
|
||||
const EQUALS_SIGN = 0x3d;
|
||||
const GREATER_THAN_SIGN = 0x3e;
|
||||
const QUESTION_MARK = 0x3f;
|
||||
const COMMERCIAL_AT = 0x40;
|
||||
const LATIN_CAPITAL_LETTER_A = 0x41;
|
||||
const LATIN_CAPITAL_LETTER_B = 0x42;
|
||||
const LATIN_CAPITAL_LETTER_D = 0x44;
|
||||
const LATIN_CAPITAL_LETTER_F = 0x46;
|
||||
const LATIN_CAPITAL_LETTER_P = 0x50;
|
||||
const LATIN_CAPITAL_LETTER_S = 0x53;
|
||||
const LATIN_CAPITAL_LETTER_W = 0x57;
|
||||
const LATIN_CAPITAL_LETTER_Z = 0x5a;
|
||||
const LOW_LINE = 0x5f;
|
||||
const LATIN_SMALL_LETTER_A = 0x61;
|
||||
const LATIN_SMALL_LETTER_B = 0x62;
|
||||
const LATIN_SMALL_LETTER_C = 0x63;
|
||||
const LATIN_SMALL_LETTER_D = 0x64;
|
||||
const LATIN_SMALL_LETTER_F = 0x66;
|
||||
const LATIN_SMALL_LETTER_G = 0x67;
|
||||
const LATIN_SMALL_LETTER_I = 0x69;
|
||||
const LATIN_SMALL_LETTER_K = 0x6b;
|
||||
const LATIN_SMALL_LETTER_M = 0x6d;
|
||||
const LATIN_SMALL_LETTER_N = 0x6e;
|
||||
const LATIN_SMALL_LETTER_P = 0x70;
|
||||
const LATIN_SMALL_LETTER_Q = 0x71;
|
||||
const LATIN_SMALL_LETTER_R = 0x72;
|
||||
const LATIN_SMALL_LETTER_S = 0x73;
|
||||
const LATIN_SMALL_LETTER_T = 0x74;
|
||||
const LATIN_SMALL_LETTER_U = 0x75;
|
||||
const LATIN_SMALL_LETTER_V = 0x76;
|
||||
const LATIN_SMALL_LETTER_W = 0x77;
|
||||
const LATIN_SMALL_LETTER_X = 0x78;
|
||||
const LATIN_SMALL_LETTER_Y = 0x79;
|
||||
const LATIN_SMALL_LETTER_Z = 0x7a;
|
||||
const LEFT_SQUARE_BRACKET = 0x5b;
|
||||
const REVERSE_SOLIDUS = 0x5c;
|
||||
const RIGHT_SQUARE_BRACKET = 0x5d;
|
||||
const CIRCUMFLEX_ACCENT = 0x5e;
|
||||
const GRAVE_ACCENT = 0x60;
|
||||
const LEFT_CURLY_BRACKET = 0x7b;
|
||||
const VERTICAL_LINE = 0x7c;
|
||||
const RIGHT_CURLY_BRACKET = 0x7d;
|
||||
const TILDE = 0x7e;
|
||||
const ZERO_WIDTH_NON_JOINER = 0x200c;
|
||||
const ZERO_WIDTH_JOINER = 0x200d;
|
||||
const LINE_SEPARATOR = 0x2028;
|
||||
const PARAGRAPH_SEPARATOR = 0x2029;
|
||||
const MIN_CODE_POINT = 0x00;
|
||||
const MAX_CODE_POINT = 0x10ffff;
|
||||
function isLatinLetter(code) {
|
||||
return ((code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_Z) ||
|
||||
(code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_Z));
|
||||
}
|
||||
function isDecimalDigit(code) {
|
||||
return code >= DIGIT_ZERO && code <= DIGIT_NINE;
|
||||
}
|
||||
function isOctalDigit(code) {
|
||||
return code >= DIGIT_ZERO && code <= DIGIT_SEVEN;
|
||||
}
|
||||
function isHexDigit(code) {
|
||||
return ((code >= DIGIT_ZERO && code <= DIGIT_NINE) ||
|
||||
(code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) ||
|
||||
(code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F));
|
||||
}
|
||||
function isLineTerminator(code) {
|
||||
return (code === LINE_FEED ||
|
||||
code === CARRIAGE_RETURN ||
|
||||
code === LINE_SEPARATOR ||
|
||||
code === PARAGRAPH_SEPARATOR);
|
||||
}
|
||||
function isValidUnicode(code) {
|
||||
return code >= MIN_CODE_POINT && code <= MAX_CODE_POINT;
|
||||
}
|
||||
function digitToInt(code) {
|
||||
if (code >= LATIN_SMALL_LETTER_A && code <= LATIN_SMALL_LETTER_F) {
|
||||
return code - LATIN_SMALL_LETTER_A + 10;
|
||||
}
|
||||
if (code >= LATIN_CAPITAL_LETTER_A && code <= LATIN_CAPITAL_LETTER_F) {
|
||||
return code - LATIN_CAPITAL_LETTER_A + 10;
|
||||
}
|
||||
return code - DIGIT_ZERO;
|
||||
}
|
||||
function isLeadSurrogate(code) {
|
||||
return code >= 0xd800 && code <= 0xdbff;
|
||||
}
|
||||
function isTrailSurrogate(code) {
|
||||
return code >= 0xdc00 && code <= 0xdfff;
|
||||
}
|
||||
function combineSurrogatePair(lead, trail) {
|
||||
return (lead - 0xd800) * 0x400 + (trail - 0xdc00) + 0x10000;
|
||||
}
|
||||
|
||||
class GroupSpecifiersAsES2018 {
|
||||
constructor() {
|
||||
this.groupName = new Set();
|
||||
}
|
||||
clear() {
|
||||
this.groupName.clear();
|
||||
}
|
||||
isEmpty() {
|
||||
return !this.groupName.size;
|
||||
}
|
||||
hasInPattern(name) {
|
||||
return this.groupName.has(name);
|
||||
}
|
||||
hasInScope(name) {
|
||||
return this.hasInPattern(name);
|
||||
}
|
||||
addToScope(name) {
|
||||
this.groupName.add(name);
|
||||
}
|
||||
enterDisjunction() {
|
||||
}
|
||||
enterAlternative() {
|
||||
}
|
||||
leaveDisjunction() {
|
||||
}
|
||||
}
|
||||
class BranchID {
|
||||
constructor(parent, base) {
|
||||
this.parent = parent;
|
||||
this.base = base !== null && base !== void 0 ? base : this;
|
||||
}
|
||||
separatedFrom(other) {
|
||||
var _a, _b;
|
||||
if (this.base === other.base && this !== other) {
|
||||
return true;
|
||||
}
|
||||
if (other.parent && this.separatedFrom(other.parent)) {
|
||||
return true;
|
||||
}
|
||||
return (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.separatedFrom(other)) !== null && _b !== void 0 ? _b : false;
|
||||
}
|
||||
child() {
|
||||
return new BranchID(this, null);
|
||||
}
|
||||
sibling() {
|
||||
return new BranchID(this.parent, this.base);
|
||||
}
|
||||
}
|
||||
class GroupSpecifiersAsES2025 {
|
||||
constructor() {
|
||||
this.branchID = new BranchID(null, null);
|
||||
this.groupNames = new Map();
|
||||
}
|
||||
clear() {
|
||||
this.branchID = new BranchID(null, null);
|
||||
this.groupNames.clear();
|
||||
}
|
||||
isEmpty() {
|
||||
return !this.groupNames.size;
|
||||
}
|
||||
enterDisjunction() {
|
||||
this.branchID = this.branchID.child();
|
||||
}
|
||||
enterAlternative(index) {
|
||||
if (index === 0) {
|
||||
return;
|
||||
}
|
||||
this.branchID = this.branchID.sibling();
|
||||
}
|
||||
leaveDisjunction() {
|
||||
this.branchID = this.branchID.parent;
|
||||
}
|
||||
hasInPattern(name) {
|
||||
return this.groupNames.has(name);
|
||||
}
|
||||
hasInScope(name) {
|
||||
const branches = this.groupNames.get(name);
|
||||
if (!branches) {
|
||||
return false;
|
||||
}
|
||||
for (const branch of branches) {
|
||||
if (!branch.separatedFrom(this.branchID)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
addToScope(name) {
|
||||
const branches = this.groupNames.get(name);
|
||||
if (branches) {
|
||||
branches.push(this.branchID);
|
||||
return;
|
||||
}
|
||||
this.groupNames.set(name, [this.branchID]);
|
||||
}
|
||||
}
|
||||
|
||||
const legacyImpl = {
|
||||
at(s, end, i) {
|
||||
return i < end ? s.charCodeAt(i) : -1;
|
||||
},
|
||||
width(c) {
|
||||
return 1;
|
||||
},
|
||||
};
|
||||
const unicodeImpl = {
|
||||
at(s, end, i) {
|
||||
return i < end ? s.codePointAt(i) : -1;
|
||||
},
|
||||
width(c) {
|
||||
return c > 0xffff ? 2 : 1;
|
||||
},
|
||||
};
|
||||
class Reader {
|
||||
constructor() {
|
||||
this._impl = legacyImpl;
|
||||
this._s = "";
|
||||
this._i = 0;
|
||||
this._end = 0;
|
||||
this._cp1 = -1;
|
||||
this._w1 = 1;
|
||||
this._cp2 = -1;
|
||||
this._w2 = 1;
|
||||
this._cp3 = -1;
|
||||
this._w3 = 1;
|
||||
this._cp4 = -1;
|
||||
}
|
||||
get source() {
|
||||
return this._s;
|
||||
}
|
||||
get index() {
|
||||
return this._i;
|
||||
}
|
||||
get currentCodePoint() {
|
||||
return this._cp1;
|
||||
}
|
||||
get nextCodePoint() {
|
||||
return this._cp2;
|
||||
}
|
||||
get nextCodePoint2() {
|
||||
return this._cp3;
|
||||
}
|
||||
get nextCodePoint3() {
|
||||
return this._cp4;
|
||||
}
|
||||
reset(source, start, end, uFlag) {
|
||||
this._impl = uFlag ? unicodeImpl : legacyImpl;
|
||||
this._s = source;
|
||||
this._end = end;
|
||||
this.rewind(start);
|
||||
}
|
||||
rewind(index) {
|
||||
const impl = this._impl;
|
||||
this._i = index;
|
||||
this._cp1 = impl.at(this._s, this._end, index);
|
||||
this._w1 = impl.width(this._cp1);
|
||||
this._cp2 = impl.at(this._s, this._end, index + this._w1);
|
||||
this._w2 = impl.width(this._cp2);
|
||||
this._cp3 = impl.at(this._s, this._end, index + this._w1 + this._w2);
|
||||
this._w3 = impl.width(this._cp3);
|
||||
this._cp4 = impl.at(this._s, this._end, index + this._w1 + this._w2 + this._w3);
|
||||
}
|
||||
advance() {
|
||||
if (this._cp1 !== -1) {
|
||||
const impl = this._impl;
|
||||
this._i += this._w1;
|
||||
this._cp1 = this._cp2;
|
||||
this._w1 = this._w2;
|
||||
this._cp2 = this._cp3;
|
||||
this._w2 = impl.width(this._cp2);
|
||||
this._cp3 = this._cp4;
|
||||
this._w3 = impl.width(this._cp3);
|
||||
this._cp4 = impl.at(this._s, this._end, this._i + this._w1 + this._w2 + this._w3);
|
||||
}
|
||||
}
|
||||
eat(cp) {
|
||||
if (this._cp1 === cp) {
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eat2(cp1, cp2) {
|
||||
if (this._cp1 === cp1 && this._cp2 === cp2) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eat3(cp1, cp2, cp3) {
|
||||
if (this._cp1 === cp1 && this._cp2 === cp2 && this._cp3 === cp3) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class RegExpSyntaxError extends SyntaxError {
|
||||
constructor(message, index) {
|
||||
super(message);
|
||||
this.index = index;
|
||||
}
|
||||
}
|
||||
function newRegExpSyntaxError(srcCtx, flags, index, message) {
|
||||
let source = "";
|
||||
if (srcCtx.kind === "literal") {
|
||||
const literal = srcCtx.source.slice(srcCtx.start, srcCtx.end);
|
||||
if (literal) {
|
||||
source = `: ${literal}`;
|
||||
}
|
||||
}
|
||||
else if (srcCtx.kind === "pattern") {
|
||||
const pattern = srcCtx.source.slice(srcCtx.start, srcCtx.end);
|
||||
const flagsText = `${flags.unicode ? "u" : ""}${flags.unicodeSets ? "v" : ""}`;
|
||||
source = `: /${pattern}/${flagsText}`;
|
||||
}
|
||||
return new RegExpSyntaxError(`Invalid regular expression${source}: ${message}`, index);
|
||||
}
|
||||
|
||||
const SYNTAX_CHARACTER = new Set([
|
||||
CIRCUMFLEX_ACCENT,
|
||||
DOLLAR_SIGN,
|
||||
REVERSE_SOLIDUS,
|
||||
FULL_STOP,
|
||||
ASTERISK,
|
||||
PLUS_SIGN,
|
||||
QUESTION_MARK,
|
||||
LEFT_PARENTHESIS,
|
||||
RIGHT_PARENTHESIS,
|
||||
LEFT_SQUARE_BRACKET,
|
||||
RIGHT_SQUARE_BRACKET,
|
||||
LEFT_CURLY_BRACKET,
|
||||
RIGHT_CURLY_BRACKET,
|
||||
VERTICAL_LINE,
|
||||
]);
|
||||
const CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER = new Set([
|
||||
AMPERSAND,
|
||||
EXCLAMATION_MARK,
|
||||
NUMBER_SIGN,
|
||||
DOLLAR_SIGN,
|
||||
PERCENT_SIGN,
|
||||
ASTERISK,
|
||||
PLUS_SIGN,
|
||||
COMMA,
|
||||
FULL_STOP,
|
||||
COLON,
|
||||
SEMICOLON,
|
||||
LESS_THAN_SIGN,
|
||||
EQUALS_SIGN,
|
||||
GREATER_THAN_SIGN,
|
||||
QUESTION_MARK,
|
||||
COMMERCIAL_AT,
|
||||
CIRCUMFLEX_ACCENT,
|
||||
GRAVE_ACCENT,
|
||||
TILDE,
|
||||
]);
|
||||
const CLASS_SET_SYNTAX_CHARACTER = new Set([
|
||||
LEFT_PARENTHESIS,
|
||||
RIGHT_PARENTHESIS,
|
||||
LEFT_SQUARE_BRACKET,
|
||||
RIGHT_SQUARE_BRACKET,
|
||||
LEFT_CURLY_BRACKET,
|
||||
RIGHT_CURLY_BRACKET,
|
||||
SOLIDUS,
|
||||
HYPHEN_MINUS,
|
||||
REVERSE_SOLIDUS,
|
||||
VERTICAL_LINE,
|
||||
]);
|
||||
const CLASS_SET_RESERVED_PUNCTUATOR = new Set([
|
||||
AMPERSAND,
|
||||
HYPHEN_MINUS,
|
||||
EXCLAMATION_MARK,
|
||||
NUMBER_SIGN,
|
||||
PERCENT_SIGN,
|
||||
COMMA,
|
||||
COLON,
|
||||
SEMICOLON,
|
||||
LESS_THAN_SIGN,
|
||||
EQUALS_SIGN,
|
||||
GREATER_THAN_SIGN,
|
||||
COMMERCIAL_AT,
|
||||
GRAVE_ACCENT,
|
||||
TILDE,
|
||||
]);
|
||||
const FLAG_PROP_TO_CODEPOINT = {
|
||||
global: LATIN_SMALL_LETTER_G,
|
||||
ignoreCase: LATIN_SMALL_LETTER_I,
|
||||
multiline: LATIN_SMALL_LETTER_M,
|
||||
unicode: LATIN_SMALL_LETTER_U,
|
||||
sticky: LATIN_SMALL_LETTER_Y,
|
||||
dotAll: LATIN_SMALL_LETTER_S,
|
||||
hasIndices: LATIN_SMALL_LETTER_D,
|
||||
unicodeSets: LATIN_SMALL_LETTER_V,
|
||||
};
|
||||
const FLAG_CODEPOINT_TO_PROP = Object.fromEntries(Object.entries(FLAG_PROP_TO_CODEPOINT).map(([k, v]) => [v, k]));
|
||||
function isSyntaxCharacter(cp) {
|
||||
return SYNTAX_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetReservedDoublePunctuatorCharacter(cp) {
|
||||
return CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetSyntaxCharacter(cp) {
|
||||
return CLASS_SET_SYNTAX_CHARACTER.has(cp);
|
||||
}
|
||||
function isClassSetReservedPunctuator(cp) {
|
||||
return CLASS_SET_RESERVED_PUNCTUATOR.has(cp);
|
||||
}
|
||||
function isIdentifierStartChar(cp) {
|
||||
return isIdStart(cp) || cp === DOLLAR_SIGN || cp === LOW_LINE;
|
||||
}
|
||||
function isIdentifierPartChar(cp) {
|
||||
return (isIdContinue(cp) ||
|
||||
cp === DOLLAR_SIGN ||
|
||||
cp === ZERO_WIDTH_NON_JOINER ||
|
||||
cp === ZERO_WIDTH_JOINER);
|
||||
}
|
||||
function isUnicodePropertyNameCharacter(cp) {
|
||||
return isLatinLetter(cp) || cp === LOW_LINE;
|
||||
}
|
||||
function isUnicodePropertyValueCharacter(cp) {
|
||||
return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp);
|
||||
}
|
||||
function isRegularExpressionModifier(ch) {
|
||||
return (ch === LATIN_SMALL_LETTER_I ||
|
||||
ch === LATIN_SMALL_LETTER_M ||
|
||||
ch === LATIN_SMALL_LETTER_S);
|
||||
}
|
||||
class RegExpValidator {
|
||||
constructor(options) {
|
||||
this._reader = new Reader();
|
||||
this._unicodeMode = false;
|
||||
this._unicodeSetsMode = false;
|
||||
this._nFlag = false;
|
||||
this._lastIntValue = 0;
|
||||
this._lastRange = {
|
||||
min: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
};
|
||||
this._lastStrValue = "";
|
||||
this._lastAssertionIsQuantifiable = false;
|
||||
this._numCapturingParens = 0;
|
||||
this._backreferenceNames = new Set();
|
||||
this._srcCtx = null;
|
||||
this._options = options !== null && options !== void 0 ? options : {};
|
||||
this._groupSpecifiers =
|
||||
this.ecmaVersion >= 2025
|
||||
? new GroupSpecifiersAsES2025()
|
||||
: new GroupSpecifiersAsES2018();
|
||||
}
|
||||
validateLiteral(source, start = 0, end = source.length) {
|
||||
this._srcCtx = { source, start, end, kind: "literal" };
|
||||
this._unicodeSetsMode = this._unicodeMode = this._nFlag = false;
|
||||
this.reset(source, start, end);
|
||||
this.onLiteralEnter(start);
|
||||
if (this.eat(SOLIDUS) && this.eatRegExpBody() && this.eat(SOLIDUS)) {
|
||||
const flagStart = this.index;
|
||||
const unicode = source.includes("u", flagStart);
|
||||
const unicodeSets = source.includes("v", flagStart);
|
||||
this.validateFlagsInternal(source, flagStart, end);
|
||||
this.validatePatternInternal(source, start + 1, flagStart - 1, {
|
||||
unicode,
|
||||
unicodeSets,
|
||||
});
|
||||
}
|
||||
else if (start >= end) {
|
||||
this.raise("Empty");
|
||||
}
|
||||
else {
|
||||
const c = String.fromCodePoint(this.currentCodePoint);
|
||||
this.raise(`Unexpected character '${c}'`);
|
||||
}
|
||||
this.onLiteralLeave(start, end);
|
||||
}
|
||||
validateFlags(source, start = 0, end = source.length) {
|
||||
this._srcCtx = { source, start, end, kind: "flags" };
|
||||
this.validateFlagsInternal(source, start, end);
|
||||
}
|
||||
validatePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
this._srcCtx = { source, start, end, kind: "pattern" };
|
||||
this.validatePatternInternal(source, start, end, uFlagOrFlags);
|
||||
}
|
||||
validatePatternInternal(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
const mode = this._parseFlagsOptionToMode(uFlagOrFlags, end);
|
||||
this._unicodeMode = mode.unicodeMode;
|
||||
this._nFlag = mode.nFlag;
|
||||
this._unicodeSetsMode = mode.unicodeSetsMode;
|
||||
this.reset(source, start, end);
|
||||
this.consumePattern();
|
||||
if (!this._nFlag &&
|
||||
this.ecmaVersion >= 2018 &&
|
||||
!this._groupSpecifiers.isEmpty()) {
|
||||
this._nFlag = true;
|
||||
this.rewind(start);
|
||||
this.consumePattern();
|
||||
}
|
||||
}
|
||||
validateFlagsInternal(source, start, end) {
|
||||
const flags = this.parseFlags(source, start, end);
|
||||
this.onRegExpFlags(start, end, flags);
|
||||
}
|
||||
_parseFlagsOptionToMode(uFlagOrFlags, sourceEnd) {
|
||||
let unicode = false;
|
||||
let unicodeSets = false;
|
||||
if (uFlagOrFlags && this.ecmaVersion >= 2015) {
|
||||
if (typeof uFlagOrFlags === "object") {
|
||||
unicode = Boolean(uFlagOrFlags.unicode);
|
||||
if (this.ecmaVersion >= 2024) {
|
||||
unicodeSets = Boolean(uFlagOrFlags.unicodeSets);
|
||||
}
|
||||
}
|
||||
else {
|
||||
unicode = uFlagOrFlags;
|
||||
}
|
||||
}
|
||||
if (unicode && unicodeSets) {
|
||||
this.raise("Invalid regular expression flags", {
|
||||
index: sourceEnd + 1,
|
||||
unicode,
|
||||
unicodeSets,
|
||||
});
|
||||
}
|
||||
const unicodeMode = unicode || unicodeSets;
|
||||
const nFlag = (unicode && this.ecmaVersion >= 2018) ||
|
||||
unicodeSets ||
|
||||
Boolean(this._options.strict && this.ecmaVersion >= 2023);
|
||||
const unicodeSetsMode = unicodeSets;
|
||||
return { unicodeMode, nFlag, unicodeSetsMode };
|
||||
}
|
||||
get strict() {
|
||||
return Boolean(this._options.strict) || this._unicodeMode;
|
||||
}
|
||||
get ecmaVersion() {
|
||||
var _a;
|
||||
return (_a = this._options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion;
|
||||
}
|
||||
onLiteralEnter(start) {
|
||||
if (this._options.onLiteralEnter) {
|
||||
this._options.onLiteralEnter(start);
|
||||
}
|
||||
}
|
||||
onLiteralLeave(start, end) {
|
||||
if (this._options.onLiteralLeave) {
|
||||
this._options.onLiteralLeave(start, end);
|
||||
}
|
||||
}
|
||||
onRegExpFlags(start, end, flags) {
|
||||
if (this._options.onRegExpFlags) {
|
||||
this._options.onRegExpFlags(start, end, flags);
|
||||
}
|
||||
if (this._options.onFlags) {
|
||||
this._options.onFlags(start, end, flags.global, flags.ignoreCase, flags.multiline, flags.unicode, flags.sticky, flags.dotAll, flags.hasIndices);
|
||||
}
|
||||
}
|
||||
onPatternEnter(start) {
|
||||
if (this._options.onPatternEnter) {
|
||||
this._options.onPatternEnter(start);
|
||||
}
|
||||
}
|
||||
onPatternLeave(start, end) {
|
||||
if (this._options.onPatternLeave) {
|
||||
this._options.onPatternLeave(start, end);
|
||||
}
|
||||
}
|
||||
onDisjunctionEnter(start) {
|
||||
if (this._options.onDisjunctionEnter) {
|
||||
this._options.onDisjunctionEnter(start);
|
||||
}
|
||||
}
|
||||
onDisjunctionLeave(start, end) {
|
||||
if (this._options.onDisjunctionLeave) {
|
||||
this._options.onDisjunctionLeave(start, end);
|
||||
}
|
||||
}
|
||||
onAlternativeEnter(start, index) {
|
||||
if (this._options.onAlternativeEnter) {
|
||||
this._options.onAlternativeEnter(start, index);
|
||||
}
|
||||
}
|
||||
onAlternativeLeave(start, end, index) {
|
||||
if (this._options.onAlternativeLeave) {
|
||||
this._options.onAlternativeLeave(start, end, index);
|
||||
}
|
||||
}
|
||||
onGroupEnter(start) {
|
||||
if (this._options.onGroupEnter) {
|
||||
this._options.onGroupEnter(start);
|
||||
}
|
||||
}
|
||||
onGroupLeave(start, end) {
|
||||
if (this._options.onGroupLeave) {
|
||||
this._options.onGroupLeave(start, end);
|
||||
}
|
||||
}
|
||||
onModifiersEnter(start) {
|
||||
if (this._options.onModifiersEnter) {
|
||||
this._options.onModifiersEnter(start);
|
||||
}
|
||||
}
|
||||
onModifiersLeave(start, end) {
|
||||
if (this._options.onModifiersLeave) {
|
||||
this._options.onModifiersLeave(start, end);
|
||||
}
|
||||
}
|
||||
onAddModifiers(start, end, flags) {
|
||||
if (this._options.onAddModifiers) {
|
||||
this._options.onAddModifiers(start, end, flags);
|
||||
}
|
||||
}
|
||||
onRemoveModifiers(start, end, flags) {
|
||||
if (this._options.onRemoveModifiers) {
|
||||
this._options.onRemoveModifiers(start, end, flags);
|
||||
}
|
||||
}
|
||||
onCapturingGroupEnter(start, name) {
|
||||
if (this._options.onCapturingGroupEnter) {
|
||||
this._options.onCapturingGroupEnter(start, name);
|
||||
}
|
||||
}
|
||||
onCapturingGroupLeave(start, end, name) {
|
||||
if (this._options.onCapturingGroupLeave) {
|
||||
this._options.onCapturingGroupLeave(start, end, name);
|
||||
}
|
||||
}
|
||||
onQuantifier(start, end, min, max, greedy) {
|
||||
if (this._options.onQuantifier) {
|
||||
this._options.onQuantifier(start, end, min, max, greedy);
|
||||
}
|
||||
}
|
||||
onLookaroundAssertionEnter(start, kind, negate) {
|
||||
if (this._options.onLookaroundAssertionEnter) {
|
||||
this._options.onLookaroundAssertionEnter(start, kind, negate);
|
||||
}
|
||||
}
|
||||
onLookaroundAssertionLeave(start, end, kind, negate) {
|
||||
if (this._options.onLookaroundAssertionLeave) {
|
||||
this._options.onLookaroundAssertionLeave(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onEdgeAssertion(start, end, kind) {
|
||||
if (this._options.onEdgeAssertion) {
|
||||
this._options.onEdgeAssertion(start, end, kind);
|
||||
}
|
||||
}
|
||||
onWordBoundaryAssertion(start, end, kind, negate) {
|
||||
if (this._options.onWordBoundaryAssertion) {
|
||||
this._options.onWordBoundaryAssertion(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onAnyCharacterSet(start, end, kind) {
|
||||
if (this._options.onAnyCharacterSet) {
|
||||
this._options.onAnyCharacterSet(start, end, kind);
|
||||
}
|
||||
}
|
||||
onEscapeCharacterSet(start, end, kind, negate) {
|
||||
if (this._options.onEscapeCharacterSet) {
|
||||
this._options.onEscapeCharacterSet(start, end, kind, negate);
|
||||
}
|
||||
}
|
||||
onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) {
|
||||
if (this._options.onUnicodePropertyCharacterSet) {
|
||||
this._options.onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings);
|
||||
}
|
||||
}
|
||||
onCharacter(start, end, value) {
|
||||
if (this._options.onCharacter) {
|
||||
this._options.onCharacter(start, end, value);
|
||||
}
|
||||
}
|
||||
onBackreference(start, end, ref) {
|
||||
if (this._options.onBackreference) {
|
||||
this._options.onBackreference(start, end, ref);
|
||||
}
|
||||
}
|
||||
onCharacterClassEnter(start, negate, unicodeSets) {
|
||||
if (this._options.onCharacterClassEnter) {
|
||||
this._options.onCharacterClassEnter(start, negate, unicodeSets);
|
||||
}
|
||||
}
|
||||
onCharacterClassLeave(start, end, negate) {
|
||||
if (this._options.onCharacterClassLeave) {
|
||||
this._options.onCharacterClassLeave(start, end, negate);
|
||||
}
|
||||
}
|
||||
onCharacterClassRange(start, end, min, max) {
|
||||
if (this._options.onCharacterClassRange) {
|
||||
this._options.onCharacterClassRange(start, end, min, max);
|
||||
}
|
||||
}
|
||||
onClassIntersection(start, end) {
|
||||
if (this._options.onClassIntersection) {
|
||||
this._options.onClassIntersection(start, end);
|
||||
}
|
||||
}
|
||||
onClassSubtraction(start, end) {
|
||||
if (this._options.onClassSubtraction) {
|
||||
this._options.onClassSubtraction(start, end);
|
||||
}
|
||||
}
|
||||
onClassStringDisjunctionEnter(start) {
|
||||
if (this._options.onClassStringDisjunctionEnter) {
|
||||
this._options.onClassStringDisjunctionEnter(start);
|
||||
}
|
||||
}
|
||||
onClassStringDisjunctionLeave(start, end) {
|
||||
if (this._options.onClassStringDisjunctionLeave) {
|
||||
this._options.onClassStringDisjunctionLeave(start, end);
|
||||
}
|
||||
}
|
||||
onStringAlternativeEnter(start, index) {
|
||||
if (this._options.onStringAlternativeEnter) {
|
||||
this._options.onStringAlternativeEnter(start, index);
|
||||
}
|
||||
}
|
||||
onStringAlternativeLeave(start, end, index) {
|
||||
if (this._options.onStringAlternativeLeave) {
|
||||
this._options.onStringAlternativeLeave(start, end, index);
|
||||
}
|
||||
}
|
||||
get index() {
|
||||
return this._reader.index;
|
||||
}
|
||||
get currentCodePoint() {
|
||||
return this._reader.currentCodePoint;
|
||||
}
|
||||
get nextCodePoint() {
|
||||
return this._reader.nextCodePoint;
|
||||
}
|
||||
get nextCodePoint2() {
|
||||
return this._reader.nextCodePoint2;
|
||||
}
|
||||
get nextCodePoint3() {
|
||||
return this._reader.nextCodePoint3;
|
||||
}
|
||||
reset(source, start, end) {
|
||||
this._reader.reset(source, start, end, this._unicodeMode);
|
||||
}
|
||||
rewind(index) {
|
||||
this._reader.rewind(index);
|
||||
}
|
||||
advance() {
|
||||
this._reader.advance();
|
||||
}
|
||||
eat(cp) {
|
||||
return this._reader.eat(cp);
|
||||
}
|
||||
eat2(cp1, cp2) {
|
||||
return this._reader.eat2(cp1, cp2);
|
||||
}
|
||||
eat3(cp1, cp2, cp3) {
|
||||
return this._reader.eat3(cp1, cp2, cp3);
|
||||
}
|
||||
raise(message, context) {
|
||||
var _a, _b, _c;
|
||||
throw newRegExpSyntaxError(this._srcCtx, {
|
||||
unicode: (_a = context === null || context === void 0 ? void 0 : context.unicode) !== null && _a !== void 0 ? _a : (this._unicodeMode && !this._unicodeSetsMode),
|
||||
unicodeSets: (_b = context === null || context === void 0 ? void 0 : context.unicodeSets) !== null && _b !== void 0 ? _b : this._unicodeSetsMode,
|
||||
}, (_c = context === null || context === void 0 ? void 0 : context.index) !== null && _c !== void 0 ? _c : this.index, message);
|
||||
}
|
||||
eatRegExpBody() {
|
||||
const start = this.index;
|
||||
let inClass = false;
|
||||
let escaped = false;
|
||||
for (;;) {
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp === -1 || isLineTerminator(cp)) {
|
||||
const kind = inClass ? "character class" : "regular expression";
|
||||
this.raise(`Unterminated ${kind}`);
|
||||
}
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
}
|
||||
else if (cp === REVERSE_SOLIDUS) {
|
||||
escaped = true;
|
||||
}
|
||||
else if (cp === LEFT_SQUARE_BRACKET) {
|
||||
inClass = true;
|
||||
}
|
||||
else if (cp === RIGHT_SQUARE_BRACKET) {
|
||||
inClass = false;
|
||||
}
|
||||
else if ((cp === SOLIDUS && !inClass) ||
|
||||
(cp === ASTERISK && this.index === start)) {
|
||||
break;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
consumePattern() {
|
||||
const start = this.index;
|
||||
this._numCapturingParens = this.countCapturingParens();
|
||||
this._groupSpecifiers.clear();
|
||||
this._backreferenceNames.clear();
|
||||
this.onPatternEnter(start);
|
||||
this.consumeDisjunction();
|
||||
const cp = this.currentCodePoint;
|
||||
if (this.currentCodePoint !== -1) {
|
||||
if (cp === RIGHT_PARENTHESIS) {
|
||||
this.raise("Unmatched ')'");
|
||||
}
|
||||
if (cp === REVERSE_SOLIDUS) {
|
||||
this.raise("\\ at end of pattern");
|
||||
}
|
||||
if (cp === RIGHT_SQUARE_BRACKET || cp === RIGHT_CURLY_BRACKET) {
|
||||
this.raise("Lone quantifier brackets");
|
||||
}
|
||||
const c = String.fromCodePoint(cp);
|
||||
this.raise(`Unexpected character '${c}'`);
|
||||
}
|
||||
for (const name of this._backreferenceNames) {
|
||||
if (!this._groupSpecifiers.hasInPattern(name)) {
|
||||
this.raise("Invalid named capture referenced");
|
||||
}
|
||||
}
|
||||
this.onPatternLeave(start, this.index);
|
||||
}
|
||||
countCapturingParens() {
|
||||
const start = this.index;
|
||||
let inClass = false;
|
||||
let escaped = false;
|
||||
let count = 0;
|
||||
let cp = 0;
|
||||
while ((cp = this.currentCodePoint) !== -1) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
}
|
||||
else if (cp === REVERSE_SOLIDUS) {
|
||||
escaped = true;
|
||||
}
|
||||
else if (cp === LEFT_SQUARE_BRACKET) {
|
||||
inClass = true;
|
||||
}
|
||||
else if (cp === RIGHT_SQUARE_BRACKET) {
|
||||
inClass = false;
|
||||
}
|
||||
else if (cp === LEFT_PARENTHESIS &&
|
||||
!inClass &&
|
||||
(this.nextCodePoint !== QUESTION_MARK ||
|
||||
(this.nextCodePoint2 === LESS_THAN_SIGN &&
|
||||
this.nextCodePoint3 !== EQUALS_SIGN &&
|
||||
this.nextCodePoint3 !== EXCLAMATION_MARK))) {
|
||||
count += 1;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
this.rewind(start);
|
||||
return count;
|
||||
}
|
||||
consumeDisjunction() {
|
||||
const start = this.index;
|
||||
let i = 0;
|
||||
this._groupSpecifiers.enterDisjunction();
|
||||
this.onDisjunctionEnter(start);
|
||||
do {
|
||||
this.consumeAlternative(i++);
|
||||
} while (this.eat(VERTICAL_LINE));
|
||||
if (this.consumeQuantifier(true)) {
|
||||
this.raise("Nothing to repeat");
|
||||
}
|
||||
if (this.eat(LEFT_CURLY_BRACKET)) {
|
||||
this.raise("Lone quantifier brackets");
|
||||
}
|
||||
this.onDisjunctionLeave(start, this.index);
|
||||
this._groupSpecifiers.leaveDisjunction();
|
||||
}
|
||||
consumeAlternative(i) {
|
||||
const start = this.index;
|
||||
this._groupSpecifiers.enterAlternative(i);
|
||||
this.onAlternativeEnter(start, i);
|
||||
while (this.currentCodePoint !== -1 && this.consumeTerm()) {
|
||||
}
|
||||
this.onAlternativeLeave(start, this.index, i);
|
||||
}
|
||||
consumeTerm() {
|
||||
if (this._unicodeMode || this.strict) {
|
||||
return (this.consumeAssertion() ||
|
||||
(this.consumeAtom() && this.consumeOptionalQuantifier()));
|
||||
}
|
||||
return ((this.consumeAssertion() &&
|
||||
(!this._lastAssertionIsQuantifiable ||
|
||||
this.consumeOptionalQuantifier())) ||
|
||||
(this.consumeExtendedAtom() && this.consumeOptionalQuantifier()));
|
||||
}
|
||||
consumeOptionalQuantifier() {
|
||||
this.consumeQuantifier();
|
||||
return true;
|
||||
}
|
||||
consumeAssertion() {
|
||||
const start = this.index;
|
||||
this._lastAssertionIsQuantifiable = false;
|
||||
if (this.eat(CIRCUMFLEX_ACCENT)) {
|
||||
this.onEdgeAssertion(start, this.index, "start");
|
||||
return true;
|
||||
}
|
||||
if (this.eat(DOLLAR_SIGN)) {
|
||||
this.onEdgeAssertion(start, this.index, "end");
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(REVERSE_SOLIDUS, LATIN_CAPITAL_LETTER_B)) {
|
||||
this.onWordBoundaryAssertion(start, this.index, "word", true);
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_B)) {
|
||||
this.onWordBoundaryAssertion(start, this.index, "word", false);
|
||||
return true;
|
||||
}
|
||||
if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) {
|
||||
const lookbehind = this.ecmaVersion >= 2018 && this.eat(LESS_THAN_SIGN);
|
||||
let negate = false;
|
||||
if (this.eat(EQUALS_SIGN) ||
|
||||
(negate = this.eat(EXCLAMATION_MARK))) {
|
||||
const kind = lookbehind ? "lookbehind" : "lookahead";
|
||||
this.onLookaroundAssertionEnter(start, kind, negate);
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this._lastAssertionIsQuantifiable = !lookbehind && !this.strict;
|
||||
this.onLookaroundAssertionLeave(start, this.index, kind, negate);
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeQuantifier(noConsume = false) {
|
||||
const start = this.index;
|
||||
let min = 0;
|
||||
let max = 0;
|
||||
let greedy = false;
|
||||
if (this.eat(ASTERISK)) {
|
||||
min = 0;
|
||||
max = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
else if (this.eat(PLUS_SIGN)) {
|
||||
min = 1;
|
||||
max = Number.POSITIVE_INFINITY;
|
||||
}
|
||||
else if (this.eat(QUESTION_MARK)) {
|
||||
min = 0;
|
||||
max = 1;
|
||||
}
|
||||
else if (this.eatBracedQuantifier(noConsume)) {
|
||||
({ min, max } = this._lastRange);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
greedy = !this.eat(QUESTION_MARK);
|
||||
if (!noConsume) {
|
||||
this.onQuantifier(start, this.index, min, max, greedy);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
eatBracedQuantifier(noError) {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_CURLY_BRACKET)) {
|
||||
if (this.eatDecimalDigits()) {
|
||||
const min = this._lastIntValue;
|
||||
let max = min;
|
||||
if (this.eat(COMMA)) {
|
||||
max = this.eatDecimalDigits()
|
||||
? this._lastIntValue
|
||||
: Number.POSITIVE_INFINITY;
|
||||
}
|
||||
if (this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
if (!noError && max < min) {
|
||||
this.raise("numbers out of order in {} quantifier");
|
||||
}
|
||||
this._lastRange = { min, max };
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!noError && (this._unicodeMode || this.strict)) {
|
||||
this.raise("Incomplete quantifier");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeAtom() {
|
||||
return (this.consumePatternCharacter() ||
|
||||
this.consumeDot() ||
|
||||
this.consumeReverseSolidusAtomEscape() ||
|
||||
Boolean(this.consumeCharacterClass()) ||
|
||||
this.consumeCapturingGroup() ||
|
||||
this.consumeUncapturingGroup());
|
||||
}
|
||||
consumeDot() {
|
||||
if (this.eat(FULL_STOP)) {
|
||||
this.onAnyCharacterSet(this.index - 1, this.index, "any");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeReverseSolidusAtomEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeAtomEscape()) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeUncapturingGroup() {
|
||||
const start = this.index;
|
||||
if (this.eat2(LEFT_PARENTHESIS, QUESTION_MARK)) {
|
||||
this.onGroupEnter(start);
|
||||
if (this.ecmaVersion >= 2025) {
|
||||
this.consumeModifiers();
|
||||
}
|
||||
if (!this.eat(COLON)) {
|
||||
this.rewind(start + 1);
|
||||
this.raise("Invalid group");
|
||||
}
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this.onGroupLeave(start, this.index);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeModifiers() {
|
||||
const start = this.index;
|
||||
const hasAddModifiers = this.eatModifiers();
|
||||
const addModifiersEnd = this.index;
|
||||
const hasHyphen = this.eat(HYPHEN_MINUS);
|
||||
if (!hasAddModifiers && !hasHyphen) {
|
||||
return false;
|
||||
}
|
||||
this.onModifiersEnter(start);
|
||||
const addModifiers = this.parseModifiers(start, addModifiersEnd);
|
||||
this.onAddModifiers(start, addModifiersEnd, addModifiers);
|
||||
if (hasHyphen) {
|
||||
const modifiersStart = this.index;
|
||||
if (!this.eatModifiers() &&
|
||||
!hasAddModifiers &&
|
||||
this.currentCodePoint === COLON) {
|
||||
this.raise("Invalid empty flags");
|
||||
}
|
||||
const modifiers = this.parseModifiers(modifiersStart, this.index);
|
||||
for (const [flagName] of Object.entries(modifiers).filter(([, enable]) => enable)) {
|
||||
if (addModifiers[flagName]) {
|
||||
this.raise(`Duplicated flag '${String.fromCodePoint(FLAG_PROP_TO_CODEPOINT[flagName])}'`);
|
||||
}
|
||||
}
|
||||
this.onRemoveModifiers(modifiersStart, this.index, modifiers);
|
||||
}
|
||||
this.onModifiersLeave(start, this.index);
|
||||
return true;
|
||||
}
|
||||
consumeCapturingGroup() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_PARENTHESIS)) {
|
||||
let name = null;
|
||||
if (this.ecmaVersion >= 2018) {
|
||||
if (this.consumeGroupSpecifier()) {
|
||||
name = this._lastStrValue;
|
||||
}
|
||||
else if (this.currentCodePoint === QUESTION_MARK) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.currentCodePoint === QUESTION_MARK) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
this.onCapturingGroupEnter(start, name);
|
||||
this.consumeDisjunction();
|
||||
if (!this.eat(RIGHT_PARENTHESIS)) {
|
||||
this.raise("Unterminated group");
|
||||
}
|
||||
this.onCapturingGroupLeave(start, this.index, name);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeExtendedAtom() {
|
||||
return (this.consumeDot() ||
|
||||
this.consumeReverseSolidusAtomEscape() ||
|
||||
this.consumeReverseSolidusFollowedByC() ||
|
||||
Boolean(this.consumeCharacterClass()) ||
|
||||
this.consumeCapturingGroup() ||
|
||||
this.consumeUncapturingGroup() ||
|
||||
this.consumeInvalidBracedQuantifier() ||
|
||||
this.consumeExtendedPatternCharacter());
|
||||
}
|
||||
consumeReverseSolidusFollowedByC() {
|
||||
const start = this.index;
|
||||
if (this.currentCodePoint === REVERSE_SOLIDUS &&
|
||||
this.nextCodePoint === LATIN_SMALL_LETTER_C) {
|
||||
this._lastIntValue = this.currentCodePoint;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, REVERSE_SOLIDUS);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeInvalidBracedQuantifier() {
|
||||
if (this.eatBracedQuantifier(true)) {
|
||||
this.raise("Nothing to repeat");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumePatternCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 && !isSyntaxCharacter(cp)) {
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, cp);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeExtendedPatternCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 &&
|
||||
cp !== CIRCUMFLEX_ACCENT &&
|
||||
cp !== DOLLAR_SIGN &&
|
||||
cp !== REVERSE_SOLIDUS &&
|
||||
cp !== FULL_STOP &&
|
||||
cp !== ASTERISK &&
|
||||
cp !== PLUS_SIGN &&
|
||||
cp !== QUESTION_MARK &&
|
||||
cp !== LEFT_PARENTHESIS &&
|
||||
cp !== RIGHT_PARENTHESIS &&
|
||||
cp !== LEFT_SQUARE_BRACKET &&
|
||||
cp !== VERTICAL_LINE) {
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, cp);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeGroupSpecifier() {
|
||||
const start = this.index;
|
||||
if (this.eat(QUESTION_MARK)) {
|
||||
if (this.eatGroupName()) {
|
||||
if (!this._groupSpecifiers.hasInScope(this._lastStrValue)) {
|
||||
this._groupSpecifiers.addToScope(this._lastStrValue);
|
||||
return true;
|
||||
}
|
||||
this.raise("Duplicate capture group name");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeAtomEscape() {
|
||||
if (this.consumeBackreference() ||
|
||||
this.consumeCharacterClassEscape() ||
|
||||
this.consumeCharacterEscape() ||
|
||||
(this._nFlag && this.consumeKGroupName())) {
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeBackreference() {
|
||||
const start = this.index;
|
||||
if (this.eatDecimalEscape()) {
|
||||
const n = this._lastIntValue;
|
||||
if (n <= this._numCapturingParens) {
|
||||
this.onBackreference(start - 1, this.index, n);
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeCharacterClassEscape() {
|
||||
var _a;
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_D)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "digit", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_D)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "digit", true);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_S)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "space", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_S)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "space", true);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_W)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "word", false);
|
||||
return {};
|
||||
}
|
||||
if (this.eat(LATIN_CAPITAL_LETTER_W)) {
|
||||
this._lastIntValue = -1;
|
||||
this.onEscapeCharacterSet(start - 1, this.index, "word", true);
|
||||
return {};
|
||||
}
|
||||
let negate = false;
|
||||
if (this._unicodeMode &&
|
||||
this.ecmaVersion >= 2018 &&
|
||||
(this.eat(LATIN_SMALL_LETTER_P) ||
|
||||
(negate = this.eat(LATIN_CAPITAL_LETTER_P)))) {
|
||||
this._lastIntValue = -1;
|
||||
let result = null;
|
||||
if (this.eat(LEFT_CURLY_BRACKET) &&
|
||||
(result = this.eatUnicodePropertyValueExpression()) &&
|
||||
this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
if (negate && result.strings) {
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
this.onUnicodePropertyCharacterSet(start - 1, this.index, "property", result.key, result.value, negate, (_a = result.strings) !== null && _a !== void 0 ? _a : false);
|
||||
return { mayContainStrings: result.strings };
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeCharacterEscape() {
|
||||
const start = this.index;
|
||||
if (this.eatControlEscape() ||
|
||||
this.eatCControlLetter() ||
|
||||
this.eatZero() ||
|
||||
this.eatHexEscapeSequence() ||
|
||||
this.eatRegExpUnicodeEscapeSequence() ||
|
||||
(!this.strict &&
|
||||
!this._unicodeMode &&
|
||||
this.eatLegacyOctalEscapeSequence()) ||
|
||||
this.eatIdentityEscape()) {
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeKGroupName() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_K)) {
|
||||
if (this.eatGroupName()) {
|
||||
const groupName = this._lastStrValue;
|
||||
this._backreferenceNames.add(groupName);
|
||||
this.onBackreference(start - 1, this.index, groupName);
|
||||
return true;
|
||||
}
|
||||
this.raise("Invalid named reference");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeCharacterClass() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_SQUARE_BRACKET)) {
|
||||
const negate = this.eat(CIRCUMFLEX_ACCENT);
|
||||
this.onCharacterClassEnter(start, negate, this._unicodeSetsMode);
|
||||
const result = this.consumeClassContents();
|
||||
if (!this.eat(RIGHT_SQUARE_BRACKET)) {
|
||||
if (this.currentCodePoint === -1) {
|
||||
this.raise("Unterminated character class");
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (negate && result.mayContainStrings) {
|
||||
this.raise("Negated character class may contain strings");
|
||||
}
|
||||
this.onCharacterClassLeave(start, this.index, negate);
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassContents() {
|
||||
if (this._unicodeSetsMode) {
|
||||
if (this.currentCodePoint === RIGHT_SQUARE_BRACKET) {
|
||||
return {};
|
||||
}
|
||||
const result = this.consumeClassSetExpression();
|
||||
return result;
|
||||
}
|
||||
const strict = this.strict || this._unicodeMode;
|
||||
for (;;) {
|
||||
const rangeStart = this.index;
|
||||
if (!this.consumeClassAtom()) {
|
||||
break;
|
||||
}
|
||||
const min = this._lastIntValue;
|
||||
if (!this.eat(HYPHEN_MINUS)) {
|
||||
continue;
|
||||
}
|
||||
this.onCharacter(this.index - 1, this.index, HYPHEN_MINUS);
|
||||
if (!this.consumeClassAtom()) {
|
||||
break;
|
||||
}
|
||||
const max = this._lastIntValue;
|
||||
if (min === -1 || max === -1) {
|
||||
if (strict) {
|
||||
this.raise("Invalid character class");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (min > max) {
|
||||
this.raise("Range out of order in character class");
|
||||
}
|
||||
this.onCharacterClassRange(rangeStart, this.index, min, max);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
consumeClassAtom() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== -1 &&
|
||||
cp !== REVERSE_SOLIDUS &&
|
||||
cp !== RIGHT_SQUARE_BRACKET) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeClassEscape()) {
|
||||
return true;
|
||||
}
|
||||
if (!this.strict &&
|
||||
this.currentCodePoint === LATIN_SMALL_LETTER_C) {
|
||||
this._lastIntValue = REVERSE_SOLIDUS;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.strict || this._unicodeMode) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeClassEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_B)) {
|
||||
this._lastIntValue = BACKSPACE;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this._unicodeMode && this.eat(HYPHEN_MINUS)) {
|
||||
this._lastIntValue = HYPHEN_MINUS;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
let cp = 0;
|
||||
if (!this.strict &&
|
||||
!this._unicodeMode &&
|
||||
this.currentCodePoint === LATIN_SMALL_LETTER_C &&
|
||||
(isDecimalDigit((cp = this.nextCodePoint)) || cp === LOW_LINE)) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
this._lastIntValue = cp % 0x20;
|
||||
this.onCharacter(start - 1, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
return (Boolean(this.consumeCharacterClassEscape()) ||
|
||||
this.consumeCharacterEscape());
|
||||
}
|
||||
consumeClassSetExpression() {
|
||||
const start = this.index;
|
||||
let mayContainStrings = false;
|
||||
let result = null;
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
if (this.consumeClassSetRangeFromOperator(start)) {
|
||||
this.consumeClassUnionRight({});
|
||||
return {};
|
||||
}
|
||||
mayContainStrings = false;
|
||||
}
|
||||
else if ((result = this.consumeClassSetOperand())) {
|
||||
mayContainStrings = result.mayContainStrings;
|
||||
}
|
||||
else {
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp === REVERSE_SOLIDUS) {
|
||||
this.advance();
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
if (cp === this.nextCodePoint &&
|
||||
isClassSetReservedDoublePunctuatorCharacter(cp)) {
|
||||
this.raise("Invalid set operation in character class");
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (this.eat2(AMPERSAND, AMPERSAND)) {
|
||||
while (this.currentCodePoint !== AMPERSAND &&
|
||||
(result = this.consumeClassSetOperand())) {
|
||||
this.onClassIntersection(start, this.index);
|
||||
if (!result.mayContainStrings) {
|
||||
mayContainStrings = false;
|
||||
}
|
||||
if (this.eat2(AMPERSAND, AMPERSAND)) {
|
||||
continue;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) {
|
||||
while (this.consumeClassSetOperand()) {
|
||||
this.onClassSubtraction(start, this.index);
|
||||
if (this.eat2(HYPHEN_MINUS, HYPHEN_MINUS)) {
|
||||
continue;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Invalid character in character class");
|
||||
}
|
||||
return this.consumeClassUnionRight({ mayContainStrings });
|
||||
}
|
||||
consumeClassUnionRight(leftResult) {
|
||||
let mayContainStrings = leftResult.mayContainStrings;
|
||||
for (;;) {
|
||||
const start = this.index;
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
this.consumeClassSetRangeFromOperator(start);
|
||||
continue;
|
||||
}
|
||||
const result = this.consumeClassSetOperand();
|
||||
if (result) {
|
||||
if (result.mayContainStrings) {
|
||||
mayContainStrings = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return { mayContainStrings };
|
||||
}
|
||||
consumeClassSetRangeFromOperator(start) {
|
||||
const currentStart = this.index;
|
||||
const min = this._lastIntValue;
|
||||
if (this.eat(HYPHEN_MINUS)) {
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
const max = this._lastIntValue;
|
||||
if (min === -1 || max === -1) {
|
||||
this.raise("Invalid character class");
|
||||
}
|
||||
if (min > max) {
|
||||
this.raise("Range out of order in character class");
|
||||
}
|
||||
this.onCharacterClassRange(start, this.index, min, max);
|
||||
return true;
|
||||
}
|
||||
this.rewind(currentStart);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
consumeClassSetOperand() {
|
||||
let result = null;
|
||||
if ((result = this.consumeNestedClass())) {
|
||||
return result;
|
||||
}
|
||||
if ((result = this.consumeClassStringDisjunction())) {
|
||||
return result;
|
||||
}
|
||||
if (this.consumeClassSetCharacter()) {
|
||||
return {};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeNestedClass() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_SQUARE_BRACKET)) {
|
||||
const negate = this.eat(CIRCUMFLEX_ACCENT);
|
||||
this.onCharacterClassEnter(start, negate, true);
|
||||
const result = this.consumeClassContents();
|
||||
if (!this.eat(RIGHT_SQUARE_BRACKET)) {
|
||||
this.raise("Unterminated character class");
|
||||
}
|
||||
if (negate && result.mayContainStrings) {
|
||||
this.raise("Negated character class may contain strings");
|
||||
}
|
||||
this.onCharacterClassLeave(start, this.index, negate);
|
||||
return result;
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
const result = this.consumeCharacterClassEscape();
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassStringDisjunction() {
|
||||
const start = this.index;
|
||||
if (this.eat3(REVERSE_SOLIDUS, LATIN_SMALL_LETTER_Q, LEFT_CURLY_BRACKET)) {
|
||||
this.onClassStringDisjunctionEnter(start);
|
||||
let i = 0;
|
||||
let mayContainStrings = false;
|
||||
do {
|
||||
if (this.consumeClassString(i++).mayContainStrings) {
|
||||
mayContainStrings = true;
|
||||
}
|
||||
} while (this.eat(VERTICAL_LINE));
|
||||
if (this.eat(RIGHT_CURLY_BRACKET)) {
|
||||
this.onClassStringDisjunctionLeave(start, this.index);
|
||||
return { mayContainStrings };
|
||||
}
|
||||
this.raise("Unterminated class string disjunction");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
consumeClassString(i) {
|
||||
const start = this.index;
|
||||
let count = 0;
|
||||
this.onStringAlternativeEnter(start, i);
|
||||
while (this.currentCodePoint !== -1 &&
|
||||
this.consumeClassSetCharacter()) {
|
||||
count++;
|
||||
}
|
||||
this.onStringAlternativeLeave(start, this.index, i);
|
||||
return { mayContainStrings: count !== 1 };
|
||||
}
|
||||
consumeClassSetCharacter() {
|
||||
const start = this.index;
|
||||
const cp = this.currentCodePoint;
|
||||
if (cp !== this.nextCodePoint ||
|
||||
!isClassSetReservedDoublePunctuatorCharacter(cp)) {
|
||||
if (cp !== -1 && !isClassSetSyntaxCharacter(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (this.eat(REVERSE_SOLIDUS)) {
|
||||
if (this.consumeCharacterEscape()) {
|
||||
return true;
|
||||
}
|
||||
if (isClassSetReservedPunctuator(this.currentCodePoint)) {
|
||||
this._lastIntValue = this.currentCodePoint;
|
||||
this.advance();
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_B)) {
|
||||
this._lastIntValue = BACKSPACE;
|
||||
this.onCharacter(start, this.index, this._lastIntValue);
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatGroupName() {
|
||||
if (this.eat(LESS_THAN_SIGN)) {
|
||||
if (this.eatRegExpIdentifierName() && this.eat(GREATER_THAN_SIGN)) {
|
||||
return true;
|
||||
}
|
||||
this.raise("Invalid capture group name");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierName() {
|
||||
if (this.eatRegExpIdentifierStart()) {
|
||||
this._lastStrValue = String.fromCodePoint(this._lastIntValue);
|
||||
while (this.eatRegExpIdentifierPart()) {
|
||||
this._lastStrValue += String.fromCodePoint(this._lastIntValue);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierStart() {
|
||||
const start = this.index;
|
||||
const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020;
|
||||
let cp = this.currentCodePoint;
|
||||
this.advance();
|
||||
if (cp === REVERSE_SOLIDUS &&
|
||||
this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
|
||||
cp = this._lastIntValue;
|
||||
}
|
||||
else if (forceUFlag &&
|
||||
isLeadSurrogate(cp) &&
|
||||
isTrailSurrogate(this.currentCodePoint)) {
|
||||
cp = combineSurrogatePair(cp, this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
if (isIdentifierStartChar(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
return true;
|
||||
}
|
||||
if (this.index !== start) {
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpIdentifierPart() {
|
||||
const start = this.index;
|
||||
const forceUFlag = !this._unicodeMode && this.ecmaVersion >= 2020;
|
||||
let cp = this.currentCodePoint;
|
||||
this.advance();
|
||||
if (cp === REVERSE_SOLIDUS &&
|
||||
this.eatRegExpUnicodeEscapeSequence(forceUFlag)) {
|
||||
cp = this._lastIntValue;
|
||||
}
|
||||
else if (forceUFlag &&
|
||||
isLeadSurrogate(cp) &&
|
||||
isTrailSurrogate(this.currentCodePoint)) {
|
||||
cp = combineSurrogatePair(cp, this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
if (isIdentifierPartChar(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
return true;
|
||||
}
|
||||
if (this.index !== start) {
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatCControlLetter() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_C)) {
|
||||
if (this.eatControlLetter()) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatZero() {
|
||||
if (this.currentCodePoint === DIGIT_ZERO &&
|
||||
!isDecimalDigit(this.nextCodePoint)) {
|
||||
this._lastIntValue = 0;
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatControlEscape() {
|
||||
if (this.eat(LATIN_SMALL_LETTER_F)) {
|
||||
this._lastIntValue = FORM_FEED;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_N)) {
|
||||
this._lastIntValue = LINE_FEED;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_R)) {
|
||||
this._lastIntValue = CARRIAGE_RETURN;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_T)) {
|
||||
this._lastIntValue = CHARACTER_TABULATION;
|
||||
return true;
|
||||
}
|
||||
if (this.eat(LATIN_SMALL_LETTER_V)) {
|
||||
this._lastIntValue = LINE_TABULATION;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatControlLetter() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (isLatinLetter(cp)) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp % 0x20;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeEscapeSequence(forceUFlag = false) {
|
||||
const start = this.index;
|
||||
const uFlag = forceUFlag || this._unicodeMode;
|
||||
if (this.eat(LATIN_SMALL_LETTER_U)) {
|
||||
if ((uFlag && this.eatRegExpUnicodeSurrogatePairEscape()) ||
|
||||
this.eatFixedHexDigits(4) ||
|
||||
(uFlag && this.eatRegExpUnicodeCodePointEscape())) {
|
||||
return true;
|
||||
}
|
||||
if (this.strict || uFlag) {
|
||||
this.raise("Invalid unicode escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeSurrogatePairEscape() {
|
||||
const start = this.index;
|
||||
if (this.eatFixedHexDigits(4)) {
|
||||
const lead = this._lastIntValue;
|
||||
if (isLeadSurrogate(lead) &&
|
||||
this.eat(REVERSE_SOLIDUS) &&
|
||||
this.eat(LATIN_SMALL_LETTER_U) &&
|
||||
this.eatFixedHexDigits(4)) {
|
||||
const trail = this._lastIntValue;
|
||||
if (isTrailSurrogate(trail)) {
|
||||
this._lastIntValue = combineSurrogatePair(lead, trail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatRegExpUnicodeCodePointEscape() {
|
||||
const start = this.index;
|
||||
if (this.eat(LEFT_CURLY_BRACKET) &&
|
||||
this.eatHexDigits() &&
|
||||
this.eat(RIGHT_CURLY_BRACKET) &&
|
||||
isValidUnicode(this._lastIntValue)) {
|
||||
return true;
|
||||
}
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
eatIdentityEscape() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (this.isValidIdentityEscape(cp)) {
|
||||
this._lastIntValue = cp;
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
isValidIdentityEscape(cp) {
|
||||
if (cp === -1) {
|
||||
return false;
|
||||
}
|
||||
if (this._unicodeMode) {
|
||||
return isSyntaxCharacter(cp) || cp === SOLIDUS;
|
||||
}
|
||||
if (this.strict) {
|
||||
return !isIdContinue(cp);
|
||||
}
|
||||
if (this._nFlag) {
|
||||
return !(cp === LATIN_SMALL_LETTER_C || cp === LATIN_SMALL_LETTER_K);
|
||||
}
|
||||
return cp !== LATIN_SMALL_LETTER_C;
|
||||
}
|
||||
eatDecimalEscape() {
|
||||
this._lastIntValue = 0;
|
||||
let cp = this.currentCodePoint;
|
||||
if (cp >= DIGIT_ONE && cp <= DIGIT_NINE) {
|
||||
do {
|
||||
this._lastIntValue = 10 * this._lastIntValue + (cp - DIGIT_ZERO);
|
||||
this.advance();
|
||||
} while ((cp = this.currentCodePoint) >= DIGIT_ZERO &&
|
||||
cp <= DIGIT_NINE);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatUnicodePropertyValueExpression() {
|
||||
const start = this.index;
|
||||
if (this.eatUnicodePropertyName() && this.eat(EQUALS_SIGN)) {
|
||||
const key = this._lastStrValue;
|
||||
if (this.eatUnicodePropertyValue()) {
|
||||
const value = this._lastStrValue;
|
||||
if (isValidUnicodeProperty(this.ecmaVersion, key, value)) {
|
||||
return {
|
||||
key,
|
||||
value: value || null,
|
||||
};
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
}
|
||||
this.rewind(start);
|
||||
if (this.eatLoneUnicodePropertyNameOrValue()) {
|
||||
const nameOrValue = this._lastStrValue;
|
||||
if (isValidUnicodeProperty(this.ecmaVersion, "General_Category", nameOrValue)) {
|
||||
return {
|
||||
key: "General_Category",
|
||||
value: nameOrValue || null,
|
||||
};
|
||||
}
|
||||
if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) {
|
||||
return {
|
||||
key: nameOrValue,
|
||||
value: null,
|
||||
};
|
||||
}
|
||||
if (this._unicodeSetsMode &&
|
||||
isValidLoneUnicodePropertyOfString(this.ecmaVersion, nameOrValue)) {
|
||||
return {
|
||||
key: nameOrValue,
|
||||
value: null,
|
||||
strings: true,
|
||||
};
|
||||
}
|
||||
this.raise("Invalid property name");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
eatUnicodePropertyName() {
|
||||
this._lastStrValue = "";
|
||||
while (isUnicodePropertyNameCharacter(this.currentCodePoint)) {
|
||||
this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this._lastStrValue !== "";
|
||||
}
|
||||
eatUnicodePropertyValue() {
|
||||
this._lastStrValue = "";
|
||||
while (isUnicodePropertyValueCharacter(this.currentCodePoint)) {
|
||||
this._lastStrValue += String.fromCodePoint(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this._lastStrValue !== "";
|
||||
}
|
||||
eatLoneUnicodePropertyNameOrValue() {
|
||||
return this.eatUnicodePropertyValue();
|
||||
}
|
||||
eatHexEscapeSequence() {
|
||||
const start = this.index;
|
||||
if (this.eat(LATIN_SMALL_LETTER_X)) {
|
||||
if (this.eatFixedHexDigits(2)) {
|
||||
return true;
|
||||
}
|
||||
if (this._unicodeMode || this.strict) {
|
||||
this.raise("Invalid escape");
|
||||
}
|
||||
this.rewind(start);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatDecimalDigits() {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
while (isDecimalDigit(this.currentCodePoint)) {
|
||||
this._lastIntValue =
|
||||
10 * this._lastIntValue + digitToInt(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
eatHexDigits() {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
while (isHexDigit(this.currentCodePoint)) {
|
||||
this._lastIntValue =
|
||||
16 * this._lastIntValue + digitToInt(this.currentCodePoint);
|
||||
this.advance();
|
||||
}
|
||||
return this.index !== start;
|
||||
}
|
||||
eatLegacyOctalEscapeSequence() {
|
||||
if (this.eatOctalDigit()) {
|
||||
const n1 = this._lastIntValue;
|
||||
if (this.eatOctalDigit()) {
|
||||
const n2 = this._lastIntValue;
|
||||
if (n1 <= 3 && this.eatOctalDigit()) {
|
||||
this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue;
|
||||
}
|
||||
else {
|
||||
this._lastIntValue = n1 * 8 + n2;
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._lastIntValue = n1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
eatOctalDigit() {
|
||||
const cp = this.currentCodePoint;
|
||||
if (isOctalDigit(cp)) {
|
||||
this.advance();
|
||||
this._lastIntValue = cp - DIGIT_ZERO;
|
||||
return true;
|
||||
}
|
||||
this._lastIntValue = 0;
|
||||
return false;
|
||||
}
|
||||
eatFixedHexDigits(length) {
|
||||
const start = this.index;
|
||||
this._lastIntValue = 0;
|
||||
for (let i = 0; i < length; ++i) {
|
||||
const cp = this.currentCodePoint;
|
||||
if (!isHexDigit(cp)) {
|
||||
this.rewind(start);
|
||||
return false;
|
||||
}
|
||||
this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp);
|
||||
this.advance();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
eatModifiers() {
|
||||
let ate = false;
|
||||
while (isRegularExpressionModifier(this.currentCodePoint)) {
|
||||
this.advance();
|
||||
ate = true;
|
||||
}
|
||||
return ate;
|
||||
}
|
||||
parseModifiers(start, end) {
|
||||
const { ignoreCase, multiline, dotAll } = this.parseFlags(this._reader.source, start, end);
|
||||
return { ignoreCase, multiline, dotAll };
|
||||
}
|
||||
parseFlags(source, start, end) {
|
||||
const flags = {
|
||||
global: false,
|
||||
ignoreCase: false,
|
||||
multiline: false,
|
||||
unicode: false,
|
||||
sticky: false,
|
||||
dotAll: false,
|
||||
hasIndices: false,
|
||||
unicodeSets: false,
|
||||
};
|
||||
const validFlags = new Set();
|
||||
validFlags.add(LATIN_SMALL_LETTER_G);
|
||||
validFlags.add(LATIN_SMALL_LETTER_I);
|
||||
validFlags.add(LATIN_SMALL_LETTER_M);
|
||||
if (this.ecmaVersion >= 2015) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_U);
|
||||
validFlags.add(LATIN_SMALL_LETTER_Y);
|
||||
if (this.ecmaVersion >= 2018) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_S);
|
||||
if (this.ecmaVersion >= 2022) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_D);
|
||||
if (this.ecmaVersion >= 2024) {
|
||||
validFlags.add(LATIN_SMALL_LETTER_V);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = start; i < end; ++i) {
|
||||
const flag = source.charCodeAt(i);
|
||||
if (validFlags.has(flag)) {
|
||||
const prop = FLAG_CODEPOINT_TO_PROP[flag];
|
||||
if (flags[prop]) {
|
||||
this.raise(`Duplicated flag '${source[i]}'`, {
|
||||
index: start,
|
||||
});
|
||||
}
|
||||
flags[prop] = true;
|
||||
}
|
||||
else {
|
||||
this.raise(`Invalid flag '${source[i]}'`, { index: start });
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
|
||||
const DUMMY_PATTERN = {};
|
||||
const DUMMY_FLAGS = {};
|
||||
const DUMMY_CAPTURING_GROUP = {};
|
||||
function isClassSetOperand(node) {
|
||||
return (node.type === "Character" ||
|
||||
node.type === "CharacterSet" ||
|
||||
node.type === "CharacterClass" ||
|
||||
node.type === "ExpressionCharacterClass" ||
|
||||
node.type === "ClassStringDisjunction");
|
||||
}
|
||||
class RegExpParserState {
|
||||
constructor(options) {
|
||||
var _a;
|
||||
this._node = DUMMY_PATTERN;
|
||||
this._expressionBufferMap = new Map();
|
||||
this._flags = DUMMY_FLAGS;
|
||||
this._backreferences = [];
|
||||
this._capturingGroups = [];
|
||||
this.source = "";
|
||||
this.strict = Boolean(options === null || options === void 0 ? void 0 : options.strict);
|
||||
this.ecmaVersion = (_a = options === null || options === void 0 ? void 0 : options.ecmaVersion) !== null && _a !== void 0 ? _a : latestEcmaVersion;
|
||||
}
|
||||
get pattern() {
|
||||
if (this._node.type !== "Pattern") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
return this._node;
|
||||
}
|
||||
get flags() {
|
||||
if (this._flags.type !== "Flags") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
return this._flags;
|
||||
}
|
||||
onRegExpFlags(start, end, { global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, unicodeSets, }) {
|
||||
this._flags = {
|
||||
type: "Flags",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
global,
|
||||
ignoreCase,
|
||||
multiline,
|
||||
unicode,
|
||||
sticky,
|
||||
dotAll,
|
||||
hasIndices,
|
||||
unicodeSets,
|
||||
};
|
||||
}
|
||||
onPatternEnter(start) {
|
||||
this._node = {
|
||||
type: "Pattern",
|
||||
parent: null,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
alternatives: [],
|
||||
};
|
||||
this._backreferences.length = 0;
|
||||
this._capturingGroups.length = 0;
|
||||
}
|
||||
onPatternLeave(start, end) {
|
||||
this._node.end = end;
|
||||
this._node.raw = this.source.slice(start, end);
|
||||
for (const reference of this._backreferences) {
|
||||
const ref = reference.ref;
|
||||
const groups = typeof ref === "number"
|
||||
? [this._capturingGroups[ref - 1]]
|
||||
: this._capturingGroups.filter((g) => g.name === ref);
|
||||
if (groups.length === 1) {
|
||||
const group = groups[0];
|
||||
reference.ambiguous = false;
|
||||
reference.resolved = group;
|
||||
}
|
||||
else {
|
||||
reference.ambiguous = true;
|
||||
reference.resolved = groups;
|
||||
}
|
||||
for (const group of groups) {
|
||||
group.references.push(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
onAlternativeEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Assertion" &&
|
||||
parent.type !== "CapturingGroup" &&
|
||||
parent.type !== "Group" &&
|
||||
parent.type !== "Pattern") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "Alternative",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
elements: [],
|
||||
};
|
||||
parent.alternatives.push(this._node);
|
||||
}
|
||||
onAlternativeLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onGroupEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const group = {
|
||||
type: "Group",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
modifiers: null,
|
||||
alternatives: [],
|
||||
};
|
||||
this._node = group;
|
||||
parent.elements.push(this._node);
|
||||
}
|
||||
onGroupLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Group" || node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onModifiersEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Group") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "Modifiers",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
add: null,
|
||||
remove: null,
|
||||
};
|
||||
parent.modifiers = this._node;
|
||||
}
|
||||
onModifiersLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Modifiers" || node.parent.type !== "Group") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onAddModifiers(start, end, { ignoreCase, multiline, dotAll, }) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Modifiers") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.add = {
|
||||
type: "ModifierFlags",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ignoreCase,
|
||||
multiline,
|
||||
dotAll,
|
||||
};
|
||||
}
|
||||
onRemoveModifiers(start, end, { ignoreCase, multiline, dotAll, }) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Modifiers") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.remove = {
|
||||
type: "ModifierFlags",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ignoreCase,
|
||||
multiline,
|
||||
dotAll,
|
||||
};
|
||||
}
|
||||
onCapturingGroupEnter(start, name) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "CapturingGroup",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
name,
|
||||
alternatives: [],
|
||||
references: [],
|
||||
};
|
||||
parent.elements.push(this._node);
|
||||
this._capturingGroups.push(this._node);
|
||||
}
|
||||
onCapturingGroupLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "CapturingGroup" ||
|
||||
node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onQuantifier(start, end, min, max, greedy) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const element = parent.elements.pop();
|
||||
if (element == null ||
|
||||
element.type === "Quantifier" ||
|
||||
(element.type === "Assertion" && element.kind !== "lookahead")) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "Quantifier",
|
||||
parent,
|
||||
start: element.start,
|
||||
end,
|
||||
raw: this.source.slice(element.start, end),
|
||||
min,
|
||||
max,
|
||||
greedy,
|
||||
element,
|
||||
};
|
||||
parent.elements.push(node);
|
||||
element.parent = node;
|
||||
}
|
||||
onLookaroundAssertionEnter(start, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = (this._node = {
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
kind,
|
||||
negate,
|
||||
alternatives: [],
|
||||
});
|
||||
parent.elements.push(node);
|
||||
}
|
||||
onLookaroundAssertionLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "Assertion" || node.parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onEdgeAssertion(start, end, kind) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
onWordBoundaryAssertion(start, end, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Assertion",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
negate,
|
||||
});
|
||||
}
|
||||
onAnyCharacterSet(start, end, kind) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "CharacterSet",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
onEscapeCharacterSet(start, end, kind, negate) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "CharacterSet",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
negate,
|
||||
});
|
||||
}
|
||||
onUnicodePropertyCharacterSet(start, end, kind, key, value, negate, strings) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const base = {
|
||||
type: "CharacterSet",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
kind,
|
||||
strings: null,
|
||||
key,
|
||||
};
|
||||
if (strings) {
|
||||
if ((parent.type === "CharacterClass" && !parent.unicodeSets) ||
|
||||
negate ||
|
||||
value !== null) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate }));
|
||||
}
|
||||
else {
|
||||
parent.elements.push(Object.assign(Object.assign({}, base), { parent, strings, value, negate }));
|
||||
}
|
||||
}
|
||||
onCharacter(start, end, value) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative" &&
|
||||
parent.type !== "CharacterClass" &&
|
||||
parent.type !== "StringAlternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push({
|
||||
type: "Character",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
value,
|
||||
});
|
||||
}
|
||||
onBackreference(start, end, ref) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "Alternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "Backreference",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
ref,
|
||||
ambiguous: false,
|
||||
resolved: DUMMY_CAPTURING_GROUP,
|
||||
};
|
||||
parent.elements.push(node);
|
||||
this._backreferences.push(node);
|
||||
}
|
||||
onCharacterClassEnter(start, negate, unicodeSets) {
|
||||
const parent = this._node;
|
||||
const base = {
|
||||
type: "CharacterClass",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
unicodeSets,
|
||||
negate,
|
||||
elements: [],
|
||||
};
|
||||
if (parent.type === "Alternative") {
|
||||
const node = Object.assign(Object.assign({}, base), { parent });
|
||||
this._node = node;
|
||||
parent.elements.push(node);
|
||||
}
|
||||
else if (parent.type === "CharacterClass" &&
|
||||
parent.unicodeSets &&
|
||||
unicodeSets) {
|
||||
const node = Object.assign(Object.assign({}, base), { parent,
|
||||
unicodeSets });
|
||||
this._node = node;
|
||||
parent.elements.push(node);
|
||||
}
|
||||
else {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
}
|
||||
onCharacterClassLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "CharacterClass" ||
|
||||
(node.parent.type !== "Alternative" &&
|
||||
node.parent.type !== "CharacterClass")) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const parent = node.parent;
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = parent;
|
||||
const expression = this._expressionBufferMap.get(node);
|
||||
if (!expression) {
|
||||
return;
|
||||
}
|
||||
if (node.elements.length > 0) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._expressionBufferMap.delete(node);
|
||||
const newNode = {
|
||||
type: "ExpressionCharacterClass",
|
||||
parent,
|
||||
start: node.start,
|
||||
end: node.end,
|
||||
raw: node.raw,
|
||||
negate: node.negate,
|
||||
expression,
|
||||
};
|
||||
expression.parent = newNode;
|
||||
if (node !== parent.elements.pop()) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
parent.elements.push(newNode);
|
||||
}
|
||||
onCharacterClassRange(start, end) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const elements = parent.elements;
|
||||
const max = elements.pop();
|
||||
if (!max || max.type !== "Character") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
if (!parent.unicodeSets) {
|
||||
const hyphen = elements.pop();
|
||||
if (!hyphen ||
|
||||
hyphen.type !== "Character" ||
|
||||
hyphen.value !== HYPHEN_MINUS) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
}
|
||||
const min = elements.pop();
|
||||
if (!min || min.type !== "Character") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "CharacterClassRange",
|
||||
parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
min,
|
||||
max,
|
||||
};
|
||||
min.parent = node;
|
||||
max.parent = node;
|
||||
elements.push(node);
|
||||
}
|
||||
onClassIntersection(start, end) {
|
||||
var _a;
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const right = parent.elements.pop();
|
||||
const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop();
|
||||
if (!left ||
|
||||
!right ||
|
||||
left.type === "ClassSubtraction" ||
|
||||
(left.type !== "ClassIntersection" && !isClassSetOperand(left)) ||
|
||||
!isClassSetOperand(right)) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "ClassIntersection",
|
||||
parent: parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
left,
|
||||
right,
|
||||
};
|
||||
left.parent = node;
|
||||
right.parent = node;
|
||||
this._expressionBufferMap.set(parent, node);
|
||||
}
|
||||
onClassSubtraction(start, end) {
|
||||
var _a;
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const right = parent.elements.pop();
|
||||
const left = (_a = this._expressionBufferMap.get(parent)) !== null && _a !== void 0 ? _a : parent.elements.pop();
|
||||
if (!left ||
|
||||
!right ||
|
||||
left.type === "ClassIntersection" ||
|
||||
(left.type !== "ClassSubtraction" && !isClassSetOperand(left)) ||
|
||||
!isClassSetOperand(right)) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
const node = {
|
||||
type: "ClassSubtraction",
|
||||
parent: parent,
|
||||
start,
|
||||
end,
|
||||
raw: this.source.slice(start, end),
|
||||
left,
|
||||
right,
|
||||
};
|
||||
left.parent = node;
|
||||
right.parent = node;
|
||||
this._expressionBufferMap.set(parent, node);
|
||||
}
|
||||
onClassStringDisjunctionEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "ClassStringDisjunction",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
alternatives: [],
|
||||
};
|
||||
parent.elements.push(this._node);
|
||||
}
|
||||
onClassStringDisjunctionLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "ClassStringDisjunction" ||
|
||||
node.parent.type !== "CharacterClass") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
onStringAlternativeEnter(start) {
|
||||
const parent = this._node;
|
||||
if (parent.type !== "ClassStringDisjunction") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
this._node = {
|
||||
type: "StringAlternative",
|
||||
parent,
|
||||
start,
|
||||
end: start,
|
||||
raw: "",
|
||||
elements: [],
|
||||
};
|
||||
parent.alternatives.push(this._node);
|
||||
}
|
||||
onStringAlternativeLeave(start, end) {
|
||||
const node = this._node;
|
||||
if (node.type !== "StringAlternative") {
|
||||
throw new Error("UnknownError");
|
||||
}
|
||||
node.end = end;
|
||||
node.raw = this.source.slice(start, end);
|
||||
this._node = node.parent;
|
||||
}
|
||||
}
|
||||
class RegExpParser {
|
||||
constructor(options) {
|
||||
this._state = new RegExpParserState(options);
|
||||
this._validator = new RegExpValidator(this._state);
|
||||
}
|
||||
parseLiteral(source, start = 0, end = source.length) {
|
||||
this._state.source = source;
|
||||
this._validator.validateLiteral(source, start, end);
|
||||
const pattern = this._state.pattern;
|
||||
const flags = this._state.flags;
|
||||
const literal = {
|
||||
type: "RegExpLiteral",
|
||||
parent: null,
|
||||
start,
|
||||
end,
|
||||
raw: source,
|
||||
pattern,
|
||||
flags,
|
||||
};
|
||||
pattern.parent = literal;
|
||||
flags.parent = literal;
|
||||
return literal;
|
||||
}
|
||||
parseFlags(source, start = 0, end = source.length) {
|
||||
this._state.source = source;
|
||||
this._validator.validateFlags(source, start, end);
|
||||
return this._state.flags;
|
||||
}
|
||||
parsePattern(source, start = 0, end = source.length, uFlagOrFlags = undefined) {
|
||||
this._state.source = source;
|
||||
this._validator.validatePattern(source, start, end, uFlagOrFlags);
|
||||
return this._state.pattern;
|
||||
}
|
||||
}
|
||||
|
||||
class RegExpVisitor {
|
||||
constructor(handlers) {
|
||||
this._handlers = handlers;
|
||||
}
|
||||
visit(node) {
|
||||
switch (node.type) {
|
||||
case "Alternative":
|
||||
this.visitAlternative(node);
|
||||
break;
|
||||
case "Assertion":
|
||||
this.visitAssertion(node);
|
||||
break;
|
||||
case "Backreference":
|
||||
this.visitBackreference(node);
|
||||
break;
|
||||
case "CapturingGroup":
|
||||
this.visitCapturingGroup(node);
|
||||
break;
|
||||
case "Character":
|
||||
this.visitCharacter(node);
|
||||
break;
|
||||
case "CharacterClass":
|
||||
this.visitCharacterClass(node);
|
||||
break;
|
||||
case "CharacterClassRange":
|
||||
this.visitCharacterClassRange(node);
|
||||
break;
|
||||
case "CharacterSet":
|
||||
this.visitCharacterSet(node);
|
||||
break;
|
||||
case "ClassIntersection":
|
||||
this.visitClassIntersection(node);
|
||||
break;
|
||||
case "ClassStringDisjunction":
|
||||
this.visitClassStringDisjunction(node);
|
||||
break;
|
||||
case "ClassSubtraction":
|
||||
this.visitClassSubtraction(node);
|
||||
break;
|
||||
case "ExpressionCharacterClass":
|
||||
this.visitExpressionCharacterClass(node);
|
||||
break;
|
||||
case "Flags":
|
||||
this.visitFlags(node);
|
||||
break;
|
||||
case "Group":
|
||||
this.visitGroup(node);
|
||||
break;
|
||||
case "Modifiers":
|
||||
this.visitModifiers(node);
|
||||
break;
|
||||
case "ModifierFlags":
|
||||
this.visitModifierFlags(node);
|
||||
break;
|
||||
case "Pattern":
|
||||
this.visitPattern(node);
|
||||
break;
|
||||
case "Quantifier":
|
||||
this.visitQuantifier(node);
|
||||
break;
|
||||
case "RegExpLiteral":
|
||||
this.visitRegExpLiteral(node);
|
||||
break;
|
||||
case "StringAlternative":
|
||||
this.visitStringAlternative(node);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown type: ${node.type}`);
|
||||
}
|
||||
}
|
||||
visitAlternative(node) {
|
||||
if (this._handlers.onAlternativeEnter) {
|
||||
this._handlers.onAlternativeEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onAlternativeLeave) {
|
||||
this._handlers.onAlternativeLeave(node);
|
||||
}
|
||||
}
|
||||
visitAssertion(node) {
|
||||
if (this._handlers.onAssertionEnter) {
|
||||
this._handlers.onAssertionEnter(node);
|
||||
}
|
||||
if (node.kind === "lookahead" || node.kind === "lookbehind") {
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
}
|
||||
if (this._handlers.onAssertionLeave) {
|
||||
this._handlers.onAssertionLeave(node);
|
||||
}
|
||||
}
|
||||
visitBackreference(node) {
|
||||
if (this._handlers.onBackreferenceEnter) {
|
||||
this._handlers.onBackreferenceEnter(node);
|
||||
}
|
||||
if (this._handlers.onBackreferenceLeave) {
|
||||
this._handlers.onBackreferenceLeave(node);
|
||||
}
|
||||
}
|
||||
visitCapturingGroup(node) {
|
||||
if (this._handlers.onCapturingGroupEnter) {
|
||||
this._handlers.onCapturingGroupEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onCapturingGroupLeave) {
|
||||
this._handlers.onCapturingGroupLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacter(node) {
|
||||
if (this._handlers.onCharacterEnter) {
|
||||
this._handlers.onCharacterEnter(node);
|
||||
}
|
||||
if (this._handlers.onCharacterLeave) {
|
||||
this._handlers.onCharacterLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterClass(node) {
|
||||
if (this._handlers.onCharacterClassEnter) {
|
||||
this._handlers.onCharacterClassEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onCharacterClassLeave) {
|
||||
this._handlers.onCharacterClassLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterClassRange(node) {
|
||||
if (this._handlers.onCharacterClassRangeEnter) {
|
||||
this._handlers.onCharacterClassRangeEnter(node);
|
||||
}
|
||||
this.visitCharacter(node.min);
|
||||
this.visitCharacter(node.max);
|
||||
if (this._handlers.onCharacterClassRangeLeave) {
|
||||
this._handlers.onCharacterClassRangeLeave(node);
|
||||
}
|
||||
}
|
||||
visitCharacterSet(node) {
|
||||
if (this._handlers.onCharacterSetEnter) {
|
||||
this._handlers.onCharacterSetEnter(node);
|
||||
}
|
||||
if (this._handlers.onCharacterSetLeave) {
|
||||
this._handlers.onCharacterSetLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassIntersection(node) {
|
||||
if (this._handlers.onClassIntersectionEnter) {
|
||||
this._handlers.onClassIntersectionEnter(node);
|
||||
}
|
||||
this.visit(node.left);
|
||||
this.visit(node.right);
|
||||
if (this._handlers.onClassIntersectionLeave) {
|
||||
this._handlers.onClassIntersectionLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassStringDisjunction(node) {
|
||||
if (this._handlers.onClassStringDisjunctionEnter) {
|
||||
this._handlers.onClassStringDisjunctionEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onClassStringDisjunctionLeave) {
|
||||
this._handlers.onClassStringDisjunctionLeave(node);
|
||||
}
|
||||
}
|
||||
visitClassSubtraction(node) {
|
||||
if (this._handlers.onClassSubtractionEnter) {
|
||||
this._handlers.onClassSubtractionEnter(node);
|
||||
}
|
||||
this.visit(node.left);
|
||||
this.visit(node.right);
|
||||
if (this._handlers.onClassSubtractionLeave) {
|
||||
this._handlers.onClassSubtractionLeave(node);
|
||||
}
|
||||
}
|
||||
visitExpressionCharacterClass(node) {
|
||||
if (this._handlers.onExpressionCharacterClassEnter) {
|
||||
this._handlers.onExpressionCharacterClassEnter(node);
|
||||
}
|
||||
this.visit(node.expression);
|
||||
if (this._handlers.onExpressionCharacterClassLeave) {
|
||||
this._handlers.onExpressionCharacterClassLeave(node);
|
||||
}
|
||||
}
|
||||
visitFlags(node) {
|
||||
if (this._handlers.onFlagsEnter) {
|
||||
this._handlers.onFlagsEnter(node);
|
||||
}
|
||||
if (this._handlers.onFlagsLeave) {
|
||||
this._handlers.onFlagsLeave(node);
|
||||
}
|
||||
}
|
||||
visitGroup(node) {
|
||||
if (this._handlers.onGroupEnter) {
|
||||
this._handlers.onGroupEnter(node);
|
||||
}
|
||||
if (node.modifiers) {
|
||||
this.visit(node.modifiers);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onGroupLeave) {
|
||||
this._handlers.onGroupLeave(node);
|
||||
}
|
||||
}
|
||||
visitModifiers(node) {
|
||||
if (this._handlers.onModifiersEnter) {
|
||||
this._handlers.onModifiersEnter(node);
|
||||
}
|
||||
if (node.add) {
|
||||
this.visit(node.add);
|
||||
}
|
||||
if (node.remove) {
|
||||
this.visit(node.remove);
|
||||
}
|
||||
if (this._handlers.onModifiersLeave) {
|
||||
this._handlers.onModifiersLeave(node);
|
||||
}
|
||||
}
|
||||
visitModifierFlags(node) {
|
||||
if (this._handlers.onModifierFlagsEnter) {
|
||||
this._handlers.onModifierFlagsEnter(node);
|
||||
}
|
||||
if (this._handlers.onModifierFlagsLeave) {
|
||||
this._handlers.onModifierFlagsLeave(node);
|
||||
}
|
||||
}
|
||||
visitPattern(node) {
|
||||
if (this._handlers.onPatternEnter) {
|
||||
this._handlers.onPatternEnter(node);
|
||||
}
|
||||
node.alternatives.forEach(this.visit, this);
|
||||
if (this._handlers.onPatternLeave) {
|
||||
this._handlers.onPatternLeave(node);
|
||||
}
|
||||
}
|
||||
visitQuantifier(node) {
|
||||
if (this._handlers.onQuantifierEnter) {
|
||||
this._handlers.onQuantifierEnter(node);
|
||||
}
|
||||
this.visit(node.element);
|
||||
if (this._handlers.onQuantifierLeave) {
|
||||
this._handlers.onQuantifierLeave(node);
|
||||
}
|
||||
}
|
||||
visitRegExpLiteral(node) {
|
||||
if (this._handlers.onRegExpLiteralEnter) {
|
||||
this._handlers.onRegExpLiteralEnter(node);
|
||||
}
|
||||
this.visitPattern(node.pattern);
|
||||
this.visitFlags(node.flags);
|
||||
if (this._handlers.onRegExpLiteralLeave) {
|
||||
this._handlers.onRegExpLiteralLeave(node);
|
||||
}
|
||||
}
|
||||
visitStringAlternative(node) {
|
||||
if (this._handlers.onStringAlternativeEnter) {
|
||||
this._handlers.onStringAlternativeEnter(node);
|
||||
}
|
||||
node.elements.forEach(this.visit, this);
|
||||
if (this._handlers.onStringAlternativeLeave) {
|
||||
this._handlers.onStringAlternativeLeave(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseRegExpLiteral(source, options) {
|
||||
return new RegExpParser(options).parseLiteral(String(source));
|
||||
}
|
||||
function validateRegExpLiteral(source, options) {
|
||||
new RegExpValidator(options).validateLiteral(source);
|
||||
}
|
||||
function visitRegExpAST(node, handlers) {
|
||||
new RegExpVisitor(handlers).visit(node);
|
||||
}
|
||||
|
||||
export { ast as AST, RegExpParser, RegExpSyntaxError, RegExpValidator, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST };
|
||||
//# sourceMappingURL=index.mjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@eslint-community/regexpp",
|
||||
"version": "4.12.2",
|
||||
"description": "Regular expression parser for ECMAScript.",
|
||||
"keywords": [
|
||||
"regexp",
|
||||
"regular",
|
||||
"expression",
|
||||
"parser",
|
||||
"validator",
|
||||
"ast",
|
||||
"abstract",
|
||||
"syntax",
|
||||
"tree",
|
||||
"ecmascript",
|
||||
"es2015",
|
||||
"es2016",
|
||||
"es2017",
|
||||
"es2018",
|
||||
"es2019",
|
||||
"es2020",
|
||||
"es2021",
|
||||
"annexB"
|
||||
],
|
||||
"homepage": "https://github.com/eslint-community/regexpp#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint-community/regexpp/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint-community/regexpp"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Toru Nagashima",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.mjs",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "index",
|
||||
"files": [
|
||||
"index.*"
|
||||
],
|
||||
"scripts": {
|
||||
"prebuild": "npm run -s clean",
|
||||
"build": "run-s build:*",
|
||||
"build:tsc": "tsc --module es2015",
|
||||
"build:rollup": "rollup -c",
|
||||
"build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts",
|
||||
"clean": "rimraf .temp index.*",
|
||||
"lint": "eslint . --ext .ts",
|
||||
"test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000",
|
||||
"debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000",
|
||||
"update:test": "ts-node scripts/update-fixtures.ts",
|
||||
"update:unicode": "run-s update:unicode:*",
|
||||
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
|
||||
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
|
||||
"update:test262:extract": "ts-node -T scripts/extract-test262.ts",
|
||||
"preversion": "npm test && npm run -s build",
|
||||
"postversion": "git push && git push --tags",
|
||||
"prewatch": "npm run -s clean",
|
||||
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-mysticatea": "^15.5.1",
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@types/eslint": "^8.44.3",
|
||||
"@types/jsdom": "^16.2.15",
|
||||
"@types/mocha": "^9.1.1",
|
||||
"@types/node": "^12.20.55",
|
||||
"dts-bundle": "^0.7.3",
|
||||
"eslint": "^8.50.0",
|
||||
"js-tokens": "^8.0.2",
|
||||
"jsdom": "^19.0.0",
|
||||
"mocha": "^9.2.2",
|
||||
"npm-run-all2": "^6.2.2",
|
||||
"nyc": "^14.1.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-plugin-sourcemaps": "^0.6.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "~5.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# ESLintRC Library
|
||||
|
||||
This repository contains the legacy ESLintRC configuration file format for ESLint. This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.
|
||||
|
||||
**Note:** This package is frozen except for critical bug fixes as ESLint moves to a new config system.
|
||||
|
||||
## Installation
|
||||
|
||||
You can install the package as follows:
|
||||
|
||||
```
|
||||
npm install @eslint/eslintrc --save-dev
|
||||
|
||||
# or
|
||||
|
||||
yarn add @eslint/eslintrc -D
|
||||
```
|
||||
|
||||
## Usage (ESM)
|
||||
|
||||
The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file:
|
||||
|
||||
```js
|
||||
import { FlatCompat } from "@eslint/eslintrc";
|
||||
import js from "@eslint/js";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
// mimic CommonJS variables -- not needed if using CommonJS
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname, // optional; default: process.cwd()
|
||||
resolvePluginsRelativeTo: __dirname, // optional
|
||||
recommendedConfig: js.configs.recommended, // optional
|
||||
allConfig: js.configs.all, // optional
|
||||
});
|
||||
|
||||
export default [
|
||||
|
||||
// mimic ESLintRC-style extends
|
||||
...compat.extends("standard", "example"),
|
||||
|
||||
// mimic environments
|
||||
...compat.env({
|
||||
es2020: true,
|
||||
node: true
|
||||
}),
|
||||
|
||||
// mimic plugins
|
||||
...compat.plugins("airbnb", "react"),
|
||||
|
||||
// translate an entire config
|
||||
...compat.config({
|
||||
plugins: ["airbnb", "react"],
|
||||
extends: "standard",
|
||||
env: {
|
||||
es2020: true,
|
||||
node: true
|
||||
},
|
||||
rules: {
|
||||
semi: "error"
|
||||
}
|
||||
})
|
||||
];
|
||||
```
|
||||
|
||||
## Usage (CommonJS)
|
||||
|
||||
Using `FlatCompat` in CommonJS files is similar to ESM, but you'll use `require()` and `module.exports` instead of `import` and `export`. Here's how you use it inside of your `eslint.config.js` CommonJS file:
|
||||
|
||||
```js
|
||||
const { FlatCompat } = require("@eslint/eslintrc");
|
||||
const js = require("@eslint/js");
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname, // optional; default: process.cwd()
|
||||
resolvePluginsRelativeTo: __dirname, // optional
|
||||
recommendedConfig: js.configs.recommended, // optional
|
||||
allConfig: js.configs.all, // optional
|
||||
});
|
||||
|
||||
module.exports = [
|
||||
|
||||
// mimic ESLintRC-style extends
|
||||
...compat.extends("standard", "example"),
|
||||
|
||||
// mimic environments
|
||||
...compat.env({
|
||||
es2020: true,
|
||||
node: true
|
||||
}),
|
||||
|
||||
// mimic plugins
|
||||
...compat.plugins("airbnb", "react"),
|
||||
|
||||
// translate an entire config
|
||||
...compat.config({
|
||||
plugins: ["airbnb", "react"],
|
||||
extends: "standard",
|
||||
env: {
|
||||
es2020: true,
|
||||
node: true
|
||||
},
|
||||
rules: {
|
||||
semi: "error"
|
||||
}
|
||||
})
|
||||
];
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT License
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @fileoverview Defines a schema for configs.
|
||||
* @author Sylvan Mably
|
||||
*/
|
||||
|
||||
const baseConfigProperties = {
|
||||
$schema: { type: "string" },
|
||||
env: { type: "object" },
|
||||
extends: { $ref: "#/definitions/stringOrStrings" },
|
||||
globals: { type: "object" },
|
||||
overrides: {
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/overrideConfig" },
|
||||
additionalItems: false
|
||||
},
|
||||
parser: { type: ["string", "null"] },
|
||||
parserOptions: { type: "object" },
|
||||
plugins: { type: "array" },
|
||||
processor: { type: "string" },
|
||||
rules: { type: "object" },
|
||||
settings: { type: "object" },
|
||||
noInlineConfig: { type: "boolean" },
|
||||
reportUnusedDisableDirectives: { type: "boolean" },
|
||||
|
||||
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
|
||||
};
|
||||
|
||||
const configSchema = {
|
||||
definitions: {
|
||||
stringOrStrings: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false
|
||||
}
|
||||
]
|
||||
},
|
||||
stringOrStringsRequired: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false,
|
||||
minItems: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// Config at top-level.
|
||||
objectConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
root: { type: "boolean" },
|
||||
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
|
||||
// Config in `overrides`.
|
||||
overrideConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
|
||||
files: { $ref: "#/definitions/stringOrStringsRequired" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
required: ["files"],
|
||||
additionalProperties: false
|
||||
}
|
||||
},
|
||||
|
||||
$ref: "#/definitions/objectConfig"
|
||||
};
|
||||
|
||||
export default configSchema;
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* @fileoverview Defines environment settings and globals.
|
||||
* @author Elan Shanker
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import globals from "globals";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the object that has difference.
|
||||
* @param {Record<string,boolean>} current The newer object.
|
||||
* @param {Record<string,boolean>} prev The older object.
|
||||
* @returns {Record<string,boolean>} The difference object.
|
||||
*/
|
||||
function getDiff(current, prev) {
|
||||
const retv = {};
|
||||
|
||||
for (const [key, value] of Object.entries(current)) {
|
||||
if (!Object.hasOwnProperty.call(prev, key)) {
|
||||
retv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return retv;
|
||||
}
|
||||
|
||||
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
|
||||
const newGlobals2017 = {
|
||||
Atomics: false,
|
||||
SharedArrayBuffer: false
|
||||
};
|
||||
const newGlobals2020 = {
|
||||
BigInt: false,
|
||||
BigInt64Array: false,
|
||||
BigUint64Array: false,
|
||||
globalThis: false
|
||||
};
|
||||
|
||||
const newGlobals2021 = {
|
||||
AggregateError: false,
|
||||
FinalizationRegistry: false,
|
||||
WeakRef: false
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {Map<string, import("../lib/shared/types").Environment>} */
|
||||
export default new Map(Object.entries({
|
||||
|
||||
// Language
|
||||
builtin: {
|
||||
globals: globals.es5
|
||||
},
|
||||
es6: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2015: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2016: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 7
|
||||
}
|
||||
},
|
||||
es2017: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 8
|
||||
}
|
||||
},
|
||||
es2018: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 9
|
||||
}
|
||||
},
|
||||
es2019: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 10
|
||||
}
|
||||
},
|
||||
es2020: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 11
|
||||
}
|
||||
},
|
||||
es2021: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 12
|
||||
}
|
||||
},
|
||||
es2022: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 13
|
||||
}
|
||||
},
|
||||
es2023: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 14
|
||||
}
|
||||
},
|
||||
es2024: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 15
|
||||
}
|
||||
},
|
||||
|
||||
// Platforms
|
||||
browser: {
|
||||
globals: globals.browser
|
||||
},
|
||||
node: {
|
||||
globals: globals.node,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
"shared-node-browser": {
|
||||
globals: globals["shared-node-browser"]
|
||||
},
|
||||
worker: {
|
||||
globals: globals.worker
|
||||
},
|
||||
serviceworker: {
|
||||
globals: globals.serviceworker
|
||||
},
|
||||
|
||||
// Frameworks
|
||||
commonjs: {
|
||||
globals: globals.commonjs,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
amd: {
|
||||
globals: globals.amd
|
||||
},
|
||||
mocha: {
|
||||
globals: globals.mocha
|
||||
},
|
||||
jasmine: {
|
||||
globals: globals.jasmine
|
||||
},
|
||||
jest: {
|
||||
globals: globals.jest
|
||||
},
|
||||
phantomjs: {
|
||||
globals: globals.phantomjs
|
||||
},
|
||||
jquery: {
|
||||
globals: globals.jquery
|
||||
},
|
||||
qunit: {
|
||||
globals: globals.qunit
|
||||
},
|
||||
prototypejs: {
|
||||
globals: globals.prototypejs
|
||||
},
|
||||
shelljs: {
|
||||
globals: globals.shelljs
|
||||
},
|
||||
meteor: {
|
||||
globals: globals.meteor
|
||||
},
|
||||
mongo: {
|
||||
globals: globals.mongo
|
||||
},
|
||||
protractor: {
|
||||
globals: globals.protractor
|
||||
},
|
||||
applescript: {
|
||||
globals: globals.applescript
|
||||
},
|
||||
nashorn: {
|
||||
globals: globals.nashorn
|
||||
},
|
||||
atomtest: {
|
||||
globals: globals.atomtest
|
||||
},
|
||||
embertest: {
|
||||
globals: globals.embertest
|
||||
},
|
||||
webextensions: {
|
||||
globals: globals.webextensions
|
||||
},
|
||||
greasemonkey: {
|
||||
globals: globals.greasemonkey
|
||||
}
|
||||
}));
|
||||
Generated
Vendored
+1104
@@ -0,0 +1,1104 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var util = require('util');
|
||||
var path = require('path');
|
||||
var Ajv = require('ajv');
|
||||
var globals = require('globals');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
|
||||
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
||||
var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
|
||||
var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals);
|
||||
|
||||
/**
|
||||
* @fileoverview Config file operations. This file must be usable in the browser,
|
||||
* so no Node-specific code can be here.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
|
||||
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
|
||||
map[value] = index;
|
||||
return map;
|
||||
}, {}),
|
||||
VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Normalizes the severity value of a rule's configuration to a number
|
||||
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
|
||||
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
|
||||
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
|
||||
* whose first element is one of the above values. Strings are matched case-insensitively.
|
||||
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
|
||||
*/
|
||||
function getRuleSeverity(ruleConfig) {
|
||||
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
|
||||
return severityValue;
|
||||
}
|
||||
|
||||
if (typeof severityValue === "string") {
|
||||
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts old-style severity settings (0, 1, 2) into new-style
|
||||
* severity settings (off, warn, error) for all rules. Assumption is that severity
|
||||
* values have already been validated as correct.
|
||||
* @param {Object} config The config object to normalize.
|
||||
* @returns {void}
|
||||
*/
|
||||
function normalizeToStrings(config) {
|
||||
|
||||
if (config.rules) {
|
||||
Object.keys(config.rules).forEach(ruleId => {
|
||||
const ruleConfig = config.rules[ruleId];
|
||||
|
||||
if (typeof ruleConfig === "number") {
|
||||
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
|
||||
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
|
||||
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the severity for the given rule configuration represents an error.
|
||||
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} True if the rule represents an error, false if not.
|
||||
*/
|
||||
function isErrorSeverity(ruleConfig) {
|
||||
return getRuleSeverity(ruleConfig) === 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given config has valid severity or not.
|
||||
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isValidSeverity(ruleConfig) {
|
||||
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (typeof severity === "string") {
|
||||
severity = severity.toLowerCase();
|
||||
}
|
||||
return VALID_SEVERITIES.indexOf(severity) !== -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether every rule of a given config has valid severity or not.
|
||||
* @param {Object} config The configuration for rules.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isEverySeverityValid(config) {
|
||||
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a value for a global in a config
|
||||
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
|
||||
* a global directive comment
|
||||
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
|
||||
* @throws Error if global value is invalid
|
||||
*/
|
||||
function normalizeConfigGlobal(configuredValue) {
|
||||
switch (configuredValue) {
|
||||
case "off":
|
||||
return "off";
|
||||
|
||||
case true:
|
||||
case "true":
|
||||
case "writeable":
|
||||
case "writable":
|
||||
return "writable";
|
||||
|
||||
case null:
|
||||
case false:
|
||||
case "false":
|
||||
case "readable":
|
||||
case "readonly":
|
||||
return "readonly";
|
||||
|
||||
default:
|
||||
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
|
||||
}
|
||||
}
|
||||
|
||||
var ConfigOps = {
|
||||
__proto__: null,
|
||||
getRuleSeverity: getRuleSeverity,
|
||||
normalizeToStrings: normalizeToStrings,
|
||||
isErrorSeverity: isErrorSeverity,
|
||||
isValidSeverity: isValidSeverity,
|
||||
isEverySeverityValid: isEverySeverityValid,
|
||||
normalizeConfigGlobal: normalizeConfigGlobal
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Provide the function that emits deprecation warnings.
|
||||
* @author Toru Nagashima <http://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Defitions for deprecation warnings.
|
||||
const deprecationWarningMessages = {
|
||||
ESLINT_LEGACY_ECMAFEATURES:
|
||||
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
|
||||
ESLINT_PERSONAL_CONFIG_LOAD:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please use a config file per project or the '--config' option.",
|
||||
ESLINT_PERSONAL_CONFIG_SUPPRESS:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please remove it or add 'root:true' to the config files in your " +
|
||||
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
|
||||
};
|
||||
|
||||
const sourceFileErrorCache = new Set();
|
||||
|
||||
/**
|
||||
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
|
||||
* for each unique file path, but repeated invocations with the same file path have no effect.
|
||||
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
|
||||
* @param {string} source The name of the configuration source to report the warning for.
|
||||
* @param {string} errorCode The warning message to show.
|
||||
* @returns {void}
|
||||
*/
|
||||
function emitDeprecationWarning(source, errorCode) {
|
||||
const cacheKey = JSON.stringify({ source, errorCode });
|
||||
|
||||
if (sourceFileErrorCache.has(cacheKey)) {
|
||||
return;
|
||||
}
|
||||
sourceFileErrorCache.add(cacheKey);
|
||||
|
||||
const rel = path__default["default"].relative(process.cwd(), source);
|
||||
const message = deprecationWarningMessages[errorCode];
|
||||
|
||||
process.emitWarning(
|
||||
`${message} (found in "${rel}")`,
|
||||
"DeprecationWarning",
|
||||
errorCode
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview The instance of Ajv validator.
|
||||
* @author Evgeny Poberezkin
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* Copied from ajv/lib/refs/json-schema-draft-04.json
|
||||
* The MIT License (MIT)
|
||||
* Copyright (c) 2015-2017 Evgeny Poberezkin
|
||||
*/
|
||||
const metaSchema = {
|
||||
id: "http://json-schema.org/draft-04/schema#",
|
||||
$schema: "http://json-schema.org/draft-04/schema#",
|
||||
description: "Core schema meta-schema",
|
||||
definitions: {
|
||||
schemaArray: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
items: { $ref: "#" }
|
||||
},
|
||||
positiveInteger: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
},
|
||||
positiveIntegerDefault0: {
|
||||
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
|
||||
},
|
||||
simpleTypes: {
|
||||
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
stringArray: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
},
|
||||
type: "object",
|
||||
properties: {
|
||||
id: {
|
||||
type: "string"
|
||||
},
|
||||
$schema: {
|
||||
type: "string"
|
||||
},
|
||||
title: {
|
||||
type: "string"
|
||||
},
|
||||
description: {
|
||||
type: "string"
|
||||
},
|
||||
default: { },
|
||||
multipleOf: {
|
||||
type: "number",
|
||||
minimum: 0,
|
||||
exclusiveMinimum: true
|
||||
},
|
||||
maximum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMaximum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
minimum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMinimum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxLength: { $ref: "#/definitions/positiveInteger" },
|
||||
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
pattern: {
|
||||
type: "string",
|
||||
format: "regex"
|
||||
},
|
||||
additionalItems: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
items: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/schemaArray" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
maxItems: { $ref: "#/definitions/positiveInteger" },
|
||||
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
uniqueItems: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxProperties: { $ref: "#/definitions/positiveInteger" },
|
||||
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
required: { $ref: "#/definitions/stringArray" },
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
definitions: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
properties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
patternProperties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
dependencies: {
|
||||
type: "object",
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/stringArray" }
|
||||
]
|
||||
}
|
||||
},
|
||||
enum: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
},
|
||||
type: {
|
||||
anyOf: [
|
||||
{ $ref: "#/definitions/simpleTypes" },
|
||||
{
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/simpleTypes" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
]
|
||||
},
|
||||
format: { type: "string" },
|
||||
allOf: { $ref: "#/definitions/schemaArray" },
|
||||
anyOf: { $ref: "#/definitions/schemaArray" },
|
||||
oneOf: { $ref: "#/definitions/schemaArray" },
|
||||
not: { $ref: "#" }
|
||||
},
|
||||
dependencies: {
|
||||
exclusiveMaximum: ["maximum"],
|
||||
exclusiveMinimum: ["minimum"]
|
||||
},
|
||||
default: { }
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var ajvOrig = (additionalOptions = {}) => {
|
||||
const ajv = new Ajv__default["default"]({
|
||||
meta: false,
|
||||
useDefaults: true,
|
||||
validateSchema: false,
|
||||
missingRefs: "ignore",
|
||||
verbose: true,
|
||||
schemaId: "auto",
|
||||
...additionalOptions
|
||||
});
|
||||
|
||||
ajv.addMetaSchema(metaSchema);
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
ajv._opts.defaultMeta = metaSchema.id;
|
||||
|
||||
return ajv;
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Defines a schema for configs.
|
||||
* @author Sylvan Mably
|
||||
*/
|
||||
|
||||
const baseConfigProperties = {
|
||||
$schema: { type: "string" },
|
||||
env: { type: "object" },
|
||||
extends: { $ref: "#/definitions/stringOrStrings" },
|
||||
globals: { type: "object" },
|
||||
overrides: {
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/overrideConfig" },
|
||||
additionalItems: false
|
||||
},
|
||||
parser: { type: ["string", "null"] },
|
||||
parserOptions: { type: "object" },
|
||||
plugins: { type: "array" },
|
||||
processor: { type: "string" },
|
||||
rules: { type: "object" },
|
||||
settings: { type: "object" },
|
||||
noInlineConfig: { type: "boolean" },
|
||||
reportUnusedDisableDirectives: { type: "boolean" },
|
||||
|
||||
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
|
||||
};
|
||||
|
||||
const configSchema = {
|
||||
definitions: {
|
||||
stringOrStrings: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false
|
||||
}
|
||||
]
|
||||
},
|
||||
stringOrStringsRequired: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false,
|
||||
minItems: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// Config at top-level.
|
||||
objectConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
root: { type: "boolean" },
|
||||
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
|
||||
// Config in `overrides`.
|
||||
overrideConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
|
||||
files: { $ref: "#/definitions/stringOrStringsRequired" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
required: ["files"],
|
||||
additionalProperties: false
|
||||
}
|
||||
},
|
||||
|
||||
$ref: "#/definitions/objectConfig"
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Defines environment settings and globals.
|
||||
* @author Elan Shanker
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the object that has difference.
|
||||
* @param {Record<string,boolean>} current The newer object.
|
||||
* @param {Record<string,boolean>} prev The older object.
|
||||
* @returns {Record<string,boolean>} The difference object.
|
||||
*/
|
||||
function getDiff(current, prev) {
|
||||
const retv = {};
|
||||
|
||||
for (const [key, value] of Object.entries(current)) {
|
||||
if (!Object.hasOwnProperty.call(prev, key)) {
|
||||
retv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return retv;
|
||||
}
|
||||
|
||||
const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
|
||||
const newGlobals2017 = {
|
||||
Atomics: false,
|
||||
SharedArrayBuffer: false
|
||||
};
|
||||
const newGlobals2020 = {
|
||||
BigInt: false,
|
||||
BigInt64Array: false,
|
||||
BigUint64Array: false,
|
||||
globalThis: false
|
||||
};
|
||||
|
||||
const newGlobals2021 = {
|
||||
AggregateError: false,
|
||||
FinalizationRegistry: false,
|
||||
WeakRef: false
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {Map<string, import("../lib/shared/types").Environment>} */
|
||||
var environments = new Map(Object.entries({
|
||||
|
||||
// Language
|
||||
builtin: {
|
||||
globals: globals__default["default"].es5
|
||||
},
|
||||
es6: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2015: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2016: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 7
|
||||
}
|
||||
},
|
||||
es2017: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 8
|
||||
}
|
||||
},
|
||||
es2018: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 9
|
||||
}
|
||||
},
|
||||
es2019: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 10
|
||||
}
|
||||
},
|
||||
es2020: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 11
|
||||
}
|
||||
},
|
||||
es2021: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 12
|
||||
}
|
||||
},
|
||||
es2022: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 13
|
||||
}
|
||||
},
|
||||
es2023: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 14
|
||||
}
|
||||
},
|
||||
es2024: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 15
|
||||
}
|
||||
},
|
||||
|
||||
// Platforms
|
||||
browser: {
|
||||
globals: globals__default["default"].browser
|
||||
},
|
||||
node: {
|
||||
globals: globals__default["default"].node,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
"shared-node-browser": {
|
||||
globals: globals__default["default"]["shared-node-browser"]
|
||||
},
|
||||
worker: {
|
||||
globals: globals__default["default"].worker
|
||||
},
|
||||
serviceworker: {
|
||||
globals: globals__default["default"].serviceworker
|
||||
},
|
||||
|
||||
// Frameworks
|
||||
commonjs: {
|
||||
globals: globals__default["default"].commonjs,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
amd: {
|
||||
globals: globals__default["default"].amd
|
||||
},
|
||||
mocha: {
|
||||
globals: globals__default["default"].mocha
|
||||
},
|
||||
jasmine: {
|
||||
globals: globals__default["default"].jasmine
|
||||
},
|
||||
jest: {
|
||||
globals: globals__default["default"].jest
|
||||
},
|
||||
phantomjs: {
|
||||
globals: globals__default["default"].phantomjs
|
||||
},
|
||||
jquery: {
|
||||
globals: globals__default["default"].jquery
|
||||
},
|
||||
qunit: {
|
||||
globals: globals__default["default"].qunit
|
||||
},
|
||||
prototypejs: {
|
||||
globals: globals__default["default"].prototypejs
|
||||
},
|
||||
shelljs: {
|
||||
globals: globals__default["default"].shelljs
|
||||
},
|
||||
meteor: {
|
||||
globals: globals__default["default"].meteor
|
||||
},
|
||||
mongo: {
|
||||
globals: globals__default["default"].mongo
|
||||
},
|
||||
protractor: {
|
||||
globals: globals__default["default"].protractor
|
||||
},
|
||||
applescript: {
|
||||
globals: globals__default["default"].applescript
|
||||
},
|
||||
nashorn: {
|
||||
globals: globals__default["default"].nashorn
|
||||
},
|
||||
atomtest: {
|
||||
globals: globals__default["default"].atomtest
|
||||
},
|
||||
embertest: {
|
||||
globals: globals__default["default"].embertest
|
||||
},
|
||||
webextensions: {
|
||||
globals: globals__default["default"].webextensions
|
||||
},
|
||||
greasemonkey: {
|
||||
globals: globals__default["default"].greasemonkey
|
||||
}
|
||||
}));
|
||||
|
||||
/**
|
||||
* @fileoverview Validates configs.
|
||||
* @author Brandon Mills
|
||||
*/
|
||||
|
||||
const ajv = ajvOrig();
|
||||
|
||||
const ruleValidators = new WeakMap();
|
||||
const noop = Function.prototype;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
let validateSchema;
|
||||
const severityMap = {
|
||||
error: 2,
|
||||
warn: 1,
|
||||
off: 0
|
||||
};
|
||||
|
||||
const validated = new WeakSet();
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
class ConfigValidator {
|
||||
constructor({ builtInRules = new Map() } = {}) {
|
||||
this.builtInRules = builtInRules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a complete options schema for a rule.
|
||||
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
|
||||
* @returns {Object} JSON Schema for the rule's options.
|
||||
*/
|
||||
getRuleOptionsSchema(rule) {
|
||||
if (!rule) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const schema = rule.schema || rule.meta && rule.meta.schema;
|
||||
|
||||
// Given a tuple of schemas, insert warning level at the beginning
|
||||
if (Array.isArray(schema)) {
|
||||
if (schema.length) {
|
||||
return {
|
||||
type: "array",
|
||||
items: schema,
|
||||
minItems: 0,
|
||||
maxItems: schema.length
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "array",
|
||||
minItems: 0,
|
||||
maxItems: 0
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// Given a full schema, leave it alone
|
||||
return schema || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
|
||||
* @param {options} options The given options for the rule.
|
||||
* @returns {number|string} The rule's severity value
|
||||
*/
|
||||
validateRuleSeverity(options) {
|
||||
const severity = Array.isArray(options) ? options[0] : options;
|
||||
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
|
||||
|
||||
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
|
||||
return normSeverity;
|
||||
}
|
||||
|
||||
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the non-severity options passed to a rule, based on its schema.
|
||||
* @param {{create: Function}} rule The rule to validate
|
||||
* @param {Array} localOptions The options for the rule, excluding severity
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleSchema(rule, localOptions) {
|
||||
if (!ruleValidators.has(rule)) {
|
||||
const schema = this.getRuleOptionsSchema(rule);
|
||||
|
||||
if (schema) {
|
||||
ruleValidators.set(rule, ajv.compile(schema));
|
||||
}
|
||||
}
|
||||
|
||||
const validateRule = ruleValidators.get(rule);
|
||||
|
||||
if (validateRule) {
|
||||
validateRule(localOptions);
|
||||
if (validateRule.errors) {
|
||||
throw new Error(validateRule.errors.map(
|
||||
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
|
||||
).join(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's options against its schema.
|
||||
* @param {{create: Function}|null} rule The rule that the config is being validated for
|
||||
* @param {string} ruleId The rule's unique name.
|
||||
* @param {Array|number} options The given options for the rule.
|
||||
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
|
||||
* no source is prepended to the message.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleOptions(rule, ruleId, options, source = null) {
|
||||
try {
|
||||
const severity = this.validateRuleSeverity(options);
|
||||
|
||||
if (severity !== 0) {
|
||||
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
|
||||
}
|
||||
} catch (err) {
|
||||
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
|
||||
|
||||
if (typeof source === "string") {
|
||||
throw new Error(`${source}:\n\t${enhancedMessage}`);
|
||||
} else {
|
||||
throw new Error(enhancedMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an environment object
|
||||
* @param {Object} environment The environment config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateEnvironment(
|
||||
environment,
|
||||
source,
|
||||
getAdditionalEnv = noop
|
||||
) {
|
||||
|
||||
// not having an environment is ok
|
||||
if (!environment) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(environment).forEach(id => {
|
||||
const env = getAdditionalEnv(id) || environments.get(id) || null;
|
||||
|
||||
if (!env) {
|
||||
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
|
||||
|
||||
throw new Error(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rules config object
|
||||
* @param {Object} rulesConfig The rules config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRules(
|
||||
rulesConfig,
|
||||
source,
|
||||
getAdditionalRule = noop
|
||||
) {
|
||||
if (!rulesConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(rulesConfig).forEach(id => {
|
||||
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
|
||||
|
||||
this.validateRuleOptions(rule, id, rulesConfig[id], source);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a `globals` section of a config file
|
||||
* @param {Object} globalsConfig The `globals` section
|
||||
* @param {string|null} source The name of the configuration source to report in the event of an error.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateGlobals(globalsConfig, source = null) {
|
||||
if (!globalsConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.entries(globalsConfig)
|
||||
.forEach(([configuredGlobal, configuredValue]) => {
|
||||
try {
|
||||
normalizeConfigGlobal(configuredValue);
|
||||
} catch (err) {
|
||||
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate `processor` configuration.
|
||||
* @param {string|undefined} processorName The processor name.
|
||||
* @param {string} source The name of config file.
|
||||
* @param {function(id:string): Processor} getProcessor The getter of defined processors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateProcessor(processorName, source, getProcessor) {
|
||||
if (processorName && !getProcessor(processorName)) {
|
||||
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats an array of schema validation errors.
|
||||
* @param {Array} errors An array of error messages to format.
|
||||
* @returns {string} Formatted error message
|
||||
*/
|
||||
formatErrors(errors) {
|
||||
return errors.map(error => {
|
||||
if (error.keyword === "additionalProperties") {
|
||||
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
|
||||
|
||||
return `Unexpected top-level property "${formattedPropertyPath}"`;
|
||||
}
|
||||
if (error.keyword === "type") {
|
||||
const formattedField = error.dataPath.slice(1);
|
||||
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
|
||||
const formattedValue = JSON.stringify(error.data);
|
||||
|
||||
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
|
||||
}
|
||||
|
||||
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
|
||||
|
||||
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
|
||||
}).map(message => `\t- ${message}.\n`).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the top level properties of the config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigSchema(config, source = null) {
|
||||
validateSchema = validateSchema || ajv.compile(configSchema);
|
||||
|
||||
if (!validateSchema(config)) {
|
||||
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
|
||||
}
|
||||
|
||||
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
|
||||
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an entire config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
|
||||
* @returns {void}
|
||||
*/
|
||||
validate(config, source, getAdditionalRule, getAdditionalEnv) {
|
||||
this.validateConfigSchema(config, source);
|
||||
this.validateRules(config.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(config.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
|
||||
for (const override of config.overrides || []) {
|
||||
this.validateRules(override.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(override.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate config array object.
|
||||
* @param {ConfigArray} configArray The config array to validate.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigArray(configArray) {
|
||||
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
|
||||
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
|
||||
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
|
||||
|
||||
// Validate.
|
||||
for (const element of configArray) {
|
||||
if (validated.has(element)) {
|
||||
continue;
|
||||
}
|
||||
validated.add(element);
|
||||
|
||||
this.validateEnvironment(element.env, element.name, getPluginEnv);
|
||||
this.validateGlobals(element.globals, element.name);
|
||||
this.validateProcessor(element.processor, element.name, getPluginProcessor);
|
||||
this.validateRules(element.rules, element.name, getPluginRule);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview Common helpers for naming of plugins, formatters and configs
|
||||
*/
|
||||
|
||||
const NAMESPACE_REGEX = /^@.*\//iu;
|
||||
|
||||
/**
|
||||
* Brings package name to correct format based on prefix
|
||||
* @param {string} name The name of the package.
|
||||
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
|
||||
* @returns {string} Normalized name of the package
|
||||
* @private
|
||||
*/
|
||||
function normalizePackageName(name, prefix) {
|
||||
let normalizedName = name;
|
||||
|
||||
/**
|
||||
* On Windows, name can come in with Windows slashes instead of Unix slashes.
|
||||
* Normalize to Unix first to avoid errors later on.
|
||||
* https://github.com/eslint/eslint/issues/5644
|
||||
*/
|
||||
if (normalizedName.includes("\\")) {
|
||||
normalizedName = normalizedName.replace(/\\/gu, "/");
|
||||
}
|
||||
|
||||
if (normalizedName.charAt(0) === "@") {
|
||||
|
||||
/**
|
||||
* it's a scoped package
|
||||
* package name is the prefix, or just a username
|
||||
*/
|
||||
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
|
||||
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
|
||||
|
||||
if (scopedPackageShortcutRegex.test(normalizedName)) {
|
||||
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
|
||||
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
|
||||
|
||||
/**
|
||||
* for scoped packages, insert the prefix after the first / unless
|
||||
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
|
||||
*/
|
||||
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
|
||||
}
|
||||
} else if (!normalizedName.startsWith(`${prefix}-`)) {
|
||||
normalizedName = `${prefix}-${normalizedName}`;
|
||||
}
|
||||
|
||||
return normalizedName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the prefix from a fullname.
|
||||
* @param {string} fullname The term which may have the prefix.
|
||||
* @param {string} prefix The prefix to remove.
|
||||
* @returns {string} The term without prefix.
|
||||
*/
|
||||
function getShorthandName(fullname, prefix) {
|
||||
if (fullname[0] === "@") {
|
||||
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
|
||||
|
||||
if (matchResult) {
|
||||
return matchResult[1];
|
||||
}
|
||||
|
||||
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
|
||||
if (matchResult) {
|
||||
return `${matchResult[1]}/${matchResult[2]}`;
|
||||
}
|
||||
} else if (fullname.startsWith(`${prefix}-`)) {
|
||||
return fullname.slice(prefix.length + 1);
|
||||
}
|
||||
|
||||
return fullname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the scope (namespace) of a term.
|
||||
* @param {string} term The term which may have the namespace.
|
||||
* @returns {string} The namespace of the term if it has one.
|
||||
*/
|
||||
function getNamespaceFromTerm(term) {
|
||||
const match = term.match(NAMESPACE_REGEX);
|
||||
|
||||
return match ? match[0] : "";
|
||||
}
|
||||
|
||||
var naming = {
|
||||
__proto__: null,
|
||||
normalizePackageName: normalizePackageName,
|
||||
getShorthandName: getShorthandName,
|
||||
getNamespaceFromTerm: getNamespaceFromTerm
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Package exports for @eslint/eslintrc
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const Legacy = {
|
||||
environments,
|
||||
|
||||
// shared
|
||||
ConfigOps,
|
||||
ConfigValidator,
|
||||
naming
|
||||
};
|
||||
|
||||
exports.Legacy = Legacy;
|
||||
//# sourceMappingURL=eslintrc-universal.cjs.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+4344
@@ -0,0 +1,4344 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var debugOrig = require('debug');
|
||||
var fs = require('fs');
|
||||
var importFresh = require('import-fresh');
|
||||
var Module = require('module');
|
||||
var path = require('path');
|
||||
var stripComments = require('strip-json-comments');
|
||||
var assert = require('assert');
|
||||
var ignore = require('ignore');
|
||||
var util = require('util');
|
||||
var minimatch = require('minimatch');
|
||||
var Ajv = require('ajv');
|
||||
var globals = require('globals');
|
||||
var os = require('os');
|
||||
|
||||
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
||||
|
||||
var debugOrig__default = /*#__PURE__*/_interopDefaultLegacy(debugOrig);
|
||||
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
||||
var importFresh__default = /*#__PURE__*/_interopDefaultLegacy(importFresh);
|
||||
var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
|
||||
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
||||
var stripComments__default = /*#__PURE__*/_interopDefaultLegacy(stripComments);
|
||||
var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
|
||||
var ignore__default = /*#__PURE__*/_interopDefaultLegacy(ignore);
|
||||
var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
|
||||
var minimatch__default = /*#__PURE__*/_interopDefaultLegacy(minimatch);
|
||||
var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
|
||||
var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals);
|
||||
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
|
||||
|
||||
/**
|
||||
* @fileoverview `IgnorePattern` class.
|
||||
*
|
||||
* `IgnorePattern` class has the set of glob patterns and the base path.
|
||||
*
|
||||
* It provides two static methods.
|
||||
*
|
||||
* - `IgnorePattern.createDefaultIgnore(cwd)`
|
||||
* Create the default predicate function.
|
||||
* - `IgnorePattern.createIgnore(ignorePatterns)`
|
||||
* Create the predicate function from multiple `IgnorePattern` objects.
|
||||
*
|
||||
* It provides two properties and a method.
|
||||
*
|
||||
* - `patterns`
|
||||
* The glob patterns that ignore to lint.
|
||||
* - `basePath`
|
||||
* The base path of the glob patterns. If absolute paths existed in the
|
||||
* glob patterns, those are handled as relative paths to the base path.
|
||||
* - `getPatternsRelativeTo(basePath)`
|
||||
* Get `patterns` as modified for a given base path. It modifies the
|
||||
* absolute paths in the patterns as prepending the difference of two base
|
||||
* paths.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
|
||||
* `ignorePatterns` properties.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
const debug$3 = debugOrig__default["default"]("eslintrc:ignore-pattern");
|
||||
|
||||
/** @typedef {ReturnType<import("ignore").default>} Ignore */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the path to the common ancestor directory of given paths.
|
||||
* @param {string[]} sourcePaths The paths to calculate the common ancestor.
|
||||
* @returns {string} The path to the common ancestor directory.
|
||||
*/
|
||||
function getCommonAncestorPath(sourcePaths) {
|
||||
let result = sourcePaths[0];
|
||||
|
||||
for (let i = 1; i < sourcePaths.length; ++i) {
|
||||
const a = result;
|
||||
const b = sourcePaths[i];
|
||||
|
||||
// Set the shorter one (it's the common ancestor if one includes the other).
|
||||
result = a.length < b.length ? a : b;
|
||||
|
||||
// Set the common ancestor.
|
||||
for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
|
||||
if (a[j] !== b[j]) {
|
||||
result = a.slice(0, lastSepPos);
|
||||
break;
|
||||
}
|
||||
if (a[j] === path__default["default"].sep) {
|
||||
lastSepPos = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resolvedResult = result || path__default["default"].sep;
|
||||
|
||||
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
|
||||
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
|
||||
resolvedResult += path__default["default"].sep;
|
||||
}
|
||||
return resolvedResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make relative path.
|
||||
* @param {string} from The source path to get relative path.
|
||||
* @param {string} to The destination path to get relative path.
|
||||
* @returns {string} The relative path.
|
||||
*/
|
||||
function relative(from, to) {
|
||||
const relPath = path__default["default"].relative(from, to);
|
||||
|
||||
if (path__default["default"].sep === "/") {
|
||||
return relPath;
|
||||
}
|
||||
return relPath.split(path__default["default"].sep).join("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the trailing slash if existed.
|
||||
* @param {string} filePath The path to check.
|
||||
* @returns {string} The trailing slash if existed.
|
||||
*/
|
||||
function dirSuffix(filePath) {
|
||||
const isDir = (
|
||||
filePath.endsWith(path__default["default"].sep) ||
|
||||
(process.platform === "win32" && filePath.endsWith("/"))
|
||||
);
|
||||
|
||||
return isDir ? "/" : "";
|
||||
}
|
||||
|
||||
const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
|
||||
const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
class IgnorePattern {
|
||||
|
||||
/**
|
||||
* The default patterns.
|
||||
* @type {string[]}
|
||||
*/
|
||||
static get DefaultPatterns() {
|
||||
return DefaultPatterns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the default predicate function.
|
||||
* @param {string} cwd The current working directory.
|
||||
* @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
|
||||
* The preficate function.
|
||||
* The first argument is an absolute path that is checked.
|
||||
* The second argument is the flag to not ignore dotfiles.
|
||||
* If the predicate function returned `true`, it means the path should be ignored.
|
||||
*/
|
||||
static createDefaultIgnore(cwd) {
|
||||
return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the predicate function from multiple `IgnorePattern` objects.
|
||||
* @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
|
||||
* @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
|
||||
* The preficate function.
|
||||
* The first argument is an absolute path that is checked.
|
||||
* The second argument is the flag to not ignore dotfiles.
|
||||
* If the predicate function returned `true`, it means the path should be ignored.
|
||||
*/
|
||||
static createIgnore(ignorePatterns) {
|
||||
debug$3("Create with: %o", ignorePatterns);
|
||||
|
||||
const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
|
||||
const patterns = [].concat(
|
||||
...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
|
||||
);
|
||||
const ig = ignore__default["default"]({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
|
||||
const dotIg = ignore__default["default"]({ allowRelativePaths: true }).add(patterns);
|
||||
|
||||
debug$3(" processed: %o", { basePath, patterns });
|
||||
|
||||
return Object.assign(
|
||||
(filePath, dot = false) => {
|
||||
assert__default["default"](path__default["default"].isAbsolute(filePath), "'filePath' should be an absolute path.");
|
||||
const relPathRaw = relative(basePath, filePath);
|
||||
const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
|
||||
const adoptedIg = dot ? dotIg : ig;
|
||||
const result = relPath !== "" && adoptedIg.ignores(relPath);
|
||||
|
||||
debug$3("Check", { filePath, dot, relativePath: relPath, result });
|
||||
return result;
|
||||
},
|
||||
{ basePath, patterns }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a new `IgnorePattern` instance.
|
||||
* @param {string[]} patterns The glob patterns that ignore to lint.
|
||||
* @param {string} basePath The base path of `patterns`.
|
||||
*/
|
||||
constructor(patterns, basePath) {
|
||||
assert__default["default"](path__default["default"].isAbsolute(basePath), "'basePath' should be an absolute path.");
|
||||
|
||||
/**
|
||||
* The glob patterns that ignore to lint.
|
||||
* @type {string[]}
|
||||
*/
|
||||
this.patterns = patterns;
|
||||
|
||||
/**
|
||||
* The base path of `patterns`.
|
||||
* @type {string}
|
||||
*/
|
||||
this.basePath = basePath;
|
||||
|
||||
/**
|
||||
* If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
|
||||
*
|
||||
* It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
|
||||
* It's `false` as-is for `ignorePatterns` property in config files.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.loose = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get `patterns` as modified for a given base path. It modifies the
|
||||
* absolute paths in the patterns as prepending the difference of two base
|
||||
* paths.
|
||||
* @param {string} newBasePath The base path.
|
||||
* @returns {string[]} Modifired patterns.
|
||||
*/
|
||||
getPatternsRelativeTo(newBasePath) {
|
||||
assert__default["default"](path__default["default"].isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
|
||||
const { basePath, loose, patterns } = this;
|
||||
|
||||
if (newBasePath === basePath) {
|
||||
return patterns;
|
||||
}
|
||||
const prefix = `/${relative(newBasePath, basePath)}`;
|
||||
|
||||
return patterns.map(pattern => {
|
||||
const negative = pattern.startsWith("!");
|
||||
const head = negative ? "!" : "";
|
||||
const body = negative ? pattern.slice(1) : pattern;
|
||||
|
||||
if (body.startsWith("/") || body.startsWith("../")) {
|
||||
return `${head}${prefix}${body}`;
|
||||
}
|
||||
return loose ? pattern : `${head}${prefix}/**/${body}`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `ExtractedConfig` class.
|
||||
*
|
||||
* `ExtractedConfig` class expresses a final configuration for a specific file.
|
||||
*
|
||||
* It provides one method.
|
||||
*
|
||||
* - `toCompatibleObjectAsConfigFileContent()`
|
||||
* Convert this configuration to the compatible object as the content of
|
||||
* config files. It converts the loaded parser and plugins to strings.
|
||||
* `CLIEngine#getConfigForFile(filePath)` method uses this method.
|
||||
*
|
||||
* `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
// For VSCode intellisense
|
||||
/** @typedef {import("../../shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
|
||||
/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
|
||||
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
|
||||
|
||||
/**
|
||||
* Check if `xs` starts with `ys`.
|
||||
* @template T
|
||||
* @param {T[]} xs The array to check.
|
||||
* @param {T[]} ys The array that may be the first part of `xs`.
|
||||
* @returns {boolean} `true` if `xs` starts with `ys`.
|
||||
*/
|
||||
function startsWith(xs, ys) {
|
||||
return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The class for extracted config data.
|
||||
*/
|
||||
class ExtractedConfig {
|
||||
constructor() {
|
||||
|
||||
/**
|
||||
* The config name what `noInlineConfig` setting came from.
|
||||
* @type {string}
|
||||
*/
|
||||
this.configNameOfNoInlineConfig = "";
|
||||
|
||||
/**
|
||||
* Environments.
|
||||
* @type {Record<string, boolean>}
|
||||
*/
|
||||
this.env = {};
|
||||
|
||||
/**
|
||||
* Global variables.
|
||||
* @type {Record<string, GlobalConf>}
|
||||
*/
|
||||
this.globals = {};
|
||||
|
||||
/**
|
||||
* The glob patterns that ignore to lint.
|
||||
* @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
|
||||
*/
|
||||
this.ignores = void 0;
|
||||
|
||||
/**
|
||||
* The flag that disables directive comments.
|
||||
* @type {boolean|undefined}
|
||||
*/
|
||||
this.noInlineConfig = void 0;
|
||||
|
||||
/**
|
||||
* Parser definition.
|
||||
* @type {DependentParser|null}
|
||||
*/
|
||||
this.parser = null;
|
||||
|
||||
/**
|
||||
* Options for the parser.
|
||||
* @type {Object}
|
||||
*/
|
||||
this.parserOptions = {};
|
||||
|
||||
/**
|
||||
* Plugin definitions.
|
||||
* @type {Record<string, DependentPlugin>}
|
||||
*/
|
||||
this.plugins = {};
|
||||
|
||||
/**
|
||||
* Processor ID.
|
||||
* @type {string|null}
|
||||
*/
|
||||
this.processor = null;
|
||||
|
||||
/**
|
||||
* The flag that reports unused `eslint-disable` directive comments.
|
||||
* @type {boolean|undefined}
|
||||
*/
|
||||
this.reportUnusedDisableDirectives = void 0;
|
||||
|
||||
/**
|
||||
* Rule settings.
|
||||
* @type {Record<string, [SeverityConf, ...any[]]>}
|
||||
*/
|
||||
this.rules = {};
|
||||
|
||||
/**
|
||||
* Shared settings.
|
||||
* @type {Object}
|
||||
*/
|
||||
this.settings = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert this config to the compatible object as a config file content.
|
||||
* @returns {ConfigData} The converted object.
|
||||
*/
|
||||
toCompatibleObjectAsConfigFileContent() {
|
||||
const {
|
||||
/* eslint-disable no-unused-vars */
|
||||
configNameOfNoInlineConfig: _ignore1,
|
||||
processor: _ignore2,
|
||||
/* eslint-enable no-unused-vars */
|
||||
ignores,
|
||||
...config
|
||||
} = this;
|
||||
|
||||
config.parser = config.parser && config.parser.filePath;
|
||||
config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
|
||||
config.ignorePatterns = ignores ? ignores.patterns : [];
|
||||
|
||||
// Strip the default patterns from `ignorePatterns`.
|
||||
if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
|
||||
config.ignorePatterns =
|
||||
config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `ConfigArray` class.
|
||||
*
|
||||
* `ConfigArray` class expresses the full of a configuration. It has the entry
|
||||
* config file, base config files that were extended, loaded parsers, and loaded
|
||||
* plugins.
|
||||
*
|
||||
* `ConfigArray` class provides three properties and two methods.
|
||||
*
|
||||
* - `pluginEnvironments`
|
||||
* - `pluginProcessors`
|
||||
* - `pluginRules`
|
||||
* The `Map` objects that contain the members of all plugins that this
|
||||
* config array contains. Those map objects don't have mutation methods.
|
||||
* Those keys are the member ID such as `pluginId/memberName`.
|
||||
* - `isRoot()`
|
||||
* If `true` then this configuration has `root:true` property.
|
||||
* - `extractConfig(filePath)`
|
||||
* Extract the final configuration for a given file. This means merging
|
||||
* every config array element which that `criteria` property matched. The
|
||||
* `filePath` argument must be an absolute path.
|
||||
*
|
||||
* `ConfigArrayFactory` provides the loading logic of config files.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("../../shared/types").Environment} Environment */
|
||||
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
|
||||
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
|
||||
/** @typedef {import("../../shared/types").Rule} Rule */
|
||||
/** @typedef {import("../../shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("../../shared/types").Processor} Processor */
|
||||
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
|
||||
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayElement
|
||||
* @property {string} name The name of this config element.
|
||||
* @property {string} filePath The path to the source file of this config element.
|
||||
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
|
||||
* @property {Record<string, boolean>|undefined} env The environment settings.
|
||||
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
|
||||
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
|
||||
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
|
||||
* @property {DependentParser|undefined} parser The parser loader.
|
||||
* @property {Object|undefined} parserOptions The parser options.
|
||||
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
|
||||
* @property {string|undefined} processor The processor name to refer plugin's processor.
|
||||
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
|
||||
* @property {boolean|undefined} root The flag to express root.
|
||||
* @property {Record<string, RuleConf>|undefined} rules The rule settings
|
||||
* @property {Object|undefined} settings The shared settings.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayInternalSlots
|
||||
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
|
||||
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
|
||||
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
|
||||
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
|
||||
const internalSlotsMap$2 = new class extends WeakMap {
|
||||
get(key) {
|
||||
let value = super.get(key);
|
||||
|
||||
if (!value) {
|
||||
value = {
|
||||
cache: new Map(),
|
||||
envMap: null,
|
||||
processorMap: null,
|
||||
ruleMap: null
|
||||
};
|
||||
super.set(key, value);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}();
|
||||
|
||||
/**
|
||||
* Get the indices which are matched to a given file.
|
||||
* @param {ConfigArrayElement[]} elements The elements.
|
||||
* @param {string} filePath The path to a target file.
|
||||
* @returns {number[]} The indices.
|
||||
*/
|
||||
function getMatchedIndices(elements, filePath) {
|
||||
const indices = [];
|
||||
|
||||
for (let i = elements.length - 1; i >= 0; --i) {
|
||||
const element = elements[i];
|
||||
|
||||
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
|
||||
indices.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
return indices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a non-null object.
|
||||
* @param {any} x The value to check.
|
||||
* @returns {boolean} `true` if the value is a non-null object.
|
||||
*/
|
||||
function isNonNullObject(x) {
|
||||
return typeof x === "object" && x !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two objects.
|
||||
*
|
||||
* Assign every property values of `y` to `x` if `x` doesn't have the property.
|
||||
* If `x`'s property value is an object, it does recursive.
|
||||
* @param {Object} target The destination to merge
|
||||
* @param {Object|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergeWithoutOverwrite(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isNonNullObject(target[key])) {
|
||||
mergeWithoutOverwrite(target[key], source[key]);
|
||||
} else if (target[key] === void 0) {
|
||||
if (isNonNullObject(source[key])) {
|
||||
target[key] = Array.isArray(source[key]) ? [] : {};
|
||||
mergeWithoutOverwrite(target[key], source[key]);
|
||||
} else if (source[key] !== void 0) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The error for plugin conflicts.
|
||||
*/
|
||||
class PluginConflictError extends Error {
|
||||
|
||||
/**
|
||||
* Initialize this error object.
|
||||
* @param {string} pluginId The plugin ID.
|
||||
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
|
||||
*/
|
||||
constructor(pluginId, plugins) {
|
||||
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
|
||||
this.messageTemplate = "plugin-conflict";
|
||||
this.messageData = { pluginId, plugins };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge plugins.
|
||||
* `target`'s definition is prior to `source`'s.
|
||||
* @param {Record<string, DependentPlugin>} target The destination to merge
|
||||
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergePlugins(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
const targetValue = target[key];
|
||||
const sourceValue = source[key];
|
||||
|
||||
// Adopt the plugin which was found at first.
|
||||
if (targetValue === void 0) {
|
||||
if (sourceValue.error) {
|
||||
throw sourceValue.error;
|
||||
}
|
||||
target[key] = sourceValue;
|
||||
} else if (sourceValue.filePath !== targetValue.filePath) {
|
||||
throw new PluginConflictError(key, [
|
||||
{
|
||||
filePath: targetValue.filePath,
|
||||
importerName: targetValue.importerName
|
||||
},
|
||||
{
|
||||
filePath: sourceValue.filePath,
|
||||
importerName: sourceValue.importerName
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge rule configs.
|
||||
* `target`'s definition is prior to `source`'s.
|
||||
* @param {Record<string, Array>} target The destination to merge
|
||||
* @param {Record<string, RuleConf>|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergeRuleConfigs(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
const targetDef = target[key];
|
||||
const sourceDef = source[key];
|
||||
|
||||
// Adopt the rule config which was found at first.
|
||||
if (targetDef === void 0) {
|
||||
if (Array.isArray(sourceDef)) {
|
||||
target[key] = [...sourceDef];
|
||||
} else {
|
||||
target[key] = [sourceDef];
|
||||
}
|
||||
|
||||
/*
|
||||
* If the first found rule config is severity only and the current rule
|
||||
* config has options, merge the severity and the options.
|
||||
*/
|
||||
} else if (
|
||||
targetDef.length === 1 &&
|
||||
Array.isArray(sourceDef) &&
|
||||
sourceDef.length >= 2
|
||||
) {
|
||||
targetDef.push(...sourceDef.slice(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the extracted config.
|
||||
* @param {ConfigArray} instance The config elements.
|
||||
* @param {number[]} indices The indices to use.
|
||||
* @returns {ExtractedConfig} The extracted config.
|
||||
*/
|
||||
function createConfig(instance, indices) {
|
||||
const config = new ExtractedConfig();
|
||||
const ignorePatterns = [];
|
||||
|
||||
// Merge elements.
|
||||
for (const index of indices) {
|
||||
const element = instance[index];
|
||||
|
||||
// Adopt the parser which was found at first.
|
||||
if (!config.parser && element.parser) {
|
||||
if (element.parser.error) {
|
||||
throw element.parser.error;
|
||||
}
|
||||
config.parser = element.parser;
|
||||
}
|
||||
|
||||
// Adopt the processor which was found at first.
|
||||
if (!config.processor && element.processor) {
|
||||
config.processor = element.processor;
|
||||
}
|
||||
|
||||
// Adopt the noInlineConfig which was found at first.
|
||||
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
|
||||
config.noInlineConfig = element.noInlineConfig;
|
||||
config.configNameOfNoInlineConfig = element.name;
|
||||
}
|
||||
|
||||
// Adopt the reportUnusedDisableDirectives which was found at first.
|
||||
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
|
||||
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
|
||||
}
|
||||
|
||||
// Collect ignorePatterns
|
||||
if (element.ignorePattern) {
|
||||
ignorePatterns.push(element.ignorePattern);
|
||||
}
|
||||
|
||||
// Merge others.
|
||||
mergeWithoutOverwrite(config.env, element.env);
|
||||
mergeWithoutOverwrite(config.globals, element.globals);
|
||||
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
|
||||
mergeWithoutOverwrite(config.settings, element.settings);
|
||||
mergePlugins(config.plugins, element.plugins);
|
||||
mergeRuleConfigs(config.rules, element.rules);
|
||||
}
|
||||
|
||||
// Create the predicate function for ignore patterns.
|
||||
if (ignorePatterns.length > 0) {
|
||||
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect definitions.
|
||||
* @template T, U
|
||||
* @param {string} pluginId The plugin ID for prefix.
|
||||
* @param {Record<string,T>} defs The definitions to collect.
|
||||
* @param {Map<string, U>} map The map to output.
|
||||
* @param {function(T): U} [normalize] The normalize function for each value.
|
||||
* @returns {void}
|
||||
*/
|
||||
function collect(pluginId, defs, map, normalize) {
|
||||
if (defs) {
|
||||
const prefix = pluginId && `${pluginId}/`;
|
||||
|
||||
for (const [key, value] of Object.entries(defs)) {
|
||||
map.set(
|
||||
`${prefix}${key}`,
|
||||
normalize ? normalize(value) : value
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a rule definition.
|
||||
* @param {Function|Rule} rule The rule definition to normalize.
|
||||
* @returns {Rule} The normalized rule definition.
|
||||
*/
|
||||
function normalizePluginRule(rule) {
|
||||
return typeof rule === "function" ? { create: rule } : rule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the mutation methods from a given map.
|
||||
* @param {Map<any, any>} map The map object to delete.
|
||||
* @returns {void}
|
||||
*/
|
||||
function deleteMutationMethods(map) {
|
||||
Object.defineProperties(map, {
|
||||
clear: { configurable: true, value: void 0 },
|
||||
delete: { configurable: true, value: void 0 },
|
||||
set: { configurable: true, value: void 0 }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
|
||||
* @param {ConfigArrayElement[]} elements The config elements.
|
||||
* @param {ConfigArrayInternalSlots} slots The internal slots.
|
||||
* @returns {void}
|
||||
*/
|
||||
function initPluginMemberMaps(elements, slots) {
|
||||
const processed = new Set();
|
||||
|
||||
slots.envMap = new Map();
|
||||
slots.processorMap = new Map();
|
||||
slots.ruleMap = new Map();
|
||||
|
||||
for (const element of elements) {
|
||||
if (!element.plugins) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [pluginId, value] of Object.entries(element.plugins)) {
|
||||
const plugin = value.definition;
|
||||
|
||||
if (!plugin || processed.has(pluginId)) {
|
||||
continue;
|
||||
}
|
||||
processed.add(pluginId);
|
||||
|
||||
collect(pluginId, plugin.environments, slots.envMap);
|
||||
collect(pluginId, plugin.processors, slots.processorMap);
|
||||
collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
|
||||
}
|
||||
}
|
||||
|
||||
deleteMutationMethods(slots.envMap);
|
||||
deleteMutationMethods(slots.processorMap);
|
||||
deleteMutationMethods(slots.ruleMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
|
||||
* @param {ConfigArray} instance The config elements.
|
||||
* @returns {ConfigArrayInternalSlots} The extracted config.
|
||||
*/
|
||||
function ensurePluginMemberMaps(instance) {
|
||||
const slots = internalSlotsMap$2.get(instance);
|
||||
|
||||
if (!slots.ruleMap) {
|
||||
initPluginMemberMaps(instance, slots);
|
||||
}
|
||||
|
||||
return slots;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The Config Array.
|
||||
*
|
||||
* `ConfigArray` instance contains all settings, parsers, and plugins.
|
||||
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
|
||||
* extract, merge and get only the config data which is related to an arbitrary
|
||||
* file.
|
||||
* @extends {Array<ConfigArrayElement>}
|
||||
*/
|
||||
class ConfigArray extends Array {
|
||||
|
||||
/**
|
||||
* Get the plugin environments.
|
||||
* The returned map cannot be mutated.
|
||||
* @type {ReadonlyMap<string, Environment>} The plugin environments.
|
||||
*/
|
||||
get pluginEnvironments() {
|
||||
return ensurePluginMemberMaps(this).envMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin processors.
|
||||
* The returned map cannot be mutated.
|
||||
* @type {ReadonlyMap<string, Processor>} The plugin processors.
|
||||
*/
|
||||
get pluginProcessors() {
|
||||
return ensurePluginMemberMaps(this).processorMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin rules.
|
||||
* The returned map cannot be mutated.
|
||||
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
|
||||
*/
|
||||
get pluginRules() {
|
||||
return ensurePluginMemberMaps(this).ruleMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this config has `root` flag.
|
||||
* @returns {boolean} `true` if this config array is root.
|
||||
*/
|
||||
isRoot() {
|
||||
for (let i = this.length - 1; i >= 0; --i) {
|
||||
const root = this[i].root;
|
||||
|
||||
if (typeof root === "boolean") {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the config data which is related to a given file.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {ExtractedConfig} The extracted config data.
|
||||
*/
|
||||
extractConfig(filePath) {
|
||||
const { cache } = internalSlotsMap$2.get(this);
|
||||
const indices = getMatchedIndices(this, filePath);
|
||||
const cacheKey = indices.join(",");
|
||||
|
||||
if (!cache.has(cacheKey)) {
|
||||
cache.set(cacheKey, createConfig(this, indices));
|
||||
}
|
||||
|
||||
return cache.get(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given path is an additional lint target.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {boolean} `true` if the file is an additional lint target.
|
||||
*/
|
||||
isAdditionalTargetPath(filePath) {
|
||||
for (const { criteria, type } of this) {
|
||||
if (
|
||||
type === "config" &&
|
||||
criteria &&
|
||||
!criteria.endsWithWildcard &&
|
||||
criteria.test(filePath)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the used extracted configs.
|
||||
* CLIEngine will use this method to collect used deprecated rules.
|
||||
* @param {ConfigArray} instance The config array object to get.
|
||||
* @returns {ExtractedConfig[]} The used extracted configs.
|
||||
* @private
|
||||
*/
|
||||
function getUsedExtractedConfigs(instance) {
|
||||
const { cache } = internalSlotsMap$2.get(instance);
|
||||
|
||||
return Array.from(cache.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `ConfigDependency` class.
|
||||
*
|
||||
* `ConfigDependency` class expresses a loaded parser or plugin.
|
||||
*
|
||||
* If the parser or plugin was loaded successfully, it has `definition` property
|
||||
* and `filePath` property. Otherwise, it has `error` property.
|
||||
*
|
||||
* When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
|
||||
* omits `definition` property.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
|
||||
* or plugins.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
/**
|
||||
* The class is to store parsers or plugins.
|
||||
* This class hides the loaded object from `JSON.stringify()` and `console.log`.
|
||||
* @template T
|
||||
*/
|
||||
class ConfigDependency {
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {Object} data The dependency data.
|
||||
* @param {T} [data.definition] The dependency if the loading succeeded.
|
||||
* @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.
|
||||
* @param {Error} [data.error] The error object if the loading failed.
|
||||
* @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
|
||||
* @param {string} data.id The ID of this dependency.
|
||||
* @param {string} data.importerName The name of the config file which loads this dependency.
|
||||
* @param {string} data.importerPath The path to the config file which loads this dependency.
|
||||
*/
|
||||
constructor({
|
||||
definition = null,
|
||||
original = null,
|
||||
error = null,
|
||||
filePath = null,
|
||||
id,
|
||||
importerName,
|
||||
importerPath
|
||||
}) {
|
||||
|
||||
/**
|
||||
* The loaded dependency if the loading succeeded.
|
||||
* @type {T|null}
|
||||
*/
|
||||
this.definition = definition;
|
||||
|
||||
/**
|
||||
* The original dependency as loaded directly from disk if the loading succeeded.
|
||||
* @type {T|null}
|
||||
*/
|
||||
this.original = original;
|
||||
|
||||
/**
|
||||
* The error object if the loading failed.
|
||||
* @type {Error|null}
|
||||
*/
|
||||
this.error = error;
|
||||
|
||||
/**
|
||||
* The loaded dependency if the loading succeeded.
|
||||
* @type {string|null}
|
||||
*/
|
||||
this.filePath = filePath;
|
||||
|
||||
/**
|
||||
* The ID of this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.id = id;
|
||||
|
||||
/**
|
||||
* The name of the config file which loads this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.importerName = importerName;
|
||||
|
||||
/**
|
||||
* The path to the config file which loads this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.importerPath = importerPath;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} a JSON compatible object.
|
||||
*/
|
||||
toJSON() {
|
||||
const obj = this[util__default["default"].inspect.custom]();
|
||||
|
||||
// Display `error.message` (`Error#message` is unenumerable).
|
||||
if (obj.error instanceof Error) {
|
||||
obj.error = { ...obj.error, message: obj.error.message };
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} an object to display by `console.log()`.
|
||||
*/
|
||||
[util__default["default"].inspect.custom]() {
|
||||
const {
|
||||
definition: _ignore1, // eslint-disable-line no-unused-vars
|
||||
original: _ignore2, // eslint-disable-line no-unused-vars
|
||||
...obj
|
||||
} = this;
|
||||
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `OverrideTester` class.
|
||||
*
|
||||
* `OverrideTester` class handles `files` property and `excludedFiles` property
|
||||
* of `overrides` config.
|
||||
*
|
||||
* It provides one method.
|
||||
*
|
||||
* - `test(filePath)`
|
||||
* Test if a file path matches the pair of `files` property and
|
||||
* `excludedFiles` property. The `filePath` argument must be an absolute
|
||||
* path.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `OverrideTester` objects when it processes
|
||||
* `overrides` properties.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
const { Minimatch } = minimatch__default["default"];
|
||||
|
||||
const minimatchOpts = { dot: true, matchBase: true };
|
||||
|
||||
/**
|
||||
* @typedef {Object} Pattern
|
||||
* @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
|
||||
* @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normalize a given pattern to an array.
|
||||
* @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
|
||||
* @returns {string[]|null} Normalized patterns.
|
||||
* @private
|
||||
*/
|
||||
function normalizePatterns(patterns) {
|
||||
if (Array.isArray(patterns)) {
|
||||
return patterns.filter(Boolean);
|
||||
}
|
||||
if (typeof patterns === "string" && patterns) {
|
||||
return [patterns];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the matchers of given patterns.
|
||||
* @param {string[]} patterns The patterns.
|
||||
* @returns {InstanceType<Minimatch>[] | null} The matchers.
|
||||
*/
|
||||
function toMatcher(patterns) {
|
||||
if (patterns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return patterns.map(pattern => {
|
||||
if (/^\.[/\\]/u.test(pattern)) {
|
||||
return new Minimatch(
|
||||
pattern.slice(2),
|
||||
|
||||
// `./*.js` should not match with `subdir/foo.js`
|
||||
{ ...minimatchOpts, matchBase: false }
|
||||
);
|
||||
}
|
||||
return new Minimatch(pattern, minimatchOpts);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a given matcher to string.
|
||||
* @param {Pattern} matchers The matchers.
|
||||
* @returns {string} The string expression of the matcher.
|
||||
*/
|
||||
function patternToJson({ includes, excludes }) {
|
||||
return {
|
||||
includes: includes && includes.map(m => m.pattern),
|
||||
excludes: excludes && excludes.map(m => m.pattern)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The class to test given paths are matched by the patterns.
|
||||
*/
|
||||
class OverrideTester {
|
||||
|
||||
/**
|
||||
* Create a tester with given criteria.
|
||||
* If there are no criteria, returns `null`.
|
||||
* @param {string|string[]} files The glob patterns for included files.
|
||||
* @param {string|string[]} excludedFiles The glob patterns for excluded files.
|
||||
* @param {string} basePath The path to the base directory to test paths.
|
||||
* @returns {OverrideTester|null} The created instance or `null`.
|
||||
*/
|
||||
static create(files, excludedFiles, basePath) {
|
||||
const includePatterns = normalizePatterns(files);
|
||||
const excludePatterns = normalizePatterns(excludedFiles);
|
||||
let endsWithWildcard = false;
|
||||
|
||||
if (includePatterns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Rejects absolute paths or relative paths to parents.
|
||||
for (const pattern of includePatterns) {
|
||||
if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
if (pattern.endsWith("*")) {
|
||||
endsWithWildcard = true;
|
||||
}
|
||||
}
|
||||
for (const pattern of excludePatterns) {
|
||||
if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
}
|
||||
|
||||
const includes = toMatcher(includePatterns);
|
||||
const excludes = toMatcher(excludePatterns);
|
||||
|
||||
return new OverrideTester(
|
||||
[{ includes, excludes }],
|
||||
basePath,
|
||||
endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine two testers by logical and.
|
||||
* If either of the testers was `null`, returns the other tester.
|
||||
* The `basePath` property of the two must be the same value.
|
||||
* @param {OverrideTester|null} a A tester.
|
||||
* @param {OverrideTester|null} b Another tester.
|
||||
* @returns {OverrideTester|null} Combined tester.
|
||||
*/
|
||||
static and(a, b) {
|
||||
if (!b) {
|
||||
return a && new OverrideTester(
|
||||
a.patterns,
|
||||
a.basePath,
|
||||
a.endsWithWildcard
|
||||
);
|
||||
}
|
||||
if (!a) {
|
||||
return new OverrideTester(
|
||||
b.patterns,
|
||||
b.basePath,
|
||||
b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
assert__default["default"].strictEqual(a.basePath, b.basePath);
|
||||
return new OverrideTester(
|
||||
a.patterns.concat(b.patterns),
|
||||
a.basePath,
|
||||
a.endsWithWildcard || b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {Pattern[]} patterns The matchers.
|
||||
* @param {string} basePath The base path.
|
||||
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
|
||||
*/
|
||||
constructor(patterns, basePath, endsWithWildcard = false) {
|
||||
|
||||
/** @type {Pattern[]} */
|
||||
this.patterns = patterns;
|
||||
|
||||
/** @type {string} */
|
||||
this.basePath = basePath;
|
||||
|
||||
/** @type {boolean} */
|
||||
this.endsWithWildcard = endsWithWildcard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a given path is matched or not.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {boolean} `true` if the path was matched.
|
||||
*/
|
||||
test(filePath) {
|
||||
if (typeof filePath !== "string" || !path__default["default"].isAbsolute(filePath)) {
|
||||
throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
|
||||
}
|
||||
const relativePath = path__default["default"].relative(this.basePath, filePath);
|
||||
|
||||
return this.patterns.every(({ includes, excludes }) => (
|
||||
(!includes || includes.some(m => m.match(relativePath))) &&
|
||||
(!excludes || !excludes.some(m => m.match(relativePath)))
|
||||
));
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} a JSON compatible object.
|
||||
*/
|
||||
toJSON() {
|
||||
if (this.patterns.length === 1) {
|
||||
return {
|
||||
...patternToJson(this.patterns[0]),
|
||||
basePath: this.basePath
|
||||
};
|
||||
}
|
||||
return {
|
||||
AND: this.patterns.map(patternToJson),
|
||||
basePath: this.basePath
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} an object to display by `console.log()`.
|
||||
*/
|
||||
[util__default["default"].inspect.custom]() {
|
||||
return this.toJSON();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `ConfigArray` class.
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Config file operations. This file must be usable in the browser,
|
||||
* so no Node-specific code can be here.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
|
||||
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
|
||||
map[value] = index;
|
||||
return map;
|
||||
}, {}),
|
||||
VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Normalizes the severity value of a rule's configuration to a number
|
||||
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
|
||||
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
|
||||
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
|
||||
* whose first element is one of the above values. Strings are matched case-insensitively.
|
||||
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
|
||||
*/
|
||||
function getRuleSeverity(ruleConfig) {
|
||||
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
|
||||
return severityValue;
|
||||
}
|
||||
|
||||
if (typeof severityValue === "string") {
|
||||
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts old-style severity settings (0, 1, 2) into new-style
|
||||
* severity settings (off, warn, error) for all rules. Assumption is that severity
|
||||
* values have already been validated as correct.
|
||||
* @param {Object} config The config object to normalize.
|
||||
* @returns {void}
|
||||
*/
|
||||
function normalizeToStrings(config) {
|
||||
|
||||
if (config.rules) {
|
||||
Object.keys(config.rules).forEach(ruleId => {
|
||||
const ruleConfig = config.rules[ruleId];
|
||||
|
||||
if (typeof ruleConfig === "number") {
|
||||
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
|
||||
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
|
||||
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the severity for the given rule configuration represents an error.
|
||||
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} True if the rule represents an error, false if not.
|
||||
*/
|
||||
function isErrorSeverity(ruleConfig) {
|
||||
return getRuleSeverity(ruleConfig) === 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given config has valid severity or not.
|
||||
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isValidSeverity(ruleConfig) {
|
||||
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (typeof severity === "string") {
|
||||
severity = severity.toLowerCase();
|
||||
}
|
||||
return VALID_SEVERITIES.indexOf(severity) !== -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether every rule of a given config has valid severity or not.
|
||||
* @param {Object} config The configuration for rules.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isEverySeverityValid(config) {
|
||||
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a value for a global in a config
|
||||
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
|
||||
* a global directive comment
|
||||
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
|
||||
* @throws Error if global value is invalid
|
||||
*/
|
||||
function normalizeConfigGlobal(configuredValue) {
|
||||
switch (configuredValue) {
|
||||
case "off":
|
||||
return "off";
|
||||
|
||||
case true:
|
||||
case "true":
|
||||
case "writeable":
|
||||
case "writable":
|
||||
return "writable";
|
||||
|
||||
case null:
|
||||
case false:
|
||||
case "false":
|
||||
case "readable":
|
||||
case "readonly":
|
||||
return "readonly";
|
||||
|
||||
default:
|
||||
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
|
||||
}
|
||||
}
|
||||
|
||||
var ConfigOps = {
|
||||
__proto__: null,
|
||||
getRuleSeverity: getRuleSeverity,
|
||||
normalizeToStrings: normalizeToStrings,
|
||||
isErrorSeverity: isErrorSeverity,
|
||||
isValidSeverity: isValidSeverity,
|
||||
isEverySeverityValid: isEverySeverityValid,
|
||||
normalizeConfigGlobal: normalizeConfigGlobal
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Provide the function that emits deprecation warnings.
|
||||
* @author Toru Nagashima <http://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Defitions for deprecation warnings.
|
||||
const deprecationWarningMessages = {
|
||||
ESLINT_LEGACY_ECMAFEATURES:
|
||||
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
|
||||
ESLINT_PERSONAL_CONFIG_LOAD:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please use a config file per project or the '--config' option.",
|
||||
ESLINT_PERSONAL_CONFIG_SUPPRESS:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please remove it or add 'root:true' to the config files in your " +
|
||||
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
|
||||
};
|
||||
|
||||
const sourceFileErrorCache = new Set();
|
||||
|
||||
/**
|
||||
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
|
||||
* for each unique file path, but repeated invocations with the same file path have no effect.
|
||||
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
|
||||
* @param {string} source The name of the configuration source to report the warning for.
|
||||
* @param {string} errorCode The warning message to show.
|
||||
* @returns {void}
|
||||
*/
|
||||
function emitDeprecationWarning(source, errorCode) {
|
||||
const cacheKey = JSON.stringify({ source, errorCode });
|
||||
|
||||
if (sourceFileErrorCache.has(cacheKey)) {
|
||||
return;
|
||||
}
|
||||
sourceFileErrorCache.add(cacheKey);
|
||||
|
||||
const rel = path__default["default"].relative(process.cwd(), source);
|
||||
const message = deprecationWarningMessages[errorCode];
|
||||
|
||||
process.emitWarning(
|
||||
`${message} (found in "${rel}")`,
|
||||
"DeprecationWarning",
|
||||
errorCode
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview The instance of Ajv validator.
|
||||
* @author Evgeny Poberezkin
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* Copied from ajv/lib/refs/json-schema-draft-04.json
|
||||
* The MIT License (MIT)
|
||||
* Copyright (c) 2015-2017 Evgeny Poberezkin
|
||||
*/
|
||||
const metaSchema = {
|
||||
id: "http://json-schema.org/draft-04/schema#",
|
||||
$schema: "http://json-schema.org/draft-04/schema#",
|
||||
description: "Core schema meta-schema",
|
||||
definitions: {
|
||||
schemaArray: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
items: { $ref: "#" }
|
||||
},
|
||||
positiveInteger: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
},
|
||||
positiveIntegerDefault0: {
|
||||
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
|
||||
},
|
||||
simpleTypes: {
|
||||
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
stringArray: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
},
|
||||
type: "object",
|
||||
properties: {
|
||||
id: {
|
||||
type: "string"
|
||||
},
|
||||
$schema: {
|
||||
type: "string"
|
||||
},
|
||||
title: {
|
||||
type: "string"
|
||||
},
|
||||
description: {
|
||||
type: "string"
|
||||
},
|
||||
default: { },
|
||||
multipleOf: {
|
||||
type: "number",
|
||||
minimum: 0,
|
||||
exclusiveMinimum: true
|
||||
},
|
||||
maximum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMaximum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
minimum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMinimum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxLength: { $ref: "#/definitions/positiveInteger" },
|
||||
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
pattern: {
|
||||
type: "string",
|
||||
format: "regex"
|
||||
},
|
||||
additionalItems: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
items: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/schemaArray" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
maxItems: { $ref: "#/definitions/positiveInteger" },
|
||||
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
uniqueItems: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxProperties: { $ref: "#/definitions/positiveInteger" },
|
||||
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
required: { $ref: "#/definitions/stringArray" },
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
definitions: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
properties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
patternProperties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
dependencies: {
|
||||
type: "object",
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/stringArray" }
|
||||
]
|
||||
}
|
||||
},
|
||||
enum: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
},
|
||||
type: {
|
||||
anyOf: [
|
||||
{ $ref: "#/definitions/simpleTypes" },
|
||||
{
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/simpleTypes" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
]
|
||||
},
|
||||
format: { type: "string" },
|
||||
allOf: { $ref: "#/definitions/schemaArray" },
|
||||
anyOf: { $ref: "#/definitions/schemaArray" },
|
||||
oneOf: { $ref: "#/definitions/schemaArray" },
|
||||
not: { $ref: "#" }
|
||||
},
|
||||
dependencies: {
|
||||
exclusiveMaximum: ["maximum"],
|
||||
exclusiveMinimum: ["minimum"]
|
||||
},
|
||||
default: { }
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
var ajvOrig = (additionalOptions = {}) => {
|
||||
const ajv = new Ajv__default["default"]({
|
||||
meta: false,
|
||||
useDefaults: true,
|
||||
validateSchema: false,
|
||||
missingRefs: "ignore",
|
||||
verbose: true,
|
||||
schemaId: "auto",
|
||||
...additionalOptions
|
||||
});
|
||||
|
||||
ajv.addMetaSchema(metaSchema);
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
ajv._opts.defaultMeta = metaSchema.id;
|
||||
|
||||
return ajv;
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Defines a schema for configs.
|
||||
* @author Sylvan Mably
|
||||
*/
|
||||
|
||||
const baseConfigProperties = {
|
||||
$schema: { type: "string" },
|
||||
env: { type: "object" },
|
||||
extends: { $ref: "#/definitions/stringOrStrings" },
|
||||
globals: { type: "object" },
|
||||
overrides: {
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/overrideConfig" },
|
||||
additionalItems: false
|
||||
},
|
||||
parser: { type: ["string", "null"] },
|
||||
parserOptions: { type: "object" },
|
||||
plugins: { type: "array" },
|
||||
processor: { type: "string" },
|
||||
rules: { type: "object" },
|
||||
settings: { type: "object" },
|
||||
noInlineConfig: { type: "boolean" },
|
||||
reportUnusedDisableDirectives: { type: "boolean" },
|
||||
|
||||
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
|
||||
};
|
||||
|
||||
const configSchema = {
|
||||
definitions: {
|
||||
stringOrStrings: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false
|
||||
}
|
||||
]
|
||||
},
|
||||
stringOrStringsRequired: {
|
||||
oneOf: [
|
||||
{ type: "string" },
|
||||
{
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
additionalItems: false,
|
||||
minItems: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// Config at top-level.
|
||||
objectConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
root: { type: "boolean" },
|
||||
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
additionalProperties: false
|
||||
},
|
||||
|
||||
// Config in `overrides`.
|
||||
overrideConfig: {
|
||||
type: "object",
|
||||
properties: {
|
||||
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
|
||||
files: { $ref: "#/definitions/stringOrStringsRequired" },
|
||||
...baseConfigProperties
|
||||
},
|
||||
required: ["files"],
|
||||
additionalProperties: false
|
||||
}
|
||||
},
|
||||
|
||||
$ref: "#/definitions/objectConfig"
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview Defines environment settings and globals.
|
||||
* @author Elan Shanker
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the object that has difference.
|
||||
* @param {Record<string,boolean>} current The newer object.
|
||||
* @param {Record<string,boolean>} prev The older object.
|
||||
* @returns {Record<string,boolean>} The difference object.
|
||||
*/
|
||||
function getDiff(current, prev) {
|
||||
const retv = {};
|
||||
|
||||
for (const [key, value] of Object.entries(current)) {
|
||||
if (!Object.hasOwnProperty.call(prev, key)) {
|
||||
retv[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return retv;
|
||||
}
|
||||
|
||||
const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ...
|
||||
const newGlobals2017 = {
|
||||
Atomics: false,
|
||||
SharedArrayBuffer: false
|
||||
};
|
||||
const newGlobals2020 = {
|
||||
BigInt: false,
|
||||
BigInt64Array: false,
|
||||
BigUint64Array: false,
|
||||
globalThis: false
|
||||
};
|
||||
|
||||
const newGlobals2021 = {
|
||||
AggregateError: false,
|
||||
FinalizationRegistry: false,
|
||||
WeakRef: false
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {Map<string, import("../lib/shared/types").Environment>} */
|
||||
var environments = new Map(Object.entries({
|
||||
|
||||
// Language
|
||||
builtin: {
|
||||
globals: globals__default["default"].es5
|
||||
},
|
||||
es6: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2015: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 6
|
||||
}
|
||||
},
|
||||
es2016: {
|
||||
globals: newGlobals2015,
|
||||
parserOptions: {
|
||||
ecmaVersion: 7
|
||||
}
|
||||
},
|
||||
es2017: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 8
|
||||
}
|
||||
},
|
||||
es2018: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 9
|
||||
}
|
||||
},
|
||||
es2019: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 10
|
||||
}
|
||||
},
|
||||
es2020: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 11
|
||||
}
|
||||
},
|
||||
es2021: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 12
|
||||
}
|
||||
},
|
||||
es2022: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 13
|
||||
}
|
||||
},
|
||||
es2023: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 14
|
||||
}
|
||||
},
|
||||
es2024: {
|
||||
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
|
||||
parserOptions: {
|
||||
ecmaVersion: 15
|
||||
}
|
||||
},
|
||||
|
||||
// Platforms
|
||||
browser: {
|
||||
globals: globals__default["default"].browser
|
||||
},
|
||||
node: {
|
||||
globals: globals__default["default"].node,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
"shared-node-browser": {
|
||||
globals: globals__default["default"]["shared-node-browser"]
|
||||
},
|
||||
worker: {
|
||||
globals: globals__default["default"].worker
|
||||
},
|
||||
serviceworker: {
|
||||
globals: globals__default["default"].serviceworker
|
||||
},
|
||||
|
||||
// Frameworks
|
||||
commonjs: {
|
||||
globals: globals__default["default"].commonjs,
|
||||
parserOptions: {
|
||||
ecmaFeatures: {
|
||||
globalReturn: true
|
||||
}
|
||||
}
|
||||
},
|
||||
amd: {
|
||||
globals: globals__default["default"].amd
|
||||
},
|
||||
mocha: {
|
||||
globals: globals__default["default"].mocha
|
||||
},
|
||||
jasmine: {
|
||||
globals: globals__default["default"].jasmine
|
||||
},
|
||||
jest: {
|
||||
globals: globals__default["default"].jest
|
||||
},
|
||||
phantomjs: {
|
||||
globals: globals__default["default"].phantomjs
|
||||
},
|
||||
jquery: {
|
||||
globals: globals__default["default"].jquery
|
||||
},
|
||||
qunit: {
|
||||
globals: globals__default["default"].qunit
|
||||
},
|
||||
prototypejs: {
|
||||
globals: globals__default["default"].prototypejs
|
||||
},
|
||||
shelljs: {
|
||||
globals: globals__default["default"].shelljs
|
||||
},
|
||||
meteor: {
|
||||
globals: globals__default["default"].meteor
|
||||
},
|
||||
mongo: {
|
||||
globals: globals__default["default"].mongo
|
||||
},
|
||||
protractor: {
|
||||
globals: globals__default["default"].protractor
|
||||
},
|
||||
applescript: {
|
||||
globals: globals__default["default"].applescript
|
||||
},
|
||||
nashorn: {
|
||||
globals: globals__default["default"].nashorn
|
||||
},
|
||||
atomtest: {
|
||||
globals: globals__default["default"].atomtest
|
||||
},
|
||||
embertest: {
|
||||
globals: globals__default["default"].embertest
|
||||
},
|
||||
webextensions: {
|
||||
globals: globals__default["default"].webextensions
|
||||
},
|
||||
greasemonkey: {
|
||||
globals: globals__default["default"].greasemonkey
|
||||
}
|
||||
}));
|
||||
|
||||
/**
|
||||
* @fileoverview Validates configs.
|
||||
* @author Brandon Mills
|
||||
*/
|
||||
|
||||
const ajv = ajvOrig();
|
||||
|
||||
const ruleValidators = new WeakMap();
|
||||
const noop = Function.prototype;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
let validateSchema;
|
||||
const severityMap = {
|
||||
error: 2,
|
||||
warn: 1,
|
||||
off: 0
|
||||
};
|
||||
|
||||
const validated = new WeakSet();
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
class ConfigValidator {
|
||||
constructor({ builtInRules = new Map() } = {}) {
|
||||
this.builtInRules = builtInRules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a complete options schema for a rule.
|
||||
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
|
||||
* @returns {Object} JSON Schema for the rule's options.
|
||||
*/
|
||||
getRuleOptionsSchema(rule) {
|
||||
if (!rule) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const schema = rule.schema || rule.meta && rule.meta.schema;
|
||||
|
||||
// Given a tuple of schemas, insert warning level at the beginning
|
||||
if (Array.isArray(schema)) {
|
||||
if (schema.length) {
|
||||
return {
|
||||
type: "array",
|
||||
items: schema,
|
||||
minItems: 0,
|
||||
maxItems: schema.length
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "array",
|
||||
minItems: 0,
|
||||
maxItems: 0
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// Given a full schema, leave it alone
|
||||
return schema || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
|
||||
* @param {options} options The given options for the rule.
|
||||
* @returns {number|string} The rule's severity value
|
||||
*/
|
||||
validateRuleSeverity(options) {
|
||||
const severity = Array.isArray(options) ? options[0] : options;
|
||||
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
|
||||
|
||||
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
|
||||
return normSeverity;
|
||||
}
|
||||
|
||||
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the non-severity options passed to a rule, based on its schema.
|
||||
* @param {{create: Function}} rule The rule to validate
|
||||
* @param {Array} localOptions The options for the rule, excluding severity
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleSchema(rule, localOptions) {
|
||||
if (!ruleValidators.has(rule)) {
|
||||
const schema = this.getRuleOptionsSchema(rule);
|
||||
|
||||
if (schema) {
|
||||
ruleValidators.set(rule, ajv.compile(schema));
|
||||
}
|
||||
}
|
||||
|
||||
const validateRule = ruleValidators.get(rule);
|
||||
|
||||
if (validateRule) {
|
||||
validateRule(localOptions);
|
||||
if (validateRule.errors) {
|
||||
throw new Error(validateRule.errors.map(
|
||||
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
|
||||
).join(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's options against its schema.
|
||||
* @param {{create: Function}|null} rule The rule that the config is being validated for
|
||||
* @param {string} ruleId The rule's unique name.
|
||||
* @param {Array|number} options The given options for the rule.
|
||||
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
|
||||
* no source is prepended to the message.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleOptions(rule, ruleId, options, source = null) {
|
||||
try {
|
||||
const severity = this.validateRuleSeverity(options);
|
||||
|
||||
if (severity !== 0) {
|
||||
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
|
||||
}
|
||||
} catch (err) {
|
||||
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
|
||||
|
||||
if (typeof source === "string") {
|
||||
throw new Error(`${source}:\n\t${enhancedMessage}`);
|
||||
} else {
|
||||
throw new Error(enhancedMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an environment object
|
||||
* @param {Object} environment The environment config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateEnvironment(
|
||||
environment,
|
||||
source,
|
||||
getAdditionalEnv = noop
|
||||
) {
|
||||
|
||||
// not having an environment is ok
|
||||
if (!environment) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(environment).forEach(id => {
|
||||
const env = getAdditionalEnv(id) || environments.get(id) || null;
|
||||
|
||||
if (!env) {
|
||||
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
|
||||
|
||||
throw new Error(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rules config object
|
||||
* @param {Object} rulesConfig The rules config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRules(
|
||||
rulesConfig,
|
||||
source,
|
||||
getAdditionalRule = noop
|
||||
) {
|
||||
if (!rulesConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(rulesConfig).forEach(id => {
|
||||
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
|
||||
|
||||
this.validateRuleOptions(rule, id, rulesConfig[id], source);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a `globals` section of a config file
|
||||
* @param {Object} globalsConfig The `globals` section
|
||||
* @param {string|null} source The name of the configuration source to report in the event of an error.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateGlobals(globalsConfig, source = null) {
|
||||
if (!globalsConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.entries(globalsConfig)
|
||||
.forEach(([configuredGlobal, configuredValue]) => {
|
||||
try {
|
||||
normalizeConfigGlobal(configuredValue);
|
||||
} catch (err) {
|
||||
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate `processor` configuration.
|
||||
* @param {string|undefined} processorName The processor name.
|
||||
* @param {string} source The name of config file.
|
||||
* @param {function(id:string): Processor} getProcessor The getter of defined processors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateProcessor(processorName, source, getProcessor) {
|
||||
if (processorName && !getProcessor(processorName)) {
|
||||
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats an array of schema validation errors.
|
||||
* @param {Array} errors An array of error messages to format.
|
||||
* @returns {string} Formatted error message
|
||||
*/
|
||||
formatErrors(errors) {
|
||||
return errors.map(error => {
|
||||
if (error.keyword === "additionalProperties") {
|
||||
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
|
||||
|
||||
return `Unexpected top-level property "${formattedPropertyPath}"`;
|
||||
}
|
||||
if (error.keyword === "type") {
|
||||
const formattedField = error.dataPath.slice(1);
|
||||
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
|
||||
const formattedValue = JSON.stringify(error.data);
|
||||
|
||||
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
|
||||
}
|
||||
|
||||
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
|
||||
|
||||
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
|
||||
}).map(message => `\t- ${message}.\n`).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the top level properties of the config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigSchema(config, source = null) {
|
||||
validateSchema = validateSchema || ajv.compile(configSchema);
|
||||
|
||||
if (!validateSchema(config)) {
|
||||
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
|
||||
}
|
||||
|
||||
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
|
||||
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an entire config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
|
||||
* @returns {void}
|
||||
*/
|
||||
validate(config, source, getAdditionalRule, getAdditionalEnv) {
|
||||
this.validateConfigSchema(config, source);
|
||||
this.validateRules(config.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(config.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
|
||||
for (const override of config.overrides || []) {
|
||||
this.validateRules(override.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(override.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate config array object.
|
||||
* @param {ConfigArray} configArray The config array to validate.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigArray(configArray) {
|
||||
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
|
||||
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
|
||||
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
|
||||
|
||||
// Validate.
|
||||
for (const element of configArray) {
|
||||
if (validated.has(element)) {
|
||||
continue;
|
||||
}
|
||||
validated.add(element);
|
||||
|
||||
this.validateEnvironment(element.env, element.name, getPluginEnv);
|
||||
this.validateGlobals(element.globals, element.name);
|
||||
this.validateProcessor(element.processor, element.name, getPluginProcessor);
|
||||
this.validateRules(element.rules, element.name, getPluginRule);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview Common helpers for naming of plugins, formatters and configs
|
||||
*/
|
||||
|
||||
const NAMESPACE_REGEX = /^@.*\//iu;
|
||||
|
||||
/**
|
||||
* Brings package name to correct format based on prefix
|
||||
* @param {string} name The name of the package.
|
||||
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
|
||||
* @returns {string} Normalized name of the package
|
||||
* @private
|
||||
*/
|
||||
function normalizePackageName(name, prefix) {
|
||||
let normalizedName = name;
|
||||
|
||||
/**
|
||||
* On Windows, name can come in with Windows slashes instead of Unix slashes.
|
||||
* Normalize to Unix first to avoid errors later on.
|
||||
* https://github.com/eslint/eslint/issues/5644
|
||||
*/
|
||||
if (normalizedName.includes("\\")) {
|
||||
normalizedName = normalizedName.replace(/\\/gu, "/");
|
||||
}
|
||||
|
||||
if (normalizedName.charAt(0) === "@") {
|
||||
|
||||
/**
|
||||
* it's a scoped package
|
||||
* package name is the prefix, or just a username
|
||||
*/
|
||||
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
|
||||
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
|
||||
|
||||
if (scopedPackageShortcutRegex.test(normalizedName)) {
|
||||
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
|
||||
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
|
||||
|
||||
/**
|
||||
* for scoped packages, insert the prefix after the first / unless
|
||||
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
|
||||
*/
|
||||
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
|
||||
}
|
||||
} else if (!normalizedName.startsWith(`${prefix}-`)) {
|
||||
normalizedName = `${prefix}-${normalizedName}`;
|
||||
}
|
||||
|
||||
return normalizedName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the prefix from a fullname.
|
||||
* @param {string} fullname The term which may have the prefix.
|
||||
* @param {string} prefix The prefix to remove.
|
||||
* @returns {string} The term without prefix.
|
||||
*/
|
||||
function getShorthandName(fullname, prefix) {
|
||||
if (fullname[0] === "@") {
|
||||
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
|
||||
|
||||
if (matchResult) {
|
||||
return matchResult[1];
|
||||
}
|
||||
|
||||
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
|
||||
if (matchResult) {
|
||||
return `${matchResult[1]}/${matchResult[2]}`;
|
||||
}
|
||||
} else if (fullname.startsWith(`${prefix}-`)) {
|
||||
return fullname.slice(prefix.length + 1);
|
||||
}
|
||||
|
||||
return fullname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the scope (namespace) of a term.
|
||||
* @param {string} term The term which may have the namespace.
|
||||
* @returns {string} The namespace of the term if it has one.
|
||||
*/
|
||||
function getNamespaceFromTerm(term) {
|
||||
const match = term.match(NAMESPACE_REGEX);
|
||||
|
||||
return match ? match[0] : "";
|
||||
}
|
||||
|
||||
var naming = {
|
||||
__proto__: null,
|
||||
normalizePackageName: normalizePackageName,
|
||||
getShorthandName: getShorthandName,
|
||||
getNamespaceFromTerm: getNamespaceFromTerm
|
||||
};
|
||||
|
||||
/**
|
||||
* Utility for resolving a module relative to another module
|
||||
* @author Teddy Katz
|
||||
*/
|
||||
|
||||
/*
|
||||
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
|
||||
* We only support the case where the argument is a filepath, not a URL.
|
||||
*/
|
||||
const createRequire = Module__default["default"].createRequire;
|
||||
|
||||
/**
|
||||
* Resolves a Node module relative to another module
|
||||
* @param {string} moduleName The name of a Node module, or a path to a Node module.
|
||||
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
|
||||
* a file rather than a directory, but the file need not actually exist.
|
||||
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
|
||||
*/
|
||||
function resolve(moduleName, relativeToPath) {
|
||||
try {
|
||||
return createRequire(relativeToPath).resolve(moduleName);
|
||||
} catch (error) {
|
||||
|
||||
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
error.code === "MODULE_NOT_FOUND" &&
|
||||
!error.requireStack &&
|
||||
error.message.includes(moduleName)
|
||||
) {
|
||||
error.message += `\nRequire stack:\n- ${relativeToPath}`;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
var ModuleResolver = {
|
||||
__proto__: null,
|
||||
resolve: resolve
|
||||
};
|
||||
|
||||
/**
|
||||
* @fileoverview The factory of `ConfigArray` objects.
|
||||
*
|
||||
* This class provides methods to create `ConfigArray` instance.
|
||||
*
|
||||
* - `create(configData, options)`
|
||||
* Create a `ConfigArray` instance from a config data. This is to handle CLI
|
||||
* options except `--config`.
|
||||
* - `loadFile(filePath, options)`
|
||||
* Create a `ConfigArray` instance from a config file. This is to handle
|
||||
* `--config` option. If the file was not found, throws the following error:
|
||||
* - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
|
||||
* - If the filename was `package.json`, an IO error or an
|
||||
* `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
|
||||
* - Otherwise, an IO error such as `ENOENT`.
|
||||
* - `loadInDirectory(directoryPath, options)`
|
||||
* Create a `ConfigArray` instance from a config file which is on a given
|
||||
* directory. This tries to load `.eslintrc.*` or `package.json`. If not
|
||||
* found, returns an empty `ConfigArray`.
|
||||
* - `loadESLintIgnore(filePath)`
|
||||
* Create a `ConfigArray` instance from a config file that is `.eslintignore`
|
||||
* format. This is to handle `--ignore-path` option.
|
||||
* - `loadDefaultESLintIgnore()`
|
||||
* Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
|
||||
* the current working directory.
|
||||
*
|
||||
* `ConfigArrayFactory` class has the responsibility that loads configuration
|
||||
* files, including loading `extends`, `parser`, and `plugins`. The created
|
||||
* `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
|
||||
*
|
||||
* But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
|
||||
* handles cascading and hierarchy.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
const require$1 = Module.createRequire(require('url').pathToFileURL(__filename).toString());
|
||||
|
||||
const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const configFilenames = [
|
||||
".eslintrc.js",
|
||||
".eslintrc.cjs",
|
||||
".eslintrc.yaml",
|
||||
".eslintrc.yml",
|
||||
".eslintrc.json",
|
||||
".eslintrc",
|
||||
"package.json"
|
||||
];
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("./shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
|
||||
/** @typedef {import("./shared/types").Parser} Parser */
|
||||
/** @typedef {import("./shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("./shared/types").Rule} Rule */
|
||||
/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
|
||||
/** @typedef {ConfigArray[0]} ConfigArrayElement */
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryOptions
|
||||
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
|
||||
* @property {string} [cwd] The path to the current working directory.
|
||||
* @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryInternalSlots
|
||||
* @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
|
||||
* @property {string} cwd The path to the current working directory.
|
||||
* @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryLoadingContext
|
||||
* @property {string} filePath The path to the current configuration.
|
||||
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @property {string} name The name of the current configuration.
|
||||
* @property {string} pluginBasePath The base path to resolve plugins.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryLoadingContext
|
||||
* @property {string} filePath The path to the current configuration.
|
||||
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @property {string} name The name of the current configuration.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
|
||||
const internalSlotsMap$1 = new WeakMap();
|
||||
|
||||
/** @type {WeakMap<object, Plugin>} */
|
||||
const normalizedPlugins = new WeakMap();
|
||||
|
||||
/**
|
||||
* Check if a given string is a file path.
|
||||
* @param {string} nameOrPath A module name or file path.
|
||||
* @returns {boolean} `true` if the `nameOrPath` is a file path.
|
||||
*/
|
||||
function isFilePath(nameOrPath) {
|
||||
return (
|
||||
/^\.{1,2}[/\\]/u.test(nameOrPath) ||
|
||||
path__default["default"].isAbsolute(nameOrPath)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper for synchronously reading file contents.
|
||||
* @param {string} filePath The filename to read.
|
||||
* @returns {string} The file contents, with the BOM removed.
|
||||
* @private
|
||||
*/
|
||||
function readFile(filePath) {
|
||||
return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a YAML configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadYAMLConfigFile(filePath) {
|
||||
debug$2(`Loading YAML config file: ${filePath}`);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
const yaml = require$1("js-yaml");
|
||||
|
||||
try {
|
||||
|
||||
// empty YAML file can be null, so always use
|
||||
return yaml.load(readFile(filePath)) || {};
|
||||
} catch (e) {
|
||||
debug$2(`Error reading YAML file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a JSON configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadJSONConfigFile(filePath) {
|
||||
debug$2(`Loading JSON config file: ${filePath}`);
|
||||
|
||||
try {
|
||||
return JSON.parse(stripComments__default["default"](readFile(filePath)));
|
||||
} catch (e) {
|
||||
debug$2(`Error reading JSON file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
e.messageTemplate = "failed-to-read-json";
|
||||
e.messageData = {
|
||||
path: filePath,
|
||||
message: e.message
|
||||
};
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a legacy (.eslintrc) configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadLegacyConfigFile(filePath) {
|
||||
debug$2(`Loading legacy config file: ${filePath}`);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
const yaml = require$1("js-yaml");
|
||||
|
||||
try {
|
||||
return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {};
|
||||
} catch (e) {
|
||||
debug$2("Error reading YAML file: %s\n%o", filePath, e);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a JavaScript configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadJSConfigFile(filePath) {
|
||||
debug$2(`Loading JS config file: ${filePath}`);
|
||||
try {
|
||||
return importFresh__default["default"](filePath);
|
||||
} catch (e) {
|
||||
debug$2(`Error reading JavaScript file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a configuration from a package.json file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadPackageJSONConfigFile(filePath) {
|
||||
debug$2(`Loading package.json config file: ${filePath}`);
|
||||
try {
|
||||
const packageData = loadJSONConfigFile(filePath);
|
||||
|
||||
if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
|
||||
throw Object.assign(
|
||||
new Error("package.json file doesn't have 'eslintConfig' field."),
|
||||
{ code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
|
||||
);
|
||||
}
|
||||
|
||||
return packageData.eslintConfig;
|
||||
} catch (e) {
|
||||
debug$2(`Error reading package.json file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a `.eslintignore` from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {string[]} The ignore patterns from the file.
|
||||
* @private
|
||||
*/
|
||||
function loadESLintIgnoreFile(filePath) {
|
||||
debug$2(`Loading .eslintignore file: ${filePath}`);
|
||||
|
||||
try {
|
||||
return readFile(filePath)
|
||||
.split(/\r?\n/gu)
|
||||
.filter(line => line.trim() !== "" && !line.startsWith("#"));
|
||||
} catch (e) {
|
||||
debug$2(`Error reading .eslintignore file: ${filePath}`);
|
||||
e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an error to notify about a missing config to extend from.
|
||||
* @param {string} configName The name of the missing config.
|
||||
* @param {string} importerName The name of the config that imported the missing config
|
||||
* @param {string} messageTemplate The text template to source error strings from.
|
||||
* @returns {Error} The error object to throw
|
||||
* @private
|
||||
*/
|
||||
function configInvalidError(configName, importerName, messageTemplate) {
|
||||
return Object.assign(
|
||||
new Error(`Failed to load config "${configName}" to extend from.`),
|
||||
{
|
||||
messageTemplate,
|
||||
messageData: { configName, importerName }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a configuration file regardless of the source. Inspects the file path
|
||||
* to determine the correctly way to load the config file.
|
||||
* @param {string} filePath The path to the configuration.
|
||||
* @returns {ConfigData|null} The configuration information.
|
||||
* @private
|
||||
*/
|
||||
function loadConfigFile(filePath) {
|
||||
switch (path__default["default"].extname(filePath)) {
|
||||
case ".js":
|
||||
case ".cjs":
|
||||
return loadJSConfigFile(filePath);
|
||||
|
||||
case ".json":
|
||||
if (path__default["default"].basename(filePath) === "package.json") {
|
||||
return loadPackageJSONConfigFile(filePath);
|
||||
}
|
||||
return loadJSONConfigFile(filePath);
|
||||
|
||||
case ".yaml":
|
||||
case ".yml":
|
||||
return loadYAMLConfigFile(filePath);
|
||||
|
||||
default:
|
||||
return loadLegacyConfigFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write debug log.
|
||||
* @param {string} request The requested module name.
|
||||
* @param {string} relativeTo The file path to resolve the request relative to.
|
||||
* @param {string} filePath The resolved file path.
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeDebugLogForLoading(request, relativeTo, filePath) {
|
||||
/* istanbul ignore next */
|
||||
if (debug$2.enabled) {
|
||||
let nameAndVersion = null;
|
||||
|
||||
try {
|
||||
const packageJsonPath = resolve(
|
||||
`${request}/package.json`,
|
||||
relativeTo
|
||||
);
|
||||
const { version = "unknown" } = require$1(packageJsonPath);
|
||||
|
||||
nameAndVersion = `${request}@${version}`;
|
||||
} catch (error) {
|
||||
debug$2("package.json was not found:", error.message);
|
||||
nameAndVersion = request;
|
||||
}
|
||||
|
||||
debug$2("Loaded: %s (%s)", nameAndVersion, filePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new context with default values.
|
||||
* @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
|
||||
* @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
|
||||
* @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
|
||||
* @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
|
||||
* @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
|
||||
* @returns {ConfigArrayFactoryLoadingContext} The created context.
|
||||
*/
|
||||
function createContext(
|
||||
{ cwd, resolvePluginsRelativeTo },
|
||||
providedType,
|
||||
providedName,
|
||||
providedFilePath,
|
||||
providedMatchBasePath
|
||||
) {
|
||||
const filePath = providedFilePath
|
||||
? path__default["default"].resolve(cwd, providedFilePath)
|
||||
: "";
|
||||
const matchBasePath =
|
||||
(providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) ||
|
||||
(filePath && path__default["default"].dirname(filePath)) ||
|
||||
cwd;
|
||||
const name =
|
||||
providedName ||
|
||||
(filePath && path__default["default"].relative(cwd, filePath)) ||
|
||||
"";
|
||||
const pluginBasePath =
|
||||
resolvePluginsRelativeTo ||
|
||||
(filePath && path__default["default"].dirname(filePath)) ||
|
||||
cwd;
|
||||
const type = providedType || "config";
|
||||
|
||||
return { filePath, matchBasePath, name, pluginBasePath, type };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given plugin.
|
||||
* - Ensure the object to have four properties: configs, environments, processors, and rules.
|
||||
* - Ensure the object to not have other properties.
|
||||
* @param {Plugin} plugin The plugin to normalize.
|
||||
* @returns {Plugin} The normalized plugin.
|
||||
*/
|
||||
function normalizePlugin(plugin) {
|
||||
|
||||
// first check the cache
|
||||
let normalizedPlugin = normalizedPlugins.get(plugin);
|
||||
|
||||
if (normalizedPlugin) {
|
||||
return normalizedPlugin;
|
||||
}
|
||||
|
||||
normalizedPlugin = {
|
||||
configs: plugin.configs || {},
|
||||
environments: plugin.environments || {},
|
||||
processors: plugin.processors || {},
|
||||
rules: plugin.rules || {}
|
||||
};
|
||||
|
||||
// save the reference for later
|
||||
normalizedPlugins.set(plugin, normalizedPlugin);
|
||||
|
||||
return normalizedPlugin;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The factory of `ConfigArray` objects.
|
||||
*/
|
||||
class ConfigArrayFactory {
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
|
||||
*/
|
||||
constructor({
|
||||
additionalPluginPool = new Map(),
|
||||
cwd = process.cwd(),
|
||||
resolvePluginsRelativeTo,
|
||||
builtInRules,
|
||||
resolver = ModuleResolver,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
} = {}) {
|
||||
internalSlotsMap$1.set(this, {
|
||||
additionalPluginPool,
|
||||
cwd,
|
||||
resolvePluginsRelativeTo:
|
||||
resolvePluginsRelativeTo &&
|
||||
path__default["default"].resolve(cwd, resolvePluginsRelativeTo),
|
||||
builtInRules,
|
||||
resolver,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `ConfigArray` instance from a config data.
|
||||
* @param {ConfigData|null} configData The config data to create.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.filePath] The path to this config data.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config.
|
||||
*/
|
||||
create(configData, { basePath, filePath, name } = {}) {
|
||||
if (!configData) {
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
const slots = internalSlotsMap$1.get(this);
|
||||
const ctx = createContext(slots, "config", name, filePath, basePath);
|
||||
const elements = this._normalizeConfigData(configData, ctx);
|
||||
|
||||
return new ConfigArray(...elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a config file.
|
||||
* @param {string} filePath The path to a config file.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config.
|
||||
*/
|
||||
loadFile(filePath, { basePath, name } = {}) {
|
||||
const slots = internalSlotsMap$1.get(this);
|
||||
const ctx = createContext(slots, "config", name, filePath, basePath);
|
||||
|
||||
return new ConfigArray(...this._loadConfigData(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the config file on a given directory if exists.
|
||||
* @param {string} directoryPath The path to a directory.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadInDirectory(directoryPath, { basePath, name } = {}) {
|
||||
const slots = internalSlotsMap$1.get(this);
|
||||
|
||||
for (const filename of configFilenames) {
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"config",
|
||||
name,
|
||||
path__default["default"].join(directoryPath, filename),
|
||||
basePath
|
||||
);
|
||||
|
||||
if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) {
|
||||
let configData;
|
||||
|
||||
try {
|
||||
configData = loadConfigFile(ctx.filePath);
|
||||
} catch (error) {
|
||||
if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (configData) {
|
||||
debug$2(`Config file found: ${ctx.filePath}`);
|
||||
return new ConfigArray(
|
||||
...this._normalizeConfigData(configData, ctx)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug$2(`Config file not found on ${directoryPath}`);
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a config file on a given directory exists or not.
|
||||
* @param {string} directoryPath The path to a directory.
|
||||
* @returns {string | null} The path to the found config file. If not found then null.
|
||||
*/
|
||||
static getPathToConfigFileInDirectory(directoryPath) {
|
||||
for (const filename of configFilenames) {
|
||||
const filePath = path__default["default"].join(directoryPath, filename);
|
||||
|
||||
if (fs__default["default"].existsSync(filePath)) {
|
||||
if (filename === "package.json") {
|
||||
try {
|
||||
loadPackageJSONConfigFile(filePath);
|
||||
return filePath;
|
||||
} catch { /* ignore */ }
|
||||
} else {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.eslintignore` file.
|
||||
* @param {string} filePath The path to a `.eslintignore` file to load.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadESLintIgnore(filePath) {
|
||||
const slots = internalSlotsMap$1.get(this);
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"ignore",
|
||||
void 0,
|
||||
filePath,
|
||||
slots.cwd
|
||||
);
|
||||
const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
|
||||
|
||||
return new ConfigArray(
|
||||
...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.eslintignore` file in the current working directory.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadDefaultESLintIgnore() {
|
||||
const slots = internalSlotsMap$1.get(this);
|
||||
const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore");
|
||||
const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json");
|
||||
|
||||
if (fs__default["default"].existsSync(eslintIgnorePath)) {
|
||||
return this.loadESLintIgnore(eslintIgnorePath);
|
||||
}
|
||||
if (fs__default["default"].existsSync(packageJsonPath)) {
|
||||
const data = loadJSONConfigFile(packageJsonPath);
|
||||
|
||||
if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
|
||||
if (!Array.isArray(data.eslintIgnore)) {
|
||||
throw new Error("Package.json eslintIgnore property requires an array of paths");
|
||||
}
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"ignore",
|
||||
"eslintIgnore in package.json",
|
||||
packageJsonPath,
|
||||
slots.cwd
|
||||
);
|
||||
|
||||
return new ConfigArray(
|
||||
...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given config file.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} Loaded config.
|
||||
* @private
|
||||
*/
|
||||
_loadConfigData(ctx) {
|
||||
return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given `.eslintignore` data to config array elements.
|
||||
* @param {string[]} ignorePatterns The patterns to ignore files.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeESLintIgnoreData(ignorePatterns, ctx) {
|
||||
const elements = this._normalizeObjectConfigData(
|
||||
{ ignorePatterns },
|
||||
ctx
|
||||
);
|
||||
|
||||
// Set `ignorePattern.loose` flag for backward compatibility.
|
||||
for (const element of elements) {
|
||||
if (element.ignorePattern) {
|
||||
element.ignorePattern.loose = true;
|
||||
}
|
||||
yield element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_normalizeConfigData(configData, ctx) {
|
||||
const validator = new ConfigValidator();
|
||||
|
||||
validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
|
||||
return this._normalizeObjectConfigData(configData, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData|OverrideConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeObjectConfigData(configData, ctx) {
|
||||
const { files, excludedFiles, ...configBody } = configData;
|
||||
const criteria = OverrideTester.create(
|
||||
files,
|
||||
excludedFiles,
|
||||
ctx.matchBasePath
|
||||
);
|
||||
const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
|
||||
|
||||
// Apply the criteria to every element.
|
||||
for (const element of elements) {
|
||||
|
||||
/*
|
||||
* Merge the criteria.
|
||||
* This is for the `overrides` entries that came from the
|
||||
* configurations of `overrides[].extends`.
|
||||
*/
|
||||
element.criteria = OverrideTester.and(criteria, element.criteria);
|
||||
|
||||
/*
|
||||
* Remove `root` property to ignore `root` settings which came from
|
||||
* `extends` in `overrides`.
|
||||
*/
|
||||
if (element.criteria) {
|
||||
element.root = void 0;
|
||||
}
|
||||
|
||||
yield element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeObjectConfigDataBody(
|
||||
{
|
||||
env,
|
||||
extends: extend,
|
||||
globals,
|
||||
ignorePatterns,
|
||||
noInlineConfig,
|
||||
parser: parserName,
|
||||
parserOptions,
|
||||
plugins: pluginList,
|
||||
processor,
|
||||
reportUnusedDisableDirectives,
|
||||
root,
|
||||
rules,
|
||||
settings,
|
||||
overrides: overrideList = []
|
||||
},
|
||||
ctx
|
||||
) {
|
||||
const extendList = Array.isArray(extend) ? extend : [extend];
|
||||
const ignorePattern = ignorePatterns && new IgnorePattern(
|
||||
Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
|
||||
ctx.matchBasePath
|
||||
);
|
||||
|
||||
// Flatten `extends`.
|
||||
for (const extendName of extendList.filter(Boolean)) {
|
||||
yield* this._loadExtends(extendName, ctx);
|
||||
}
|
||||
|
||||
// Load parser & plugins.
|
||||
const parser = parserName && this._loadParser(parserName, ctx);
|
||||
const plugins = pluginList && this._loadPlugins(pluginList, ctx);
|
||||
|
||||
// Yield pseudo config data for file extension processors.
|
||||
if (plugins) {
|
||||
yield* this._takeFileExtensionProcessors(plugins, ctx);
|
||||
}
|
||||
|
||||
// Yield the config data except `extends` and `overrides`.
|
||||
yield {
|
||||
|
||||
// Debug information.
|
||||
type: ctx.type,
|
||||
name: ctx.name,
|
||||
filePath: ctx.filePath,
|
||||
|
||||
// Config data.
|
||||
criteria: null,
|
||||
env,
|
||||
globals,
|
||||
ignorePattern,
|
||||
noInlineConfig,
|
||||
parser,
|
||||
parserOptions,
|
||||
plugins,
|
||||
processor,
|
||||
reportUnusedDisableDirectives,
|
||||
root,
|
||||
rules,
|
||||
settings
|
||||
};
|
||||
|
||||
// Flatten `overries`.
|
||||
for (let i = 0; i < overrideList.length; ++i) {
|
||||
yield* this._normalizeObjectConfigData(
|
||||
overrideList[i],
|
||||
{ ...ctx, name: `${ctx.name}#overrides[${i}]` }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtends(extendName, ctx) {
|
||||
debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
|
||||
try {
|
||||
if (extendName.startsWith("eslint:")) {
|
||||
return this._loadExtendedBuiltInConfig(extendName, ctx);
|
||||
}
|
||||
if (extendName.startsWith("plugin:")) {
|
||||
return this._loadExtendedPluginConfig(extendName, ctx);
|
||||
}
|
||||
return this._loadExtendedShareableConfig(extendName, ctx);
|
||||
} catch (error) {
|
||||
error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedBuiltInConfig(extendName, ctx) {
|
||||
const {
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
} = internalSlotsMap$1.get(this);
|
||||
|
||||
if (extendName === "eslint:recommended") {
|
||||
const name = `${ctx.name} » ${extendName}`;
|
||||
|
||||
if (getEslintRecommendedConfig) {
|
||||
if (typeof getEslintRecommendedConfig !== "function") {
|
||||
throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
|
||||
}
|
||||
return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
|
||||
}
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
name,
|
||||
filePath: eslintRecommendedPath
|
||||
});
|
||||
}
|
||||
if (extendName === "eslint:all") {
|
||||
const name = `${ctx.name} » ${extendName}`;
|
||||
|
||||
if (getEslintAllConfig) {
|
||||
if (typeof getEslintAllConfig !== "function") {
|
||||
throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
|
||||
}
|
||||
return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
|
||||
}
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
name,
|
||||
filePath: eslintAllPath
|
||||
});
|
||||
}
|
||||
|
||||
throw configInvalidError(extendName, ctx.name, "extend-config-missing");
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedPluginConfig(extendName, ctx) {
|
||||
const slashIndex = extendName.lastIndexOf("/");
|
||||
|
||||
if (slashIndex === -1) {
|
||||
throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
|
||||
}
|
||||
|
||||
const pluginName = extendName.slice("plugin:".length, slashIndex);
|
||||
const configName = extendName.slice(slashIndex + 1);
|
||||
|
||||
if (isFilePath(pluginName)) {
|
||||
throw new Error("'extends' cannot use a file path for plugins.");
|
||||
}
|
||||
|
||||
const plugin = this._loadPlugin(pluginName, ctx);
|
||||
const configData =
|
||||
plugin.definition &&
|
||||
plugin.definition.configs[configName];
|
||||
|
||||
if (configData) {
|
||||
return this._normalizeConfigData(configData, {
|
||||
...ctx,
|
||||
filePath: plugin.filePath || ctx.filePath,
|
||||
name: `${ctx.name} » plugin:${plugin.id}/${configName}`
|
||||
});
|
||||
}
|
||||
|
||||
throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedShareableConfig(extendName, ctx) {
|
||||
const { cwd, resolver } = internalSlotsMap$1.get(this);
|
||||
const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
|
||||
let request;
|
||||
|
||||
if (isFilePath(extendName)) {
|
||||
request = extendName;
|
||||
} else if (extendName.startsWith(".")) {
|
||||
request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
|
||||
} else {
|
||||
request = normalizePackageName(
|
||||
extendName,
|
||||
"eslint-config"
|
||||
);
|
||||
}
|
||||
|
||||
let filePath;
|
||||
|
||||
try {
|
||||
filePath = resolver.resolve(request, relativeTo);
|
||||
} catch (error) {
|
||||
/* istanbul ignore else */
|
||||
if (error && error.code === "MODULE_NOT_FOUND") {
|
||||
throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
writeDebugLogForLoading(request, relativeTo, filePath);
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
filePath,
|
||||
name: `${ctx.name} » ${request}`
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load given plugins.
|
||||
* @param {string[]} names The plugin names to load.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {Record<string,DependentPlugin>} The loaded parser.
|
||||
* @private
|
||||
*/
|
||||
_loadPlugins(names, ctx) {
|
||||
return names.reduce((map, name) => {
|
||||
if (isFilePath(name)) {
|
||||
throw new Error("Plugins array cannot includes file paths.");
|
||||
}
|
||||
const plugin = this._loadPlugin(name, ctx);
|
||||
|
||||
map[plugin.id] = plugin;
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given parser.
|
||||
* @param {string} nameOrPath The package name or the path to a parser file.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {DependentParser} The loaded parser.
|
||||
*/
|
||||
_loadParser(nameOrPath, ctx) {
|
||||
debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath);
|
||||
|
||||
const { cwd, resolver } = internalSlotsMap$1.get(this);
|
||||
const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js");
|
||||
|
||||
try {
|
||||
const filePath = resolver.resolve(nameOrPath, relativeTo);
|
||||
|
||||
writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
|
||||
|
||||
return new ConfigDependency({
|
||||
definition: require$1(filePath),
|
||||
filePath,
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
// If the parser name is "espree", load the espree of ESLint.
|
||||
if (nameOrPath === "espree") {
|
||||
debug$2("Fallback espree.");
|
||||
return new ConfigDependency({
|
||||
definition: require$1("espree"),
|
||||
filePath: require$1.resolve("espree"),
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
|
||||
error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
|
||||
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given plugin.
|
||||
* @param {string} name The plugin name to load.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {DependentPlugin} The loaded plugin.
|
||||
* @private
|
||||
*/
|
||||
_loadPlugin(name, ctx) {
|
||||
debug$2("Loading plugin %j from %s", name, ctx.filePath);
|
||||
|
||||
const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this);
|
||||
const request = normalizePackageName(name, "eslint-plugin");
|
||||
const id = getShorthandName(request, "eslint-plugin");
|
||||
const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js");
|
||||
|
||||
if (name.match(/\s+/u)) {
|
||||
const error = Object.assign(
|
||||
new Error(`Whitespace found in plugin name '${name}'`),
|
||||
{
|
||||
messageTemplate: "whitespace-found",
|
||||
messageData: { pluginName: request }
|
||||
}
|
||||
);
|
||||
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
// Check for additional pool.
|
||||
const plugin =
|
||||
additionalPluginPool.get(request) ||
|
||||
additionalPluginPool.get(id);
|
||||
|
||||
if (plugin) {
|
||||
return new ConfigDependency({
|
||||
definition: normalizePlugin(plugin),
|
||||
original: plugin,
|
||||
filePath: "", // It's unknown where the plugin came from.
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
let filePath;
|
||||
let error;
|
||||
|
||||
try {
|
||||
filePath = resolver.resolve(request, relativeTo);
|
||||
} catch (resolveError) {
|
||||
error = resolveError;
|
||||
/* istanbul ignore else */
|
||||
if (error && error.code === "MODULE_NOT_FOUND") {
|
||||
error.messageTemplate = "plugin-missing";
|
||||
error.messageData = {
|
||||
pluginName: request,
|
||||
resolvePluginsRelativeTo: ctx.pluginBasePath,
|
||||
importerName: ctx.name
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filePath) {
|
||||
try {
|
||||
writeDebugLogForLoading(request, relativeTo, filePath);
|
||||
|
||||
const startTime = Date.now();
|
||||
const pluginDefinition = require$1(filePath);
|
||||
|
||||
debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
|
||||
|
||||
return new ConfigDependency({
|
||||
definition: normalizePlugin(pluginDefinition),
|
||||
original: pluginDefinition,
|
||||
filePath,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
} catch (loadError) {
|
||||
error = loadError;
|
||||
}
|
||||
}
|
||||
|
||||
debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
|
||||
error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Take file expression processors as config array elements.
|
||||
* @param {Record<string,DependentPlugin>} plugins The plugin definitions.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
|
||||
* @private
|
||||
*/
|
||||
*_takeFileExtensionProcessors(plugins, ctx) {
|
||||
for (const pluginId of Object.keys(plugins)) {
|
||||
const processors =
|
||||
plugins[pluginId] &&
|
||||
plugins[pluginId].definition &&
|
||||
plugins[pluginId].definition.processors;
|
||||
|
||||
if (!processors) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const processorId of Object.keys(processors)) {
|
||||
if (processorId.startsWith(".")) {
|
||||
yield* this._normalizeObjectConfigData(
|
||||
{
|
||||
files: [`*${processorId}`],
|
||||
processor: `${pluginId}/${processorId}`
|
||||
},
|
||||
{
|
||||
...ctx,
|
||||
type: "implicit-processor",
|
||||
name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview `CascadingConfigArrayFactory` class.
|
||||
*
|
||||
* `CascadingConfigArrayFactory` class has a responsibility:
|
||||
*
|
||||
* 1. Handles cascading of config files.
|
||||
*
|
||||
* It provides two methods:
|
||||
*
|
||||
* - `getConfigArrayForFile(filePath)`
|
||||
* Get the corresponded configuration of a given file. This method doesn't
|
||||
* throw even if the given file didn't exist.
|
||||
* - `clearCache()`
|
||||
* Clear the internal cache. You have to call this method when
|
||||
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
|
||||
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("./shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("./shared/types").Parser} Parser */
|
||||
/** @typedef {import("./shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("./shared/types").Rule} Rule */
|
||||
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
|
||||
|
||||
/**
|
||||
* @typedef {Object} CascadingConfigArrayFactoryOptions
|
||||
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
|
||||
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
|
||||
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
|
||||
* @property {string} [cwd] The base directory to start lookup.
|
||||
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
|
||||
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
|
||||
* @property {string} [specificConfigPath] The value of `--config` option.
|
||||
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
|
||||
* @property {Function} loadRules The function to use to load rules.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
|
||||
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
|
||||
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
|
||||
* @property {ConfigArray} cliConfigArray The config array of CLI options.
|
||||
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
|
||||
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
|
||||
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
|
||||
* @property {string} cwd The base directory to start lookup.
|
||||
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
|
||||
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
|
||||
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
|
||||
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
|
||||
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
|
||||
* @property {Function} loadRules The function to use to load rules.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
|
||||
const internalSlotsMap = new WeakMap();
|
||||
|
||||
/**
|
||||
* Create the config array from `baseConfig` and `rulePaths`.
|
||||
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
|
||||
* @returns {ConfigArray} The config array of the base configs.
|
||||
*/
|
||||
function createBaseConfigArray({
|
||||
configArrayFactory,
|
||||
baseConfigData,
|
||||
rulePaths,
|
||||
cwd,
|
||||
loadRules
|
||||
}) {
|
||||
const baseConfigArray = configArrayFactory.create(
|
||||
baseConfigData,
|
||||
{ name: "BaseConfig" }
|
||||
);
|
||||
|
||||
/*
|
||||
* Create the config array element for the default ignore patterns.
|
||||
* This element has `ignorePattern` property that ignores the default
|
||||
* patterns in the current working directory.
|
||||
*/
|
||||
baseConfigArray.unshift(configArrayFactory.create(
|
||||
{ ignorePatterns: IgnorePattern.DefaultPatterns },
|
||||
{ name: "DefaultIgnorePattern" }
|
||||
)[0]);
|
||||
|
||||
/*
|
||||
* Load rules `--rulesdir` option as a pseudo plugin.
|
||||
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
|
||||
* the rule's options with only information in the config array.
|
||||
*/
|
||||
if (rulePaths && rulePaths.length > 0) {
|
||||
baseConfigArray.push({
|
||||
type: "config",
|
||||
name: "--rulesdir",
|
||||
filePath: "",
|
||||
plugins: {
|
||||
"": new ConfigDependency({
|
||||
definition: {
|
||||
rules: rulePaths.reduce(
|
||||
(map, rulesPath) => Object.assign(
|
||||
map,
|
||||
loadRules(rulesPath, cwd)
|
||||
),
|
||||
{}
|
||||
)
|
||||
},
|
||||
filePath: "",
|
||||
id: "",
|
||||
importerName: "--rulesdir",
|
||||
importerPath: ""
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return baseConfigArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the config array from CLI options.
|
||||
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
|
||||
* @returns {ConfigArray} The config array of the base configs.
|
||||
*/
|
||||
function createCLIConfigArray({
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
ignorePath,
|
||||
specificConfigPath
|
||||
}) {
|
||||
const cliConfigArray = configArrayFactory.create(
|
||||
cliConfigData,
|
||||
{ name: "CLIOptions" }
|
||||
);
|
||||
|
||||
cliConfigArray.unshift(
|
||||
...(ignorePath
|
||||
? configArrayFactory.loadESLintIgnore(ignorePath)
|
||||
: configArrayFactory.loadDefaultESLintIgnore())
|
||||
);
|
||||
|
||||
if (specificConfigPath) {
|
||||
cliConfigArray.unshift(
|
||||
...configArrayFactory.loadFile(
|
||||
specificConfigPath,
|
||||
{ name: "--config", basePath: cwd }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return cliConfigArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* The error type when there are files matched by a glob, but all of them have been ignored.
|
||||
*/
|
||||
class ConfigurationNotFoundError extends Error {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} directoryPath The directory path.
|
||||
*/
|
||||
constructor(directoryPath) {
|
||||
super(`No ESLint configuration found in ${directoryPath}.`);
|
||||
this.messageTemplate = "no-config-found";
|
||||
this.messageData = { directoryPath };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class provides the functionality that enumerates every file which is
|
||||
* matched by given glob patterns and that configuration.
|
||||
*/
|
||||
class CascadingConfigArrayFactory {
|
||||
|
||||
/**
|
||||
* Initialize this enumerator.
|
||||
* @param {CascadingConfigArrayFactoryOptions} options The options.
|
||||
*/
|
||||
constructor({
|
||||
additionalPluginPool = new Map(),
|
||||
baseConfig: baseConfigData = null,
|
||||
cliConfig: cliConfigData = null,
|
||||
cwd = process.cwd(),
|
||||
ignorePath,
|
||||
resolvePluginsRelativeTo,
|
||||
rulePaths = [],
|
||||
specificConfigPath = null,
|
||||
useEslintrc = true,
|
||||
builtInRules = new Map(),
|
||||
loadRules,
|
||||
resolver,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig
|
||||
} = {}) {
|
||||
const configArrayFactory = new ConfigArrayFactory({
|
||||
additionalPluginPool,
|
||||
cwd,
|
||||
resolvePluginsRelativeTo,
|
||||
builtInRules,
|
||||
resolver,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig
|
||||
});
|
||||
|
||||
internalSlotsMap.set(this, {
|
||||
baseConfigArray: createBaseConfigArray({
|
||||
baseConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
rulePaths,
|
||||
loadRules
|
||||
}),
|
||||
baseConfigData,
|
||||
cliConfigArray: createCLIConfigArray({
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
ignorePath,
|
||||
specificConfigPath
|
||||
}),
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
configCache: new Map(),
|
||||
cwd,
|
||||
finalizeCache: new WeakMap(),
|
||||
ignorePath,
|
||||
rulePaths,
|
||||
specificConfigPath,
|
||||
useEslintrc,
|
||||
builtInRules,
|
||||
loadRules
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The path to the current working directory.
|
||||
* This is used by tests.
|
||||
* @type {string}
|
||||
*/
|
||||
get cwd() {
|
||||
const { cwd } = internalSlotsMap.get(this);
|
||||
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the config array of a given file.
|
||||
* If `filePath` was not given, it returns the config which contains only
|
||||
* `baseConfigData` and `cliConfigData`.
|
||||
* @param {string} [filePath] The file path to a file.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
|
||||
* @returns {ConfigArray} The config array of the file.
|
||||
*/
|
||||
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
|
||||
const {
|
||||
baseConfigArray,
|
||||
cliConfigArray,
|
||||
cwd
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
if (!filePath) {
|
||||
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
|
||||
}
|
||||
|
||||
const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath));
|
||||
|
||||
debug$1(`Load config files for ${directoryPath}.`);
|
||||
|
||||
return this._finalizeConfigArray(
|
||||
this._loadConfigInAncestors(directoryPath),
|
||||
directoryPath,
|
||||
ignoreNotFoundError
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the config data to override all configs.
|
||||
* Require to call `clearCache()` method after this method is called.
|
||||
* @param {ConfigData} configData The config data to override all configs.
|
||||
* @returns {void}
|
||||
*/
|
||||
setOverrideConfig(configData) {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
|
||||
slots.cliConfigData = configData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear config cache.
|
||||
* @returns {void}
|
||||
*/
|
||||
clearCache() {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
|
||||
slots.baseConfigArray = createBaseConfigArray(slots);
|
||||
slots.cliConfigArray = createCLIConfigArray(slots);
|
||||
slots.configCache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and normalize config files from the ancestor directories.
|
||||
* @param {string} directoryPath The path to a leaf directory.
|
||||
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
|
||||
* @returns {ConfigArray} The loaded config.
|
||||
* @private
|
||||
*/
|
||||
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
|
||||
const {
|
||||
baseConfigArray,
|
||||
configArrayFactory,
|
||||
configCache,
|
||||
cwd,
|
||||
useEslintrc
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
if (!useEslintrc) {
|
||||
return baseConfigArray;
|
||||
}
|
||||
|
||||
let configArray = configCache.get(directoryPath);
|
||||
|
||||
// Hit cache.
|
||||
if (configArray) {
|
||||
debug$1(`Cache hit: ${directoryPath}.`);
|
||||
return configArray;
|
||||
}
|
||||
debug$1(`No cache found: ${directoryPath}.`);
|
||||
|
||||
const homePath = os__default["default"].homedir();
|
||||
|
||||
// Consider this is root.
|
||||
if (directoryPath === homePath && cwd !== homePath) {
|
||||
debug$1("Stop traversing because of considered root.");
|
||||
if (configsExistInSubdirs) {
|
||||
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
|
||||
|
||||
if (filePath) {
|
||||
emitDeprecationWarning(
|
||||
filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
|
||||
);
|
||||
}
|
||||
}
|
||||
return this._cacheConfig(directoryPath, baseConfigArray);
|
||||
}
|
||||
|
||||
// Load the config on this directory.
|
||||
try {
|
||||
configArray = configArrayFactory.loadInDirectory(directoryPath);
|
||||
} catch (error) {
|
||||
/* istanbul ignore next */
|
||||
if (error.code === "EACCES") {
|
||||
debug$1("Stop traversing because of 'EACCES' error.");
|
||||
return this._cacheConfig(directoryPath, baseConfigArray);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (configArray.length > 0 && configArray.isRoot()) {
|
||||
debug$1("Stop traversing because of 'root:true'.");
|
||||
configArray.unshift(...baseConfigArray);
|
||||
return this._cacheConfig(directoryPath, configArray);
|
||||
}
|
||||
|
||||
// Load from the ancestors and merge it.
|
||||
const parentPath = path__default["default"].dirname(directoryPath);
|
||||
const parentConfigArray = parentPath && parentPath !== directoryPath
|
||||
? this._loadConfigInAncestors(
|
||||
parentPath,
|
||||
configsExistInSubdirs || configArray.length > 0
|
||||
)
|
||||
: baseConfigArray;
|
||||
|
||||
if (configArray.length > 0) {
|
||||
configArray.unshift(...parentConfigArray);
|
||||
} else {
|
||||
configArray = parentConfigArray;
|
||||
}
|
||||
|
||||
// Cache and return.
|
||||
return this._cacheConfig(directoryPath, configArray);
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeze and cache a given config.
|
||||
* @param {string} directoryPath The path to a directory as a cache key.
|
||||
* @param {ConfigArray} configArray The config array as a cache value.
|
||||
* @returns {ConfigArray} The `configArray` (frozen).
|
||||
*/
|
||||
_cacheConfig(directoryPath, configArray) {
|
||||
const { configCache } = internalSlotsMap.get(this);
|
||||
|
||||
Object.freeze(configArray);
|
||||
configCache.set(directoryPath, configArray);
|
||||
|
||||
return configArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize a given config array.
|
||||
* Concatenate `--config` and other CLI options.
|
||||
* @param {ConfigArray} configArray The parent config array.
|
||||
* @param {string} directoryPath The path to the leaf directory to find config files.
|
||||
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
|
||||
* @returns {ConfigArray} The loaded config.
|
||||
* @private
|
||||
*/
|
||||
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
|
||||
const {
|
||||
cliConfigArray,
|
||||
configArrayFactory,
|
||||
finalizeCache,
|
||||
useEslintrc,
|
||||
builtInRules
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
let finalConfigArray = finalizeCache.get(configArray);
|
||||
|
||||
if (!finalConfigArray) {
|
||||
finalConfigArray = configArray;
|
||||
|
||||
// Load the personal config if there are no regular config files.
|
||||
if (
|
||||
useEslintrc &&
|
||||
configArray.every(c => !c.filePath) &&
|
||||
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
|
||||
) {
|
||||
const homePath = os__default["default"].homedir();
|
||||
|
||||
debug$1("Loading the config file of the home directory:", homePath);
|
||||
|
||||
const personalConfigArray = configArrayFactory.loadInDirectory(
|
||||
homePath,
|
||||
{ name: "PersonalConfig" }
|
||||
);
|
||||
|
||||
if (
|
||||
personalConfigArray.length > 0 &&
|
||||
!directoryPath.startsWith(homePath)
|
||||
) {
|
||||
const lastElement =
|
||||
personalConfigArray[personalConfigArray.length - 1];
|
||||
|
||||
emitDeprecationWarning(
|
||||
lastElement.filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_LOAD"
|
||||
);
|
||||
}
|
||||
|
||||
finalConfigArray = finalConfigArray.concat(personalConfigArray);
|
||||
}
|
||||
|
||||
// Apply CLI options.
|
||||
if (cliConfigArray.length > 0) {
|
||||
finalConfigArray = finalConfigArray.concat(cliConfigArray);
|
||||
}
|
||||
|
||||
// Validate rule settings and environments.
|
||||
const validator = new ConfigValidator({
|
||||
builtInRules
|
||||
});
|
||||
|
||||
validator.validateConfigArray(finalConfigArray);
|
||||
|
||||
// Cache it.
|
||||
Object.freeze(finalConfigArray);
|
||||
finalizeCache.set(configArray, finalConfigArray);
|
||||
|
||||
debug$1(
|
||||
"Configuration was determined: %o on %s",
|
||||
finalConfigArray,
|
||||
directoryPath
|
||||
);
|
||||
}
|
||||
|
||||
// At least one element (the default ignore patterns) exists.
|
||||
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
|
||||
throw new ConfigurationNotFoundError(directoryPath);
|
||||
}
|
||||
|
||||
return finalConfigArray;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview Compatibility class for flat config.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("../../shared/types").Environment} Environment */
|
||||
/** @typedef {import("../../shared/types").Processor} Processor */
|
||||
|
||||
const debug = debugOrig__default["default"]("eslintrc:flat-compat");
|
||||
const cafactory = Symbol("cafactory");
|
||||
|
||||
/**
|
||||
* Translates an ESLintRC-style config object into a flag-config-style config
|
||||
* object.
|
||||
* @param {Object} eslintrcConfig An ESLintRC-style config object.
|
||||
* @param {Object} options Options to help translate the config.
|
||||
* @param {string} options.resolveConfigRelativeTo To the directory to resolve
|
||||
* configs from.
|
||||
* @param {string} options.resolvePluginsRelativeTo The directory to resolve
|
||||
* plugins from.
|
||||
* @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
|
||||
* names to objects.
|
||||
* @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
|
||||
* names to objects.
|
||||
* @returns {Object} A flag-config-style config object.
|
||||
*/
|
||||
function translateESLintRC(eslintrcConfig, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo,
|
||||
pluginEnvironments,
|
||||
pluginProcessors
|
||||
}) {
|
||||
|
||||
const flatConfig = {};
|
||||
const configs = [];
|
||||
const languageOptions = {};
|
||||
const linterOptions = {};
|
||||
const keysToCopy = ["settings", "rules", "processor"];
|
||||
const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
|
||||
const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
|
||||
|
||||
// copy over simple translations
|
||||
for (const key of keysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
flatConfig[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
|
||||
// copy over languageOptions
|
||||
for (const key of languageOptionsKeysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
|
||||
// create the languageOptions key in the flat config
|
||||
flatConfig.languageOptions = languageOptions;
|
||||
|
||||
if (key === "parser") {
|
||||
debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
|
||||
|
||||
if (eslintrcConfig[key].error) {
|
||||
throw eslintrcConfig[key].error;
|
||||
}
|
||||
|
||||
languageOptions[key] = eslintrcConfig[key].definition;
|
||||
continue;
|
||||
}
|
||||
|
||||
// clone any object values that are in the eslintrc config
|
||||
if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
|
||||
languageOptions[key] = {
|
||||
...eslintrcConfig[key]
|
||||
};
|
||||
} else {
|
||||
languageOptions[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// copy over linterOptions
|
||||
for (const key of linterOptionsKeysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
flatConfig.linterOptions = linterOptions;
|
||||
linterOptions[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
|
||||
// move ecmaVersion a level up
|
||||
if (languageOptions.parserOptions) {
|
||||
|
||||
if ("ecmaVersion" in languageOptions.parserOptions) {
|
||||
languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
|
||||
delete languageOptions.parserOptions.ecmaVersion;
|
||||
}
|
||||
|
||||
if ("sourceType" in languageOptions.parserOptions) {
|
||||
languageOptions.sourceType = languageOptions.parserOptions.sourceType;
|
||||
delete languageOptions.parserOptions.sourceType;
|
||||
}
|
||||
|
||||
// check to see if we even need parserOptions anymore and remove it if not
|
||||
if (Object.keys(languageOptions.parserOptions).length === 0) {
|
||||
delete languageOptions.parserOptions;
|
||||
}
|
||||
}
|
||||
|
||||
// overrides
|
||||
if (eslintrcConfig.criteria) {
|
||||
flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
|
||||
}
|
||||
|
||||
// translate plugins
|
||||
if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
|
||||
debug(`Translating plugins: ${eslintrcConfig.plugins}`);
|
||||
|
||||
flatConfig.plugins = {};
|
||||
|
||||
for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
|
||||
|
||||
debug(`Translating plugin: ${pluginName}`);
|
||||
debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
|
||||
|
||||
const { original: plugin, error } = eslintrcConfig.plugins[pluginName];
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
flatConfig.plugins[pluginName] = plugin;
|
||||
|
||||
// create a config for any processors
|
||||
if (plugin.processors) {
|
||||
for (const processorName of Object.keys(plugin.processors)) {
|
||||
if (processorName.startsWith(".")) {
|
||||
debug(`Assigning processor: ${pluginName}/${processorName}`);
|
||||
|
||||
configs.unshift({
|
||||
files: [`**/*${processorName}`],
|
||||
processor: pluginProcessors.get(`${pluginName}/${processorName}`)
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// translate env - must come after plugins
|
||||
if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
|
||||
for (const envName of Object.keys(eslintrcConfig.env)) {
|
||||
|
||||
// only add environments that are true
|
||||
if (eslintrcConfig.env[envName]) {
|
||||
debug(`Translating environment: ${envName}`);
|
||||
|
||||
if (environments.has(envName)) {
|
||||
|
||||
// built-in environments should be defined first
|
||||
configs.unshift(...translateESLintRC({
|
||||
criteria: eslintrcConfig.criteria,
|
||||
...environments.get(envName)
|
||||
}, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo
|
||||
}));
|
||||
} else if (pluginEnvironments.has(envName)) {
|
||||
|
||||
// if the environment comes from a plugin, it should come after the plugin config
|
||||
configs.push(...translateESLintRC({
|
||||
criteria: eslintrcConfig.criteria,
|
||||
...pluginEnvironments.get(envName)
|
||||
}, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// only add if there are actually keys in the config
|
||||
if (Object.keys(flatConfig).length > 0) {
|
||||
configs.push(flatConfig);
|
||||
}
|
||||
|
||||
return configs;
|
||||
}
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A compatibility class for working with configs.
|
||||
*/
|
||||
class FlatCompat {
|
||||
|
||||
constructor({
|
||||
baseDirectory = process.cwd(),
|
||||
resolvePluginsRelativeTo = baseDirectory,
|
||||
recommendedConfig,
|
||||
allConfig
|
||||
} = {}) {
|
||||
this.baseDirectory = baseDirectory;
|
||||
this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
|
||||
this[cafactory] = new ConfigArrayFactory({
|
||||
cwd: baseDirectory,
|
||||
resolvePluginsRelativeTo,
|
||||
getEslintAllConfig: () => {
|
||||
|
||||
if (!allConfig) {
|
||||
throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
|
||||
}
|
||||
|
||||
return allConfig;
|
||||
},
|
||||
getEslintRecommendedConfig: () => {
|
||||
|
||||
if (!recommendedConfig) {
|
||||
throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
|
||||
}
|
||||
|
||||
return recommendedConfig;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates an ESLintRC-style config into a flag-config-style config.
|
||||
* @param {Object} eslintrcConfig The ESLintRC-style config object.
|
||||
* @returns {Object} A flag-config-style config object.
|
||||
*/
|
||||
config(eslintrcConfig) {
|
||||
const eslintrcArray = this[cafactory].create(eslintrcConfig, {
|
||||
basePath: this.baseDirectory
|
||||
});
|
||||
|
||||
const flatArray = [];
|
||||
let hasIgnorePatterns = false;
|
||||
|
||||
eslintrcArray.forEach(configData => {
|
||||
if (configData.type === "config") {
|
||||
hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
|
||||
flatArray.push(...translateESLintRC(configData, {
|
||||
resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"),
|
||||
resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"),
|
||||
pluginEnvironments: eslintrcArray.pluginEnvironments,
|
||||
pluginProcessors: eslintrcArray.pluginProcessors
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
// combine ignorePatterns to emulate ESLintRC behavior better
|
||||
if (hasIgnorePatterns) {
|
||||
flatArray.unshift({
|
||||
ignores: [filePath => {
|
||||
|
||||
// Compute the final config for this file.
|
||||
// This filters config array elements by `files`/`excludedFiles` then merges the elements.
|
||||
const finalConfig = eslintrcArray.extractConfig(filePath);
|
||||
|
||||
// Test the `ignorePattern` properties of the final config.
|
||||
return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
return flatArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `env` section of an ESLintRC-style config.
|
||||
* @param {Object} envConfig The `env` section of an ESLintRC config.
|
||||
* @returns {Object[]} An array of flag-config objects representing the environments.
|
||||
*/
|
||||
env(envConfig) {
|
||||
return this.config({
|
||||
env: envConfig
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `extends` section of an ESLintRC-style config.
|
||||
* @param {...string} configsToExtend The names of the configs to load.
|
||||
* @returns {Object[]} An array of flag-config objects representing the config.
|
||||
*/
|
||||
extends(...configsToExtend) {
|
||||
return this.config({
|
||||
extends: configsToExtend
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `plugins` section of an ESLintRC-style config.
|
||||
* @param {...string} plugins The names of the plugins to load.
|
||||
* @returns {Object[]} An array of flag-config objects representing the plugins.
|
||||
*/
|
||||
plugins(...plugins) {
|
||||
return this.config({
|
||||
plugins
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @fileoverview Package exports for @eslint/eslintrc
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const Legacy = {
|
||||
ConfigArray,
|
||||
createConfigArrayFactoryContext: createContext,
|
||||
CascadingConfigArrayFactory,
|
||||
ConfigArrayFactory,
|
||||
ConfigDependency,
|
||||
ExtractedConfig,
|
||||
IgnorePattern,
|
||||
OverrideTester,
|
||||
getUsedExtractedConfigs,
|
||||
environments,
|
||||
|
||||
// shared
|
||||
ConfigOps,
|
||||
ConfigValidator,
|
||||
ModuleResolver,
|
||||
naming
|
||||
};
|
||||
|
||||
exports.FlatCompat = FlatCompat;
|
||||
exports.Legacy = Legacy;
|
||||
//# sourceMappingURL=eslintrc.cjs.map
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+532
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* @fileoverview `CascadingConfigArrayFactory` class.
|
||||
*
|
||||
* `CascadingConfigArrayFactory` class has a responsibility:
|
||||
*
|
||||
* 1. Handles cascading of config files.
|
||||
*
|
||||
* It provides two methods:
|
||||
*
|
||||
* - `getConfigArrayForFile(filePath)`
|
||||
* Get the corresponded configuration of a given file. This method doesn't
|
||||
* throw even if the given file didn't exist.
|
||||
* - `clearCache()`
|
||||
* Clear the internal cache. You have to call this method when
|
||||
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
|
||||
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import debugOrig from "debug";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
|
||||
import { ConfigArrayFactory } from "./config-array-factory.js";
|
||||
import {
|
||||
ConfigArray,
|
||||
ConfigDependency,
|
||||
IgnorePattern
|
||||
} from "./config-array/index.js";
|
||||
import ConfigValidator from "./shared/config-validator.js";
|
||||
import { emitDeprecationWarning } from "./shared/deprecation-warnings.js";
|
||||
|
||||
const debug = debugOrig("eslintrc:cascading-config-array-factory");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("./shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("./shared/types").Parser} Parser */
|
||||
/** @typedef {import("./shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("./shared/types").Rule} Rule */
|
||||
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
|
||||
|
||||
/**
|
||||
* @typedef {Object} CascadingConfigArrayFactoryOptions
|
||||
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
|
||||
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
|
||||
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
|
||||
* @property {string} [cwd] The base directory to start lookup.
|
||||
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
|
||||
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
|
||||
* @property {string} [specificConfigPath] The value of `--config` option.
|
||||
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
|
||||
* @property {Function} loadRules The function to use to load rules.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
|
||||
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
|
||||
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
|
||||
* @property {ConfigArray} cliConfigArray The config array of CLI options.
|
||||
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
|
||||
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
|
||||
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
|
||||
* @property {string} cwd The base directory to start lookup.
|
||||
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
|
||||
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
|
||||
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
|
||||
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
|
||||
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
|
||||
* @property {Function} loadRules The function to use to load rules.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
|
||||
const internalSlotsMap = new WeakMap();
|
||||
|
||||
/**
|
||||
* Create the config array from `baseConfig` and `rulePaths`.
|
||||
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
|
||||
* @returns {ConfigArray} The config array of the base configs.
|
||||
*/
|
||||
function createBaseConfigArray({
|
||||
configArrayFactory,
|
||||
baseConfigData,
|
||||
rulePaths,
|
||||
cwd,
|
||||
loadRules
|
||||
}) {
|
||||
const baseConfigArray = configArrayFactory.create(
|
||||
baseConfigData,
|
||||
{ name: "BaseConfig" }
|
||||
);
|
||||
|
||||
/*
|
||||
* Create the config array element for the default ignore patterns.
|
||||
* This element has `ignorePattern` property that ignores the default
|
||||
* patterns in the current working directory.
|
||||
*/
|
||||
baseConfigArray.unshift(configArrayFactory.create(
|
||||
{ ignorePatterns: IgnorePattern.DefaultPatterns },
|
||||
{ name: "DefaultIgnorePattern" }
|
||||
)[0]);
|
||||
|
||||
/*
|
||||
* Load rules `--rulesdir` option as a pseudo plugin.
|
||||
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
|
||||
* the rule's options with only information in the config array.
|
||||
*/
|
||||
if (rulePaths && rulePaths.length > 0) {
|
||||
baseConfigArray.push({
|
||||
type: "config",
|
||||
name: "--rulesdir",
|
||||
filePath: "",
|
||||
plugins: {
|
||||
"": new ConfigDependency({
|
||||
definition: {
|
||||
rules: rulePaths.reduce(
|
||||
(map, rulesPath) => Object.assign(
|
||||
map,
|
||||
loadRules(rulesPath, cwd)
|
||||
),
|
||||
{}
|
||||
)
|
||||
},
|
||||
filePath: "",
|
||||
id: "",
|
||||
importerName: "--rulesdir",
|
||||
importerPath: ""
|
||||
})
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return baseConfigArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the config array from CLI options.
|
||||
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
|
||||
* @returns {ConfigArray} The config array of the base configs.
|
||||
*/
|
||||
function createCLIConfigArray({
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
ignorePath,
|
||||
specificConfigPath
|
||||
}) {
|
||||
const cliConfigArray = configArrayFactory.create(
|
||||
cliConfigData,
|
||||
{ name: "CLIOptions" }
|
||||
);
|
||||
|
||||
cliConfigArray.unshift(
|
||||
...(ignorePath
|
||||
? configArrayFactory.loadESLintIgnore(ignorePath)
|
||||
: configArrayFactory.loadDefaultESLintIgnore())
|
||||
);
|
||||
|
||||
if (specificConfigPath) {
|
||||
cliConfigArray.unshift(
|
||||
...configArrayFactory.loadFile(
|
||||
specificConfigPath,
|
||||
{ name: "--config", basePath: cwd }
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return cliConfigArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* The error type when there are files matched by a glob, but all of them have been ignored.
|
||||
*/
|
||||
class ConfigurationNotFoundError extends Error {
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @param {string} directoryPath The directory path.
|
||||
*/
|
||||
constructor(directoryPath) {
|
||||
super(`No ESLint configuration found in ${directoryPath}.`);
|
||||
this.messageTemplate = "no-config-found";
|
||||
this.messageData = { directoryPath };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This class provides the functionality that enumerates every file which is
|
||||
* matched by given glob patterns and that configuration.
|
||||
*/
|
||||
class CascadingConfigArrayFactory {
|
||||
|
||||
/**
|
||||
* Initialize this enumerator.
|
||||
* @param {CascadingConfigArrayFactoryOptions} options The options.
|
||||
*/
|
||||
constructor({
|
||||
additionalPluginPool = new Map(),
|
||||
baseConfig: baseConfigData = null,
|
||||
cliConfig: cliConfigData = null,
|
||||
cwd = process.cwd(),
|
||||
ignorePath,
|
||||
resolvePluginsRelativeTo,
|
||||
rulePaths = [],
|
||||
specificConfigPath = null,
|
||||
useEslintrc = true,
|
||||
builtInRules = new Map(),
|
||||
loadRules,
|
||||
resolver,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig
|
||||
} = {}) {
|
||||
const configArrayFactory = new ConfigArrayFactory({
|
||||
additionalPluginPool,
|
||||
cwd,
|
||||
resolvePluginsRelativeTo,
|
||||
builtInRules,
|
||||
resolver,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig
|
||||
});
|
||||
|
||||
internalSlotsMap.set(this, {
|
||||
baseConfigArray: createBaseConfigArray({
|
||||
baseConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
rulePaths,
|
||||
loadRules
|
||||
}),
|
||||
baseConfigData,
|
||||
cliConfigArray: createCLIConfigArray({
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
cwd,
|
||||
ignorePath,
|
||||
specificConfigPath
|
||||
}),
|
||||
cliConfigData,
|
||||
configArrayFactory,
|
||||
configCache: new Map(),
|
||||
cwd,
|
||||
finalizeCache: new WeakMap(),
|
||||
ignorePath,
|
||||
rulePaths,
|
||||
specificConfigPath,
|
||||
useEslintrc,
|
||||
builtInRules,
|
||||
loadRules
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The path to the current working directory.
|
||||
* This is used by tests.
|
||||
* @type {string}
|
||||
*/
|
||||
get cwd() {
|
||||
const { cwd } = internalSlotsMap.get(this);
|
||||
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the config array of a given file.
|
||||
* If `filePath` was not given, it returns the config which contains only
|
||||
* `baseConfigData` and `cliConfigData`.
|
||||
* @param {string} [filePath] The file path to a file.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
|
||||
* @returns {ConfigArray} The config array of the file.
|
||||
*/
|
||||
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
|
||||
const {
|
||||
baseConfigArray,
|
||||
cliConfigArray,
|
||||
cwd
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
if (!filePath) {
|
||||
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
|
||||
}
|
||||
|
||||
const directoryPath = path.dirname(path.resolve(cwd, filePath));
|
||||
|
||||
debug(`Load config files for ${directoryPath}.`);
|
||||
|
||||
return this._finalizeConfigArray(
|
||||
this._loadConfigInAncestors(directoryPath),
|
||||
directoryPath,
|
||||
ignoreNotFoundError
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the config data to override all configs.
|
||||
* Require to call `clearCache()` method after this method is called.
|
||||
* @param {ConfigData} configData The config data to override all configs.
|
||||
* @returns {void}
|
||||
*/
|
||||
setOverrideConfig(configData) {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
|
||||
slots.cliConfigData = configData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear config cache.
|
||||
* @returns {void}
|
||||
*/
|
||||
clearCache() {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
|
||||
slots.baseConfigArray = createBaseConfigArray(slots);
|
||||
slots.cliConfigArray = createCLIConfigArray(slots);
|
||||
slots.configCache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and normalize config files from the ancestor directories.
|
||||
* @param {string} directoryPath The path to a leaf directory.
|
||||
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
|
||||
* @returns {ConfigArray} The loaded config.
|
||||
* @private
|
||||
*/
|
||||
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
|
||||
const {
|
||||
baseConfigArray,
|
||||
configArrayFactory,
|
||||
configCache,
|
||||
cwd,
|
||||
useEslintrc
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
if (!useEslintrc) {
|
||||
return baseConfigArray;
|
||||
}
|
||||
|
||||
let configArray = configCache.get(directoryPath);
|
||||
|
||||
// Hit cache.
|
||||
if (configArray) {
|
||||
debug(`Cache hit: ${directoryPath}.`);
|
||||
return configArray;
|
||||
}
|
||||
debug(`No cache found: ${directoryPath}.`);
|
||||
|
||||
const homePath = os.homedir();
|
||||
|
||||
// Consider this is root.
|
||||
if (directoryPath === homePath && cwd !== homePath) {
|
||||
debug("Stop traversing because of considered root.");
|
||||
if (configsExistInSubdirs) {
|
||||
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
|
||||
|
||||
if (filePath) {
|
||||
emitDeprecationWarning(
|
||||
filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
|
||||
);
|
||||
}
|
||||
}
|
||||
return this._cacheConfig(directoryPath, baseConfigArray);
|
||||
}
|
||||
|
||||
// Load the config on this directory.
|
||||
try {
|
||||
configArray = configArrayFactory.loadInDirectory(directoryPath);
|
||||
} catch (error) {
|
||||
/* istanbul ignore next */
|
||||
if (error.code === "EACCES") {
|
||||
debug("Stop traversing because of 'EACCES' error.");
|
||||
return this._cacheConfig(directoryPath, baseConfigArray);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (configArray.length > 0 && configArray.isRoot()) {
|
||||
debug("Stop traversing because of 'root:true'.");
|
||||
configArray.unshift(...baseConfigArray);
|
||||
return this._cacheConfig(directoryPath, configArray);
|
||||
}
|
||||
|
||||
// Load from the ancestors and merge it.
|
||||
const parentPath = path.dirname(directoryPath);
|
||||
const parentConfigArray = parentPath && parentPath !== directoryPath
|
||||
? this._loadConfigInAncestors(
|
||||
parentPath,
|
||||
configsExistInSubdirs || configArray.length > 0
|
||||
)
|
||||
: baseConfigArray;
|
||||
|
||||
if (configArray.length > 0) {
|
||||
configArray.unshift(...parentConfigArray);
|
||||
} else {
|
||||
configArray = parentConfigArray;
|
||||
}
|
||||
|
||||
// Cache and return.
|
||||
return this._cacheConfig(directoryPath, configArray);
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeze and cache a given config.
|
||||
* @param {string} directoryPath The path to a directory as a cache key.
|
||||
* @param {ConfigArray} configArray The config array as a cache value.
|
||||
* @returns {ConfigArray} The `configArray` (frozen).
|
||||
*/
|
||||
_cacheConfig(directoryPath, configArray) {
|
||||
const { configCache } = internalSlotsMap.get(this);
|
||||
|
||||
Object.freeze(configArray);
|
||||
configCache.set(directoryPath, configArray);
|
||||
|
||||
return configArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize a given config array.
|
||||
* Concatenate `--config` and other CLI options.
|
||||
* @param {ConfigArray} configArray The parent config array.
|
||||
* @param {string} directoryPath The path to the leaf directory to find config files.
|
||||
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
|
||||
* @returns {ConfigArray} The loaded config.
|
||||
* @private
|
||||
*/
|
||||
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
|
||||
const {
|
||||
cliConfigArray,
|
||||
configArrayFactory,
|
||||
finalizeCache,
|
||||
useEslintrc,
|
||||
builtInRules
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
let finalConfigArray = finalizeCache.get(configArray);
|
||||
|
||||
if (!finalConfigArray) {
|
||||
finalConfigArray = configArray;
|
||||
|
||||
// Load the personal config if there are no regular config files.
|
||||
if (
|
||||
useEslintrc &&
|
||||
configArray.every(c => !c.filePath) &&
|
||||
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
|
||||
) {
|
||||
const homePath = os.homedir();
|
||||
|
||||
debug("Loading the config file of the home directory:", homePath);
|
||||
|
||||
const personalConfigArray = configArrayFactory.loadInDirectory(
|
||||
homePath,
|
||||
{ name: "PersonalConfig" }
|
||||
);
|
||||
|
||||
if (
|
||||
personalConfigArray.length > 0 &&
|
||||
!directoryPath.startsWith(homePath)
|
||||
) {
|
||||
const lastElement =
|
||||
personalConfigArray[personalConfigArray.length - 1];
|
||||
|
||||
emitDeprecationWarning(
|
||||
lastElement.filePath,
|
||||
"ESLINT_PERSONAL_CONFIG_LOAD"
|
||||
);
|
||||
}
|
||||
|
||||
finalConfigArray = finalConfigArray.concat(personalConfigArray);
|
||||
}
|
||||
|
||||
// Apply CLI options.
|
||||
if (cliConfigArray.length > 0) {
|
||||
finalConfigArray = finalConfigArray.concat(cliConfigArray);
|
||||
}
|
||||
|
||||
// Validate rule settings and environments.
|
||||
const validator = new ConfigValidator({
|
||||
builtInRules
|
||||
});
|
||||
|
||||
validator.validateConfigArray(finalConfigArray);
|
||||
|
||||
// Cache it.
|
||||
Object.freeze(finalConfigArray);
|
||||
finalizeCache.set(configArray, finalConfigArray);
|
||||
|
||||
debug(
|
||||
"Configuration was determined: %o on %s",
|
||||
finalConfigArray,
|
||||
directoryPath
|
||||
);
|
||||
}
|
||||
|
||||
// At least one element (the default ignore patterns) exists.
|
||||
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
|
||||
throw new ConfigurationNotFoundError(directoryPath);
|
||||
}
|
||||
|
||||
return finalConfigArray;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export { CascadingConfigArrayFactory };
|
||||
Generated
Vendored
+1151
@@ -0,0 +1,1151 @@
|
||||
/**
|
||||
* @fileoverview The factory of `ConfigArray` objects.
|
||||
*
|
||||
* This class provides methods to create `ConfigArray` instance.
|
||||
*
|
||||
* - `create(configData, options)`
|
||||
* Create a `ConfigArray` instance from a config data. This is to handle CLI
|
||||
* options except `--config`.
|
||||
* - `loadFile(filePath, options)`
|
||||
* Create a `ConfigArray` instance from a config file. This is to handle
|
||||
* `--config` option. If the file was not found, throws the following error:
|
||||
* - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
|
||||
* - If the filename was `package.json`, an IO error or an
|
||||
* `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
|
||||
* - Otherwise, an IO error such as `ENOENT`.
|
||||
* - `loadInDirectory(directoryPath, options)`
|
||||
* Create a `ConfigArray` instance from a config file which is on a given
|
||||
* directory. This tries to load `.eslintrc.*` or `package.json`. If not
|
||||
* found, returns an empty `ConfigArray`.
|
||||
* - `loadESLintIgnore(filePath)`
|
||||
* Create a `ConfigArray` instance from a config file that is `.eslintignore`
|
||||
* format. This is to handle `--ignore-path` option.
|
||||
* - `loadDefaultESLintIgnore()`
|
||||
* Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
|
||||
* the current working directory.
|
||||
*
|
||||
* `ConfigArrayFactory` class has the responsibility that loads configuration
|
||||
* files, including loading `extends`, `parser`, and `plugins`. The created
|
||||
* `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
|
||||
*
|
||||
* But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
|
||||
* handles cascading and hierarchy.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import debugOrig from "debug";
|
||||
import fs from "fs";
|
||||
import importFresh from "import-fresh";
|
||||
import { createRequire } from "module";
|
||||
import path from "path";
|
||||
import stripComments from "strip-json-comments";
|
||||
|
||||
import {
|
||||
ConfigArray,
|
||||
ConfigDependency,
|
||||
IgnorePattern,
|
||||
OverrideTester
|
||||
} from "./config-array/index.js";
|
||||
import ConfigValidator from "./shared/config-validator.js";
|
||||
import * as naming from "./shared/naming.js";
|
||||
import * as ModuleResolver from "./shared/relative-module-resolver.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
const debug = debugOrig("eslintrc:config-array-factory");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const configFilenames = [
|
||||
".eslintrc.js",
|
||||
".eslintrc.cjs",
|
||||
".eslintrc.yaml",
|
||||
".eslintrc.yml",
|
||||
".eslintrc.json",
|
||||
".eslintrc",
|
||||
"package.json"
|
||||
];
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("./shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
|
||||
/** @typedef {import("./shared/types").Parser} Parser */
|
||||
/** @typedef {import("./shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("./shared/types").Rule} Rule */
|
||||
/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
|
||||
/** @typedef {ConfigArray[0]} ConfigArrayElement */
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryOptions
|
||||
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
|
||||
* @property {string} [cwd] The path to the current working directory.
|
||||
* @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryInternalSlots
|
||||
* @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
|
||||
* @property {string} cwd The path to the current working directory.
|
||||
* @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
|
||||
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
|
||||
* @property {Object} [resolver=ModuleResolver] The module resolver object.
|
||||
* @property {string} eslintAllPath The path to the definitions for eslint:all.
|
||||
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
|
||||
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
|
||||
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryLoadingContext
|
||||
* @property {string} filePath The path to the current configuration.
|
||||
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @property {string} name The name of the current configuration.
|
||||
* @property {string} pluginBasePath The base path to resolve plugins.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayFactoryLoadingContext
|
||||
* @property {string} filePath The path to the current configuration.
|
||||
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @property {string} name The name of the current configuration.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
|
||||
const internalSlotsMap = new WeakMap();
|
||||
|
||||
/** @type {WeakMap<object, Plugin>} */
|
||||
const normalizedPlugins = new WeakMap();
|
||||
|
||||
/**
|
||||
* Check if a given string is a file path.
|
||||
* @param {string} nameOrPath A module name or file path.
|
||||
* @returns {boolean} `true` if the `nameOrPath` is a file path.
|
||||
*/
|
||||
function isFilePath(nameOrPath) {
|
||||
return (
|
||||
/^\.{1,2}[/\\]/u.test(nameOrPath) ||
|
||||
path.isAbsolute(nameOrPath)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper for synchronously reading file contents.
|
||||
* @param {string} filePath The filename to read.
|
||||
* @returns {string} The file contents, with the BOM removed.
|
||||
* @private
|
||||
*/
|
||||
function readFile(filePath) {
|
||||
return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a YAML configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadYAMLConfigFile(filePath) {
|
||||
debug(`Loading YAML config file: ${filePath}`);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
try {
|
||||
|
||||
// empty YAML file can be null, so always use
|
||||
return yaml.load(readFile(filePath)) || {};
|
||||
} catch (e) {
|
||||
debug(`Error reading YAML file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a JSON configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadJSONConfigFile(filePath) {
|
||||
debug(`Loading JSON config file: ${filePath}`);
|
||||
|
||||
try {
|
||||
return JSON.parse(stripComments(readFile(filePath)));
|
||||
} catch (e) {
|
||||
debug(`Error reading JSON file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
e.messageTemplate = "failed-to-read-json";
|
||||
e.messageData = {
|
||||
path: filePath,
|
||||
message: e.message
|
||||
};
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a legacy (.eslintrc) configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadLegacyConfigFile(filePath) {
|
||||
debug(`Loading legacy config file: ${filePath}`);
|
||||
|
||||
// lazy load YAML to improve performance when not used
|
||||
const yaml = require("js-yaml");
|
||||
|
||||
try {
|
||||
return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
|
||||
} catch (e) {
|
||||
debug("Error reading YAML file: %s\n%o", filePath, e);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a JavaScript configuration from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadJSConfigFile(filePath) {
|
||||
debug(`Loading JS config file: ${filePath}`);
|
||||
try {
|
||||
return importFresh(filePath);
|
||||
} catch (e) {
|
||||
debug(`Error reading JavaScript file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a configuration from a package.json file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {ConfigData} The configuration object from the file.
|
||||
* @throws {Error} If the file cannot be read.
|
||||
* @private
|
||||
*/
|
||||
function loadPackageJSONConfigFile(filePath) {
|
||||
debug(`Loading package.json config file: ${filePath}`);
|
||||
try {
|
||||
const packageData = loadJSONConfigFile(filePath);
|
||||
|
||||
if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
|
||||
throw Object.assign(
|
||||
new Error("package.json file doesn't have 'eslintConfig' field."),
|
||||
{ code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
|
||||
);
|
||||
}
|
||||
|
||||
return packageData.eslintConfig;
|
||||
} catch (e) {
|
||||
debug(`Error reading package.json file: ${filePath}`);
|
||||
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a `.eslintignore` from a file.
|
||||
* @param {string} filePath The filename to load.
|
||||
* @returns {string[]} The ignore patterns from the file.
|
||||
* @private
|
||||
*/
|
||||
function loadESLintIgnoreFile(filePath) {
|
||||
debug(`Loading .eslintignore file: ${filePath}`);
|
||||
|
||||
try {
|
||||
return readFile(filePath)
|
||||
.split(/\r?\n/gu)
|
||||
.filter(line => line.trim() !== "" && !line.startsWith("#"));
|
||||
} catch (e) {
|
||||
debug(`Error reading .eslintignore file: ${filePath}`);
|
||||
e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an error to notify about a missing config to extend from.
|
||||
* @param {string} configName The name of the missing config.
|
||||
* @param {string} importerName The name of the config that imported the missing config
|
||||
* @param {string} messageTemplate The text template to source error strings from.
|
||||
* @returns {Error} The error object to throw
|
||||
* @private
|
||||
*/
|
||||
function configInvalidError(configName, importerName, messageTemplate) {
|
||||
return Object.assign(
|
||||
new Error(`Failed to load config "${configName}" to extend from.`),
|
||||
{
|
||||
messageTemplate,
|
||||
messageData: { configName, importerName }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a configuration file regardless of the source. Inspects the file path
|
||||
* to determine the correctly way to load the config file.
|
||||
* @param {string} filePath The path to the configuration.
|
||||
* @returns {ConfigData|null} The configuration information.
|
||||
* @private
|
||||
*/
|
||||
function loadConfigFile(filePath) {
|
||||
switch (path.extname(filePath)) {
|
||||
case ".js":
|
||||
case ".cjs":
|
||||
return loadJSConfigFile(filePath);
|
||||
|
||||
case ".json":
|
||||
if (path.basename(filePath) === "package.json") {
|
||||
return loadPackageJSONConfigFile(filePath);
|
||||
}
|
||||
return loadJSONConfigFile(filePath);
|
||||
|
||||
case ".yaml":
|
||||
case ".yml":
|
||||
return loadYAMLConfigFile(filePath);
|
||||
|
||||
default:
|
||||
return loadLegacyConfigFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write debug log.
|
||||
* @param {string} request The requested module name.
|
||||
* @param {string} relativeTo The file path to resolve the request relative to.
|
||||
* @param {string} filePath The resolved file path.
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeDebugLogForLoading(request, relativeTo, filePath) {
|
||||
/* istanbul ignore next */
|
||||
if (debug.enabled) {
|
||||
let nameAndVersion = null;
|
||||
|
||||
try {
|
||||
const packageJsonPath = ModuleResolver.resolve(
|
||||
`${request}/package.json`,
|
||||
relativeTo
|
||||
);
|
||||
const { version = "unknown" } = require(packageJsonPath);
|
||||
|
||||
nameAndVersion = `${request}@${version}`;
|
||||
} catch (error) {
|
||||
debug("package.json was not found:", error.message);
|
||||
nameAndVersion = request;
|
||||
}
|
||||
|
||||
debug("Loaded: %s (%s)", nameAndVersion, filePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new context with default values.
|
||||
* @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
|
||||
* @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
|
||||
* @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
|
||||
* @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
|
||||
* @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
|
||||
* @returns {ConfigArrayFactoryLoadingContext} The created context.
|
||||
*/
|
||||
function createContext(
|
||||
{ cwd, resolvePluginsRelativeTo },
|
||||
providedType,
|
||||
providedName,
|
||||
providedFilePath,
|
||||
providedMatchBasePath
|
||||
) {
|
||||
const filePath = providedFilePath
|
||||
? path.resolve(cwd, providedFilePath)
|
||||
: "";
|
||||
const matchBasePath =
|
||||
(providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||
|
||||
(filePath && path.dirname(filePath)) ||
|
||||
cwd;
|
||||
const name =
|
||||
providedName ||
|
||||
(filePath && path.relative(cwd, filePath)) ||
|
||||
"";
|
||||
const pluginBasePath =
|
||||
resolvePluginsRelativeTo ||
|
||||
(filePath && path.dirname(filePath)) ||
|
||||
cwd;
|
||||
const type = providedType || "config";
|
||||
|
||||
return { filePath, matchBasePath, name, pluginBasePath, type };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given plugin.
|
||||
* - Ensure the object to have four properties: configs, environments, processors, and rules.
|
||||
* - Ensure the object to not have other properties.
|
||||
* @param {Plugin} plugin The plugin to normalize.
|
||||
* @returns {Plugin} The normalized plugin.
|
||||
*/
|
||||
function normalizePlugin(plugin) {
|
||||
|
||||
// first check the cache
|
||||
let normalizedPlugin = normalizedPlugins.get(plugin);
|
||||
|
||||
if (normalizedPlugin) {
|
||||
return normalizedPlugin;
|
||||
}
|
||||
|
||||
normalizedPlugin = {
|
||||
configs: plugin.configs || {},
|
||||
environments: plugin.environments || {},
|
||||
processors: plugin.processors || {},
|
||||
rules: plugin.rules || {}
|
||||
};
|
||||
|
||||
// save the reference for later
|
||||
normalizedPlugins.set(plugin, normalizedPlugin);
|
||||
|
||||
return normalizedPlugin;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The factory of `ConfigArray` objects.
|
||||
*/
|
||||
class ConfigArrayFactory {
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
|
||||
*/
|
||||
constructor({
|
||||
additionalPluginPool = new Map(),
|
||||
cwd = process.cwd(),
|
||||
resolvePluginsRelativeTo,
|
||||
builtInRules,
|
||||
resolver = ModuleResolver,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
} = {}) {
|
||||
internalSlotsMap.set(this, {
|
||||
additionalPluginPool,
|
||||
cwd,
|
||||
resolvePluginsRelativeTo:
|
||||
resolvePluginsRelativeTo &&
|
||||
path.resolve(cwd, resolvePluginsRelativeTo),
|
||||
builtInRules,
|
||||
resolver,
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `ConfigArray` instance from a config data.
|
||||
* @param {ConfigData|null} configData The config data to create.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.filePath] The path to this config data.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config.
|
||||
*/
|
||||
create(configData, { basePath, filePath, name } = {}) {
|
||||
if (!configData) {
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
const slots = internalSlotsMap.get(this);
|
||||
const ctx = createContext(slots, "config", name, filePath, basePath);
|
||||
const elements = this._normalizeConfigData(configData, ctx);
|
||||
|
||||
return new ConfigArray(...elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a config file.
|
||||
* @param {string} filePath The path to a config file.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config.
|
||||
*/
|
||||
loadFile(filePath, { basePath, name } = {}) {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
const ctx = createContext(slots, "config", name, filePath, basePath);
|
||||
|
||||
return new ConfigArray(...this._loadConfigData(ctx));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the config file on a given directory if exists.
|
||||
* @param {string} directoryPath The path to a directory.
|
||||
* @param {Object} [options] The options.
|
||||
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
|
||||
* @param {string} [options.name] The config name.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadInDirectory(directoryPath, { basePath, name } = {}) {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
|
||||
for (const filename of configFilenames) {
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"config",
|
||||
name,
|
||||
path.join(directoryPath, filename),
|
||||
basePath
|
||||
);
|
||||
|
||||
if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) {
|
||||
let configData;
|
||||
|
||||
try {
|
||||
configData = loadConfigFile(ctx.filePath);
|
||||
} catch (error) {
|
||||
if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (configData) {
|
||||
debug(`Config file found: ${ctx.filePath}`);
|
||||
return new ConfigArray(
|
||||
...this._normalizeConfigData(configData, ctx)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug(`Config file not found on ${directoryPath}`);
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a config file on a given directory exists or not.
|
||||
* @param {string} directoryPath The path to a directory.
|
||||
* @returns {string | null} The path to the found config file. If not found then null.
|
||||
*/
|
||||
static getPathToConfigFileInDirectory(directoryPath) {
|
||||
for (const filename of configFilenames) {
|
||||
const filePath = path.join(directoryPath, filename);
|
||||
|
||||
if (fs.existsSync(filePath)) {
|
||||
if (filename === "package.json") {
|
||||
try {
|
||||
loadPackageJSONConfigFile(filePath);
|
||||
return filePath;
|
||||
} catch { /* ignore */ }
|
||||
} else {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.eslintignore` file.
|
||||
* @param {string} filePath The path to a `.eslintignore` file to load.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadESLintIgnore(filePath) {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"ignore",
|
||||
void 0,
|
||||
filePath,
|
||||
slots.cwd
|
||||
);
|
||||
const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
|
||||
|
||||
return new ConfigArray(
|
||||
...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `.eslintignore` file in the current working directory.
|
||||
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
|
||||
*/
|
||||
loadDefaultESLintIgnore() {
|
||||
const slots = internalSlotsMap.get(this);
|
||||
const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
|
||||
const packageJsonPath = path.resolve(slots.cwd, "package.json");
|
||||
|
||||
if (fs.existsSync(eslintIgnorePath)) {
|
||||
return this.loadESLintIgnore(eslintIgnorePath);
|
||||
}
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
const data = loadJSONConfigFile(packageJsonPath);
|
||||
|
||||
if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
|
||||
if (!Array.isArray(data.eslintIgnore)) {
|
||||
throw new Error("Package.json eslintIgnore property requires an array of paths");
|
||||
}
|
||||
const ctx = createContext(
|
||||
slots,
|
||||
"ignore",
|
||||
"eslintIgnore in package.json",
|
||||
packageJsonPath,
|
||||
slots.cwd
|
||||
);
|
||||
|
||||
return new ConfigArray(
|
||||
...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new ConfigArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given config file.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} Loaded config.
|
||||
* @private
|
||||
*/
|
||||
_loadConfigData(ctx) {
|
||||
return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given `.eslintignore` data to config array elements.
|
||||
* @param {string[]} ignorePatterns The patterns to ignore files.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeESLintIgnoreData(ignorePatterns, ctx) {
|
||||
const elements = this._normalizeObjectConfigData(
|
||||
{ ignorePatterns },
|
||||
ctx
|
||||
);
|
||||
|
||||
// Set `ignorePattern.loose` flag for backward compatibility.
|
||||
for (const element of elements) {
|
||||
if (element.ignorePattern) {
|
||||
element.ignorePattern.loose = true;
|
||||
}
|
||||
yield element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_normalizeConfigData(configData, ctx) {
|
||||
const validator = new ConfigValidator();
|
||||
|
||||
validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
|
||||
return this._normalizeObjectConfigData(configData, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData|OverrideConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeObjectConfigData(configData, ctx) {
|
||||
const { files, excludedFiles, ...configBody } = configData;
|
||||
const criteria = OverrideTester.create(
|
||||
files,
|
||||
excludedFiles,
|
||||
ctx.matchBasePath
|
||||
);
|
||||
const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
|
||||
|
||||
// Apply the criteria to every element.
|
||||
for (const element of elements) {
|
||||
|
||||
/*
|
||||
* Merge the criteria.
|
||||
* This is for the `overrides` entries that came from the
|
||||
* configurations of `overrides[].extends`.
|
||||
*/
|
||||
element.criteria = OverrideTester.and(criteria, element.criteria);
|
||||
|
||||
/*
|
||||
* Remove `root` property to ignore `root` settings which came from
|
||||
* `extends` in `overrides`.
|
||||
*/
|
||||
if (element.criteria) {
|
||||
element.root = void 0;
|
||||
}
|
||||
|
||||
yield element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a given config to an array.
|
||||
* @param {ConfigData} configData The config data to normalize.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
*_normalizeObjectConfigDataBody(
|
||||
{
|
||||
env,
|
||||
extends: extend,
|
||||
globals,
|
||||
ignorePatterns,
|
||||
noInlineConfig,
|
||||
parser: parserName,
|
||||
parserOptions,
|
||||
plugins: pluginList,
|
||||
processor,
|
||||
reportUnusedDisableDirectives,
|
||||
root,
|
||||
rules,
|
||||
settings,
|
||||
overrides: overrideList = []
|
||||
},
|
||||
ctx
|
||||
) {
|
||||
const extendList = Array.isArray(extend) ? extend : [extend];
|
||||
const ignorePattern = ignorePatterns && new IgnorePattern(
|
||||
Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
|
||||
ctx.matchBasePath
|
||||
);
|
||||
|
||||
// Flatten `extends`.
|
||||
for (const extendName of extendList.filter(Boolean)) {
|
||||
yield* this._loadExtends(extendName, ctx);
|
||||
}
|
||||
|
||||
// Load parser & plugins.
|
||||
const parser = parserName && this._loadParser(parserName, ctx);
|
||||
const plugins = pluginList && this._loadPlugins(pluginList, ctx);
|
||||
|
||||
// Yield pseudo config data for file extension processors.
|
||||
if (plugins) {
|
||||
yield* this._takeFileExtensionProcessors(plugins, ctx);
|
||||
}
|
||||
|
||||
// Yield the config data except `extends` and `overrides`.
|
||||
yield {
|
||||
|
||||
// Debug information.
|
||||
type: ctx.type,
|
||||
name: ctx.name,
|
||||
filePath: ctx.filePath,
|
||||
|
||||
// Config data.
|
||||
criteria: null,
|
||||
env,
|
||||
globals,
|
||||
ignorePattern,
|
||||
noInlineConfig,
|
||||
parser,
|
||||
parserOptions,
|
||||
plugins,
|
||||
processor,
|
||||
reportUnusedDisableDirectives,
|
||||
root,
|
||||
rules,
|
||||
settings
|
||||
};
|
||||
|
||||
// Flatten `overries`.
|
||||
for (let i = 0; i < overrideList.length; ++i) {
|
||||
yield* this._normalizeObjectConfigData(
|
||||
overrideList[i],
|
||||
{ ...ctx, name: `${ctx.name}#overrides[${i}]` }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtends(extendName, ctx) {
|
||||
debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
|
||||
try {
|
||||
if (extendName.startsWith("eslint:")) {
|
||||
return this._loadExtendedBuiltInConfig(extendName, ctx);
|
||||
}
|
||||
if (extendName.startsWith("plugin:")) {
|
||||
return this._loadExtendedPluginConfig(extendName, ctx);
|
||||
}
|
||||
return this._loadExtendedShareableConfig(extendName, ctx);
|
||||
} catch (error) {
|
||||
error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedBuiltInConfig(extendName, ctx) {
|
||||
const {
|
||||
eslintAllPath,
|
||||
getEslintAllConfig,
|
||||
eslintRecommendedPath,
|
||||
getEslintRecommendedConfig
|
||||
} = internalSlotsMap.get(this);
|
||||
|
||||
if (extendName === "eslint:recommended") {
|
||||
const name = `${ctx.name} » ${extendName}`;
|
||||
|
||||
if (getEslintRecommendedConfig) {
|
||||
if (typeof getEslintRecommendedConfig !== "function") {
|
||||
throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);
|
||||
}
|
||||
return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" });
|
||||
}
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
name,
|
||||
filePath: eslintRecommendedPath
|
||||
});
|
||||
}
|
||||
if (extendName === "eslint:all") {
|
||||
const name = `${ctx.name} » ${extendName}`;
|
||||
|
||||
if (getEslintAllConfig) {
|
||||
if (typeof getEslintAllConfig !== "function") {
|
||||
throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);
|
||||
}
|
||||
return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" });
|
||||
}
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
name,
|
||||
filePath: eslintAllPath
|
||||
});
|
||||
}
|
||||
|
||||
throw configInvalidError(extendName, ctx.name, "extend-config-missing");
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedPluginConfig(extendName, ctx) {
|
||||
const slashIndex = extendName.lastIndexOf("/");
|
||||
|
||||
if (slashIndex === -1) {
|
||||
throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
|
||||
}
|
||||
|
||||
const pluginName = extendName.slice("plugin:".length, slashIndex);
|
||||
const configName = extendName.slice(slashIndex + 1);
|
||||
|
||||
if (isFilePath(pluginName)) {
|
||||
throw new Error("'extends' cannot use a file path for plugins.");
|
||||
}
|
||||
|
||||
const plugin = this._loadPlugin(pluginName, ctx);
|
||||
const configData =
|
||||
plugin.definition &&
|
||||
plugin.definition.configs[configName];
|
||||
|
||||
if (configData) {
|
||||
return this._normalizeConfigData(configData, {
|
||||
...ctx,
|
||||
filePath: plugin.filePath || ctx.filePath,
|
||||
name: `${ctx.name} » plugin:${plugin.id}/${configName}`
|
||||
});
|
||||
}
|
||||
|
||||
throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configs of an element in `extends`.
|
||||
* @param {string} extendName The name of a base config.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
|
||||
* @private
|
||||
*/
|
||||
_loadExtendedShareableConfig(extendName, ctx) {
|
||||
const { cwd, resolver } = internalSlotsMap.get(this);
|
||||
const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
|
||||
let request;
|
||||
|
||||
if (isFilePath(extendName)) {
|
||||
request = extendName;
|
||||
} else if (extendName.startsWith(".")) {
|
||||
request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
|
||||
} else {
|
||||
request = naming.normalizePackageName(
|
||||
extendName,
|
||||
"eslint-config"
|
||||
);
|
||||
}
|
||||
|
||||
let filePath;
|
||||
|
||||
try {
|
||||
filePath = resolver.resolve(request, relativeTo);
|
||||
} catch (error) {
|
||||
/* istanbul ignore else */
|
||||
if (error && error.code === "MODULE_NOT_FOUND") {
|
||||
throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
writeDebugLogForLoading(request, relativeTo, filePath);
|
||||
return this._loadConfigData({
|
||||
...ctx,
|
||||
filePath,
|
||||
name: `${ctx.name} » ${request}`
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load given plugins.
|
||||
* @param {string[]} names The plugin names to load.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {Record<string,DependentPlugin>} The loaded parser.
|
||||
* @private
|
||||
*/
|
||||
_loadPlugins(names, ctx) {
|
||||
return names.reduce((map, name) => {
|
||||
if (isFilePath(name)) {
|
||||
throw new Error("Plugins array cannot includes file paths.");
|
||||
}
|
||||
const plugin = this._loadPlugin(name, ctx);
|
||||
|
||||
map[plugin.id] = plugin;
|
||||
|
||||
return map;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given parser.
|
||||
* @param {string} nameOrPath The package name or the path to a parser file.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {DependentParser} The loaded parser.
|
||||
*/
|
||||
_loadParser(nameOrPath, ctx) {
|
||||
debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
|
||||
|
||||
const { cwd, resolver } = internalSlotsMap.get(this);
|
||||
const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
|
||||
|
||||
try {
|
||||
const filePath = resolver.resolve(nameOrPath, relativeTo);
|
||||
|
||||
writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
|
||||
|
||||
return new ConfigDependency({
|
||||
definition: require(filePath),
|
||||
filePath,
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
// If the parser name is "espree", load the espree of ESLint.
|
||||
if (nameOrPath === "espree") {
|
||||
debug("Fallback espree.");
|
||||
return new ConfigDependency({
|
||||
definition: require("espree"),
|
||||
filePath: require.resolve("espree"),
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
|
||||
error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
|
||||
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id: nameOrPath,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a given plugin.
|
||||
* @param {string} name The plugin name to load.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {DependentPlugin} The loaded plugin.
|
||||
* @private
|
||||
*/
|
||||
_loadPlugin(name, ctx) {
|
||||
debug("Loading plugin %j from %s", name, ctx.filePath);
|
||||
|
||||
const { additionalPluginPool, resolver } = internalSlotsMap.get(this);
|
||||
const request = naming.normalizePackageName(name, "eslint-plugin");
|
||||
const id = naming.getShorthandName(request, "eslint-plugin");
|
||||
const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
|
||||
|
||||
if (name.match(/\s+/u)) {
|
||||
const error = Object.assign(
|
||||
new Error(`Whitespace found in plugin name '${name}'`),
|
||||
{
|
||||
messageTemplate: "whitespace-found",
|
||||
messageData: { pluginName: request }
|
||||
}
|
||||
);
|
||||
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
// Check for additional pool.
|
||||
const plugin =
|
||||
additionalPluginPool.get(request) ||
|
||||
additionalPluginPool.get(id);
|
||||
|
||||
if (plugin) {
|
||||
return new ConfigDependency({
|
||||
definition: normalizePlugin(plugin),
|
||||
original: plugin,
|
||||
filePath: "", // It's unknown where the plugin came from.
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
let filePath;
|
||||
let error;
|
||||
|
||||
try {
|
||||
filePath = resolver.resolve(request, relativeTo);
|
||||
} catch (resolveError) {
|
||||
error = resolveError;
|
||||
/* istanbul ignore else */
|
||||
if (error && error.code === "MODULE_NOT_FOUND") {
|
||||
error.messageTemplate = "plugin-missing";
|
||||
error.messageData = {
|
||||
pluginName: request,
|
||||
resolvePluginsRelativeTo: ctx.pluginBasePath,
|
||||
importerName: ctx.name
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filePath) {
|
||||
try {
|
||||
writeDebugLogForLoading(request, relativeTo, filePath);
|
||||
|
||||
const startTime = Date.now();
|
||||
const pluginDefinition = require(filePath);
|
||||
|
||||
debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
|
||||
|
||||
return new ConfigDependency({
|
||||
definition: normalizePlugin(pluginDefinition),
|
||||
original: pluginDefinition,
|
||||
filePath,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
} catch (loadError) {
|
||||
error = loadError;
|
||||
}
|
||||
}
|
||||
|
||||
debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
|
||||
error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
|
||||
return new ConfigDependency({
|
||||
error,
|
||||
id,
|
||||
importerName: ctx.name,
|
||||
importerPath: ctx.filePath
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Take file expression processors as config array elements.
|
||||
* @param {Record<string,DependentPlugin>} plugins The plugin definitions.
|
||||
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
|
||||
* @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
|
||||
* @private
|
||||
*/
|
||||
*_takeFileExtensionProcessors(plugins, ctx) {
|
||||
for (const pluginId of Object.keys(plugins)) {
|
||||
const processors =
|
||||
plugins[pluginId] &&
|
||||
plugins[pluginId].definition &&
|
||||
plugins[pluginId].definition.processors;
|
||||
|
||||
if (!processors) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const processorId of Object.keys(processors)) {
|
||||
if (processorId.startsWith(".")) {
|
||||
yield* this._normalizeObjectConfigData(
|
||||
{
|
||||
files: [`*${processorId}`],
|
||||
processor: `${pluginId}/${processorId}`
|
||||
},
|
||||
{
|
||||
...ctx,
|
||||
type: "implicit-processor",
|
||||
name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { ConfigArrayFactory, createContext };
|
||||
Generated
Vendored
+523
@@ -0,0 +1,523 @@
|
||||
/**
|
||||
* @fileoverview `ConfigArray` class.
|
||||
*
|
||||
* `ConfigArray` class expresses the full of a configuration. It has the entry
|
||||
* config file, base config files that were extended, loaded parsers, and loaded
|
||||
* plugins.
|
||||
*
|
||||
* `ConfigArray` class provides three properties and two methods.
|
||||
*
|
||||
* - `pluginEnvironments`
|
||||
* - `pluginProcessors`
|
||||
* - `pluginRules`
|
||||
* The `Map` objects that contain the members of all plugins that this
|
||||
* config array contains. Those map objects don't have mutation methods.
|
||||
* Those keys are the member ID such as `pluginId/memberName`.
|
||||
* - `isRoot()`
|
||||
* If `true` then this configuration has `root:true` property.
|
||||
* - `extractConfig(filePath)`
|
||||
* Extract the final configuration for a given file. This means merging
|
||||
* every config array element which that `criteria` property matched. The
|
||||
* `filePath` argument must be an absolute path.
|
||||
*
|
||||
* `ConfigArrayFactory` provides the loading logic of config files.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import { ExtractedConfig } from "./extracted-config.js";
|
||||
import { IgnorePattern } from "./ignore-pattern.js";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Define types for VSCode IntelliSense.
|
||||
/** @typedef {import("../../shared/types").Environment} Environment */
|
||||
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
|
||||
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
|
||||
/** @typedef {import("../../shared/types").Rule} Rule */
|
||||
/** @typedef {import("../../shared/types").Plugin} Plugin */
|
||||
/** @typedef {import("../../shared/types").Processor} Processor */
|
||||
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
|
||||
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayElement
|
||||
* @property {string} name The name of this config element.
|
||||
* @property {string} filePath The path to the source file of this config element.
|
||||
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
|
||||
* @property {Record<string, boolean>|undefined} env The environment settings.
|
||||
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
|
||||
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
|
||||
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
|
||||
* @property {DependentParser|undefined} parser The parser loader.
|
||||
* @property {Object|undefined} parserOptions The parser options.
|
||||
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
|
||||
* @property {string|undefined} processor The processor name to refer plugin's processor.
|
||||
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
|
||||
* @property {boolean|undefined} root The flag to express root.
|
||||
* @property {Record<string, RuleConf>|undefined} rules The rule settings
|
||||
* @property {Object|undefined} settings The shared settings.
|
||||
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigArrayInternalSlots
|
||||
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
|
||||
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
|
||||
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
|
||||
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
|
||||
*/
|
||||
|
||||
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
|
||||
const internalSlotsMap = new class extends WeakMap {
|
||||
get(key) {
|
||||
let value = super.get(key);
|
||||
|
||||
if (!value) {
|
||||
value = {
|
||||
cache: new Map(),
|
||||
envMap: null,
|
||||
processorMap: null,
|
||||
ruleMap: null
|
||||
};
|
||||
super.set(key, value);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}();
|
||||
|
||||
/**
|
||||
* Get the indices which are matched to a given file.
|
||||
* @param {ConfigArrayElement[]} elements The elements.
|
||||
* @param {string} filePath The path to a target file.
|
||||
* @returns {number[]} The indices.
|
||||
*/
|
||||
function getMatchedIndices(elements, filePath) {
|
||||
const indices = [];
|
||||
|
||||
for (let i = elements.length - 1; i >= 0; --i) {
|
||||
const element = elements[i];
|
||||
|
||||
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
|
||||
indices.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
return indices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a non-null object.
|
||||
* @param {any} x The value to check.
|
||||
* @returns {boolean} `true` if the value is a non-null object.
|
||||
*/
|
||||
function isNonNullObject(x) {
|
||||
return typeof x === "object" && x !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two objects.
|
||||
*
|
||||
* Assign every property values of `y` to `x` if `x` doesn't have the property.
|
||||
* If `x`'s property value is an object, it does recursive.
|
||||
* @param {Object} target The destination to merge
|
||||
* @param {Object|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergeWithoutOverwrite(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isNonNullObject(target[key])) {
|
||||
mergeWithoutOverwrite(target[key], source[key]);
|
||||
} else if (target[key] === void 0) {
|
||||
if (isNonNullObject(source[key])) {
|
||||
target[key] = Array.isArray(source[key]) ? [] : {};
|
||||
mergeWithoutOverwrite(target[key], source[key]);
|
||||
} else if (source[key] !== void 0) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The error for plugin conflicts.
|
||||
*/
|
||||
class PluginConflictError extends Error {
|
||||
|
||||
/**
|
||||
* Initialize this error object.
|
||||
* @param {string} pluginId The plugin ID.
|
||||
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
|
||||
*/
|
||||
constructor(pluginId, plugins) {
|
||||
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
|
||||
this.messageTemplate = "plugin-conflict";
|
||||
this.messageData = { pluginId, plugins };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge plugins.
|
||||
* `target`'s definition is prior to `source`'s.
|
||||
* @param {Record<string, DependentPlugin>} target The destination to merge
|
||||
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergePlugins(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
const targetValue = target[key];
|
||||
const sourceValue = source[key];
|
||||
|
||||
// Adopt the plugin which was found at first.
|
||||
if (targetValue === void 0) {
|
||||
if (sourceValue.error) {
|
||||
throw sourceValue.error;
|
||||
}
|
||||
target[key] = sourceValue;
|
||||
} else if (sourceValue.filePath !== targetValue.filePath) {
|
||||
throw new PluginConflictError(key, [
|
||||
{
|
||||
filePath: targetValue.filePath,
|
||||
importerName: targetValue.importerName
|
||||
},
|
||||
{
|
||||
filePath: sourceValue.filePath,
|
||||
importerName: sourceValue.importerName
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge rule configs.
|
||||
* `target`'s definition is prior to `source`'s.
|
||||
* @param {Record<string, Array>} target The destination to merge
|
||||
* @param {Record<string, RuleConf>|undefined} source The source to merge.
|
||||
* @returns {void}
|
||||
*/
|
||||
function mergeRuleConfigs(target, source) {
|
||||
if (!isNonNullObject(source)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
if (key === "__proto__") {
|
||||
continue;
|
||||
}
|
||||
const targetDef = target[key];
|
||||
const sourceDef = source[key];
|
||||
|
||||
// Adopt the rule config which was found at first.
|
||||
if (targetDef === void 0) {
|
||||
if (Array.isArray(sourceDef)) {
|
||||
target[key] = [...sourceDef];
|
||||
} else {
|
||||
target[key] = [sourceDef];
|
||||
}
|
||||
|
||||
/*
|
||||
* If the first found rule config is severity only and the current rule
|
||||
* config has options, merge the severity and the options.
|
||||
*/
|
||||
} else if (
|
||||
targetDef.length === 1 &&
|
||||
Array.isArray(sourceDef) &&
|
||||
sourceDef.length >= 2
|
||||
) {
|
||||
targetDef.push(...sourceDef.slice(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the extracted config.
|
||||
* @param {ConfigArray} instance The config elements.
|
||||
* @param {number[]} indices The indices to use.
|
||||
* @returns {ExtractedConfig} The extracted config.
|
||||
*/
|
||||
function createConfig(instance, indices) {
|
||||
const config = new ExtractedConfig();
|
||||
const ignorePatterns = [];
|
||||
|
||||
// Merge elements.
|
||||
for (const index of indices) {
|
||||
const element = instance[index];
|
||||
|
||||
// Adopt the parser which was found at first.
|
||||
if (!config.parser && element.parser) {
|
||||
if (element.parser.error) {
|
||||
throw element.parser.error;
|
||||
}
|
||||
config.parser = element.parser;
|
||||
}
|
||||
|
||||
// Adopt the processor which was found at first.
|
||||
if (!config.processor && element.processor) {
|
||||
config.processor = element.processor;
|
||||
}
|
||||
|
||||
// Adopt the noInlineConfig which was found at first.
|
||||
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
|
||||
config.noInlineConfig = element.noInlineConfig;
|
||||
config.configNameOfNoInlineConfig = element.name;
|
||||
}
|
||||
|
||||
// Adopt the reportUnusedDisableDirectives which was found at first.
|
||||
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
|
||||
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
|
||||
}
|
||||
|
||||
// Collect ignorePatterns
|
||||
if (element.ignorePattern) {
|
||||
ignorePatterns.push(element.ignorePattern);
|
||||
}
|
||||
|
||||
// Merge others.
|
||||
mergeWithoutOverwrite(config.env, element.env);
|
||||
mergeWithoutOverwrite(config.globals, element.globals);
|
||||
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
|
||||
mergeWithoutOverwrite(config.settings, element.settings);
|
||||
mergePlugins(config.plugins, element.plugins);
|
||||
mergeRuleConfigs(config.rules, element.rules);
|
||||
}
|
||||
|
||||
// Create the predicate function for ignore patterns.
|
||||
if (ignorePatterns.length > 0) {
|
||||
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect definitions.
|
||||
* @template T, U
|
||||
* @param {string} pluginId The plugin ID for prefix.
|
||||
* @param {Record<string,T>} defs The definitions to collect.
|
||||
* @param {Map<string, U>} map The map to output.
|
||||
* @param {function(T): U} [normalize] The normalize function for each value.
|
||||
* @returns {void}
|
||||
*/
|
||||
function collect(pluginId, defs, map, normalize) {
|
||||
if (defs) {
|
||||
const prefix = pluginId && `${pluginId}/`;
|
||||
|
||||
for (const [key, value] of Object.entries(defs)) {
|
||||
map.set(
|
||||
`${prefix}${key}`,
|
||||
normalize ? normalize(value) : value
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a rule definition.
|
||||
* @param {Function|Rule} rule The rule definition to normalize.
|
||||
* @returns {Rule} The normalized rule definition.
|
||||
*/
|
||||
function normalizePluginRule(rule) {
|
||||
return typeof rule === "function" ? { create: rule } : rule;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the mutation methods from a given map.
|
||||
* @param {Map<any, any>} map The map object to delete.
|
||||
* @returns {void}
|
||||
*/
|
||||
function deleteMutationMethods(map) {
|
||||
Object.defineProperties(map, {
|
||||
clear: { configurable: true, value: void 0 },
|
||||
delete: { configurable: true, value: void 0 },
|
||||
set: { configurable: true, value: void 0 }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
|
||||
* @param {ConfigArrayElement[]} elements The config elements.
|
||||
* @param {ConfigArrayInternalSlots} slots The internal slots.
|
||||
* @returns {void}
|
||||
*/
|
||||
function initPluginMemberMaps(elements, slots) {
|
||||
const processed = new Set();
|
||||
|
||||
slots.envMap = new Map();
|
||||
slots.processorMap = new Map();
|
||||
slots.ruleMap = new Map();
|
||||
|
||||
for (const element of elements) {
|
||||
if (!element.plugins) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const [pluginId, value] of Object.entries(element.plugins)) {
|
||||
const plugin = value.definition;
|
||||
|
||||
if (!plugin || processed.has(pluginId)) {
|
||||
continue;
|
||||
}
|
||||
processed.add(pluginId);
|
||||
|
||||
collect(pluginId, plugin.environments, slots.envMap);
|
||||
collect(pluginId, plugin.processors, slots.processorMap);
|
||||
collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
|
||||
}
|
||||
}
|
||||
|
||||
deleteMutationMethods(slots.envMap);
|
||||
deleteMutationMethods(slots.processorMap);
|
||||
deleteMutationMethods(slots.ruleMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
|
||||
* @param {ConfigArray} instance The config elements.
|
||||
* @returns {ConfigArrayInternalSlots} The extracted config.
|
||||
*/
|
||||
function ensurePluginMemberMaps(instance) {
|
||||
const slots = internalSlotsMap.get(instance);
|
||||
|
||||
if (!slots.ruleMap) {
|
||||
initPluginMemberMaps(instance, slots);
|
||||
}
|
||||
|
||||
return slots;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The Config Array.
|
||||
*
|
||||
* `ConfigArray` instance contains all settings, parsers, and plugins.
|
||||
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
|
||||
* extract, merge and get only the config data which is related to an arbitrary
|
||||
* file.
|
||||
* @extends {Array<ConfigArrayElement>}
|
||||
*/
|
||||
class ConfigArray extends Array {
|
||||
|
||||
/**
|
||||
* Get the plugin environments.
|
||||
* The returned map cannot be mutated.
|
||||
* @type {ReadonlyMap<string, Environment>} The plugin environments.
|
||||
*/
|
||||
get pluginEnvironments() {
|
||||
return ensurePluginMemberMaps(this).envMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin processors.
|
||||
* The returned map cannot be mutated.
|
||||
* @type {ReadonlyMap<string, Processor>} The plugin processors.
|
||||
*/
|
||||
get pluginProcessors() {
|
||||
return ensurePluginMemberMaps(this).processorMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin rules.
|
||||
* The returned map cannot be mutated.
|
||||
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
|
||||
*/
|
||||
get pluginRules() {
|
||||
return ensurePluginMemberMaps(this).ruleMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this config has `root` flag.
|
||||
* @returns {boolean} `true` if this config array is root.
|
||||
*/
|
||||
isRoot() {
|
||||
for (let i = this.length - 1; i >= 0; --i) {
|
||||
const root = this[i].root;
|
||||
|
||||
if (typeof root === "boolean") {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the config data which is related to a given file.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {ExtractedConfig} The extracted config data.
|
||||
*/
|
||||
extractConfig(filePath) {
|
||||
const { cache } = internalSlotsMap.get(this);
|
||||
const indices = getMatchedIndices(this, filePath);
|
||||
const cacheKey = indices.join(",");
|
||||
|
||||
if (!cache.has(cacheKey)) {
|
||||
cache.set(cacheKey, createConfig(this, indices));
|
||||
}
|
||||
|
||||
return cache.get(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a given path is an additional lint target.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {boolean} `true` if the file is an additional lint target.
|
||||
*/
|
||||
isAdditionalTargetPath(filePath) {
|
||||
for (const { criteria, type } of this) {
|
||||
if (
|
||||
type === "config" &&
|
||||
criteria &&
|
||||
!criteria.endsWithWildcard &&
|
||||
criteria.test(filePath)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the used extracted configs.
|
||||
* CLIEngine will use this method to collect used deprecated rules.
|
||||
* @param {ConfigArray} instance The config array object to get.
|
||||
* @returns {ExtractedConfig[]} The used extracted configs.
|
||||
* @private
|
||||
*/
|
||||
function getUsedExtractedConfigs(instance) {
|
||||
const { cache } = internalSlotsMap.get(instance);
|
||||
|
||||
return Array.from(cache.values());
|
||||
}
|
||||
|
||||
|
||||
export {
|
||||
ConfigArray,
|
||||
getUsedExtractedConfigs
|
||||
};
|
||||
Generated
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @fileoverview `ConfigDependency` class.
|
||||
*
|
||||
* `ConfigDependency` class expresses a loaded parser or plugin.
|
||||
*
|
||||
* If the parser or plugin was loaded successfully, it has `definition` property
|
||||
* and `filePath` property. Otherwise, it has `error` property.
|
||||
*
|
||||
* When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
|
||||
* omits `definition` property.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
|
||||
* or plugins.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
import util from "util";
|
||||
|
||||
/**
|
||||
* The class is to store parsers or plugins.
|
||||
* This class hides the loaded object from `JSON.stringify()` and `console.log`.
|
||||
* @template T
|
||||
*/
|
||||
class ConfigDependency {
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {Object} data The dependency data.
|
||||
* @param {T} [data.definition] The dependency if the loading succeeded.
|
||||
* @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.
|
||||
* @param {Error} [data.error] The error object if the loading failed.
|
||||
* @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
|
||||
* @param {string} data.id The ID of this dependency.
|
||||
* @param {string} data.importerName The name of the config file which loads this dependency.
|
||||
* @param {string} data.importerPath The path to the config file which loads this dependency.
|
||||
*/
|
||||
constructor({
|
||||
definition = null,
|
||||
original = null,
|
||||
error = null,
|
||||
filePath = null,
|
||||
id,
|
||||
importerName,
|
||||
importerPath
|
||||
}) {
|
||||
|
||||
/**
|
||||
* The loaded dependency if the loading succeeded.
|
||||
* @type {T|null}
|
||||
*/
|
||||
this.definition = definition;
|
||||
|
||||
/**
|
||||
* The original dependency as loaded directly from disk if the loading succeeded.
|
||||
* @type {T|null}
|
||||
*/
|
||||
this.original = original;
|
||||
|
||||
/**
|
||||
* The error object if the loading failed.
|
||||
* @type {Error|null}
|
||||
*/
|
||||
this.error = error;
|
||||
|
||||
/**
|
||||
* The loaded dependency if the loading succeeded.
|
||||
* @type {string|null}
|
||||
*/
|
||||
this.filePath = filePath;
|
||||
|
||||
/**
|
||||
* The ID of this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.id = id;
|
||||
|
||||
/**
|
||||
* The name of the config file which loads this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.importerName = importerName;
|
||||
|
||||
/**
|
||||
* The path to the config file which loads this dependency.
|
||||
* @type {string}
|
||||
*/
|
||||
this.importerPath = importerPath;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} a JSON compatible object.
|
||||
*/
|
||||
toJSON() {
|
||||
const obj = this[util.inspect.custom]();
|
||||
|
||||
// Display `error.message` (`Error#message` is unenumerable).
|
||||
if (obj.error instanceof Error) {
|
||||
obj.error = { ...obj.error, message: obj.error.message };
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} an object to display by `console.log()`.
|
||||
*/
|
||||
[util.inspect.custom]() {
|
||||
const {
|
||||
definition: _ignore1, // eslint-disable-line no-unused-vars
|
||||
original: _ignore2, // eslint-disable-line no-unused-vars
|
||||
...obj
|
||||
} = this;
|
||||
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
/** @typedef {ConfigDependency<import("../../shared/types").Parser>} DependentParser */
|
||||
/** @typedef {ConfigDependency<import("../../shared/types").Plugin>} DependentPlugin */
|
||||
|
||||
export { ConfigDependency };
|
||||
Generated
Vendored
+145
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* @fileoverview `ExtractedConfig` class.
|
||||
*
|
||||
* `ExtractedConfig` class expresses a final configuration for a specific file.
|
||||
*
|
||||
* It provides one method.
|
||||
*
|
||||
* - `toCompatibleObjectAsConfigFileContent()`
|
||||
* Convert this configuration to the compatible object as the content of
|
||||
* config files. It converts the loaded parser and plugins to strings.
|
||||
* `CLIEngine#getConfigForFile(filePath)` method uses this method.
|
||||
*
|
||||
* `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
import { IgnorePattern } from "./ignore-pattern.js";
|
||||
|
||||
// For VSCode intellisense
|
||||
/** @typedef {import("../../shared/types").ConfigData} ConfigData */
|
||||
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
|
||||
/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
|
||||
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
|
||||
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
|
||||
|
||||
/**
|
||||
* Check if `xs` starts with `ys`.
|
||||
* @template T
|
||||
* @param {T[]} xs The array to check.
|
||||
* @param {T[]} ys The array that may be the first part of `xs`.
|
||||
* @returns {boolean} `true` if `xs` starts with `ys`.
|
||||
*/
|
||||
function startsWith(xs, ys) {
|
||||
return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The class for extracted config data.
|
||||
*/
|
||||
class ExtractedConfig {
|
||||
constructor() {
|
||||
|
||||
/**
|
||||
* The config name what `noInlineConfig` setting came from.
|
||||
* @type {string}
|
||||
*/
|
||||
this.configNameOfNoInlineConfig = "";
|
||||
|
||||
/**
|
||||
* Environments.
|
||||
* @type {Record<string, boolean>}
|
||||
*/
|
||||
this.env = {};
|
||||
|
||||
/**
|
||||
* Global variables.
|
||||
* @type {Record<string, GlobalConf>}
|
||||
*/
|
||||
this.globals = {};
|
||||
|
||||
/**
|
||||
* The glob patterns that ignore to lint.
|
||||
* @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
|
||||
*/
|
||||
this.ignores = void 0;
|
||||
|
||||
/**
|
||||
* The flag that disables directive comments.
|
||||
* @type {boolean|undefined}
|
||||
*/
|
||||
this.noInlineConfig = void 0;
|
||||
|
||||
/**
|
||||
* Parser definition.
|
||||
* @type {DependentParser|null}
|
||||
*/
|
||||
this.parser = null;
|
||||
|
||||
/**
|
||||
* Options for the parser.
|
||||
* @type {Object}
|
||||
*/
|
||||
this.parserOptions = {};
|
||||
|
||||
/**
|
||||
* Plugin definitions.
|
||||
* @type {Record<string, DependentPlugin>}
|
||||
*/
|
||||
this.plugins = {};
|
||||
|
||||
/**
|
||||
* Processor ID.
|
||||
* @type {string|null}
|
||||
*/
|
||||
this.processor = null;
|
||||
|
||||
/**
|
||||
* The flag that reports unused `eslint-disable` directive comments.
|
||||
* @type {boolean|undefined}
|
||||
*/
|
||||
this.reportUnusedDisableDirectives = void 0;
|
||||
|
||||
/**
|
||||
* Rule settings.
|
||||
* @type {Record<string, [SeverityConf, ...any[]]>}
|
||||
*/
|
||||
this.rules = {};
|
||||
|
||||
/**
|
||||
* Shared settings.
|
||||
* @type {Object}
|
||||
*/
|
||||
this.settings = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert this config to the compatible object as a config file content.
|
||||
* @returns {ConfigData} The converted object.
|
||||
*/
|
||||
toCompatibleObjectAsConfigFileContent() {
|
||||
const {
|
||||
/* eslint-disable no-unused-vars */
|
||||
configNameOfNoInlineConfig: _ignore1,
|
||||
processor: _ignore2,
|
||||
/* eslint-enable no-unused-vars */
|
||||
ignores,
|
||||
...config
|
||||
} = this;
|
||||
|
||||
config.parser = config.parser && config.parser.filePath;
|
||||
config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
|
||||
config.ignorePatterns = ignores ? ignores.patterns : [];
|
||||
|
||||
// Strip the default patterns from `ignorePatterns`.
|
||||
if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
|
||||
config.ignorePatterns =
|
||||
config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
export { ExtractedConfig };
|
||||
Generated
Vendored
+238
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* @fileoverview `IgnorePattern` class.
|
||||
*
|
||||
* `IgnorePattern` class has the set of glob patterns and the base path.
|
||||
*
|
||||
* It provides two static methods.
|
||||
*
|
||||
* - `IgnorePattern.createDefaultIgnore(cwd)`
|
||||
* Create the default predicate function.
|
||||
* - `IgnorePattern.createIgnore(ignorePatterns)`
|
||||
* Create the predicate function from multiple `IgnorePattern` objects.
|
||||
*
|
||||
* It provides two properties and a method.
|
||||
*
|
||||
* - `patterns`
|
||||
* The glob patterns that ignore to lint.
|
||||
* - `basePath`
|
||||
* The base path of the glob patterns. If absolute paths existed in the
|
||||
* glob patterns, those are handled as relative paths to the base path.
|
||||
* - `getPatternsRelativeTo(basePath)`
|
||||
* Get `patterns` as modified for a given base path. It modifies the
|
||||
* absolute paths in the patterns as prepending the difference of two base
|
||||
* paths.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
|
||||
* `ignorePatterns` properties.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import assert from "assert";
|
||||
import path from "path";
|
||||
import ignore from "ignore";
|
||||
import debugOrig from "debug";
|
||||
|
||||
const debug = debugOrig("eslintrc:ignore-pattern");
|
||||
|
||||
/** @typedef {ReturnType<import("ignore").default>} Ignore */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Get the path to the common ancestor directory of given paths.
|
||||
* @param {string[]} sourcePaths The paths to calculate the common ancestor.
|
||||
* @returns {string} The path to the common ancestor directory.
|
||||
*/
|
||||
function getCommonAncestorPath(sourcePaths) {
|
||||
let result = sourcePaths[0];
|
||||
|
||||
for (let i = 1; i < sourcePaths.length; ++i) {
|
||||
const a = result;
|
||||
const b = sourcePaths[i];
|
||||
|
||||
// Set the shorter one (it's the common ancestor if one includes the other).
|
||||
result = a.length < b.length ? a : b;
|
||||
|
||||
// Set the common ancestor.
|
||||
for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
|
||||
if (a[j] !== b[j]) {
|
||||
result = a.slice(0, lastSepPos);
|
||||
break;
|
||||
}
|
||||
if (a[j] === path.sep) {
|
||||
lastSepPos = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resolvedResult = result || path.sep;
|
||||
|
||||
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
|
||||
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
|
||||
resolvedResult += path.sep;
|
||||
}
|
||||
return resolvedResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make relative path.
|
||||
* @param {string} from The source path to get relative path.
|
||||
* @param {string} to The destination path to get relative path.
|
||||
* @returns {string} The relative path.
|
||||
*/
|
||||
function relative(from, to) {
|
||||
const relPath = path.relative(from, to);
|
||||
|
||||
if (path.sep === "/") {
|
||||
return relPath;
|
||||
}
|
||||
return relPath.split(path.sep).join("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the trailing slash if existed.
|
||||
* @param {string} filePath The path to check.
|
||||
* @returns {string} The trailing slash if existed.
|
||||
*/
|
||||
function dirSuffix(filePath) {
|
||||
const isDir = (
|
||||
filePath.endsWith(path.sep) ||
|
||||
(process.platform === "win32" && filePath.endsWith("/"))
|
||||
);
|
||||
|
||||
return isDir ? "/" : "";
|
||||
}
|
||||
|
||||
const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
|
||||
const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
class IgnorePattern {
|
||||
|
||||
/**
|
||||
* The default patterns.
|
||||
* @type {string[]}
|
||||
*/
|
||||
static get DefaultPatterns() {
|
||||
return DefaultPatterns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the default predicate function.
|
||||
* @param {string} cwd The current working directory.
|
||||
* @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
|
||||
* The preficate function.
|
||||
* The first argument is an absolute path that is checked.
|
||||
* The second argument is the flag to not ignore dotfiles.
|
||||
* If the predicate function returned `true`, it means the path should be ignored.
|
||||
*/
|
||||
static createDefaultIgnore(cwd) {
|
||||
return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the predicate function from multiple `IgnorePattern` objects.
|
||||
* @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
|
||||
* @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
|
||||
* The preficate function.
|
||||
* The first argument is an absolute path that is checked.
|
||||
* The second argument is the flag to not ignore dotfiles.
|
||||
* If the predicate function returned `true`, it means the path should be ignored.
|
||||
*/
|
||||
static createIgnore(ignorePatterns) {
|
||||
debug("Create with: %o", ignorePatterns);
|
||||
|
||||
const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
|
||||
const patterns = [].concat(
|
||||
...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
|
||||
);
|
||||
const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
|
||||
const dotIg = ignore({ allowRelativePaths: true }).add(patterns);
|
||||
|
||||
debug(" processed: %o", { basePath, patterns });
|
||||
|
||||
return Object.assign(
|
||||
(filePath, dot = false) => {
|
||||
assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
|
||||
const relPathRaw = relative(basePath, filePath);
|
||||
const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
|
||||
const adoptedIg = dot ? dotIg : ig;
|
||||
const result = relPath !== "" && adoptedIg.ignores(relPath);
|
||||
|
||||
debug("Check", { filePath, dot, relativePath: relPath, result });
|
||||
return result;
|
||||
},
|
||||
{ basePath, patterns }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a new `IgnorePattern` instance.
|
||||
* @param {string[]} patterns The glob patterns that ignore to lint.
|
||||
* @param {string} basePath The base path of `patterns`.
|
||||
*/
|
||||
constructor(patterns, basePath) {
|
||||
assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
|
||||
|
||||
/**
|
||||
* The glob patterns that ignore to lint.
|
||||
* @type {string[]}
|
||||
*/
|
||||
this.patterns = patterns;
|
||||
|
||||
/**
|
||||
* The base path of `patterns`.
|
||||
* @type {string}
|
||||
*/
|
||||
this.basePath = basePath;
|
||||
|
||||
/**
|
||||
* If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
|
||||
*
|
||||
* It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
|
||||
* It's `false` as-is for `ignorePatterns` property in config files.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.loose = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get `patterns` as modified for a given base path. It modifies the
|
||||
* absolute paths in the patterns as prepending the difference of two base
|
||||
* paths.
|
||||
* @param {string} newBasePath The base path.
|
||||
* @returns {string[]} Modifired patterns.
|
||||
*/
|
||||
getPatternsRelativeTo(newBasePath) {
|
||||
assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
|
||||
const { basePath, loose, patterns } = this;
|
||||
|
||||
if (newBasePath === basePath) {
|
||||
return patterns;
|
||||
}
|
||||
const prefix = `/${relative(newBasePath, basePath)}`;
|
||||
|
||||
return patterns.map(pattern => {
|
||||
const negative = pattern.startsWith("!");
|
||||
const head = negative ? "!" : "";
|
||||
const body = negative ? pattern.slice(1) : pattern;
|
||||
|
||||
if (body.startsWith("/") || body.startsWith("../")) {
|
||||
return `${head}${prefix}${body}`;
|
||||
}
|
||||
return loose ? pattern : `${head}${prefix}/**/${body}`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { IgnorePattern };
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @fileoverview `ConfigArray` class.
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
import { ConfigArray, getUsedExtractedConfigs } from "./config-array.js";
|
||||
import { ConfigDependency } from "./config-dependency.js";
|
||||
import { ExtractedConfig } from "./extracted-config.js";
|
||||
import { IgnorePattern } from "./ignore-pattern.js";
|
||||
import { OverrideTester } from "./override-tester.js";
|
||||
|
||||
export {
|
||||
ConfigArray,
|
||||
ConfigDependency,
|
||||
ExtractedConfig,
|
||||
IgnorePattern,
|
||||
OverrideTester,
|
||||
getUsedExtractedConfigs
|
||||
};
|
||||
Generated
Vendored
+225
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* @fileoverview `OverrideTester` class.
|
||||
*
|
||||
* `OverrideTester` class handles `files` property and `excludedFiles` property
|
||||
* of `overrides` config.
|
||||
*
|
||||
* It provides one method.
|
||||
*
|
||||
* - `test(filePath)`
|
||||
* Test if a file path matches the pair of `files` property and
|
||||
* `excludedFiles` property. The `filePath` argument must be an absolute
|
||||
* path.
|
||||
*
|
||||
* `ConfigArrayFactory` creates `OverrideTester` objects when it processes
|
||||
* `overrides` properties.
|
||||
*
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
import assert from "assert";
|
||||
import path from "path";
|
||||
import util from "util";
|
||||
import minimatch from "minimatch";
|
||||
|
||||
const { Minimatch } = minimatch;
|
||||
|
||||
const minimatchOpts = { dot: true, matchBase: true };
|
||||
|
||||
/**
|
||||
* @typedef {Object} Pattern
|
||||
* @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
|
||||
* @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normalize a given pattern to an array.
|
||||
* @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
|
||||
* @returns {string[]|null} Normalized patterns.
|
||||
* @private
|
||||
*/
|
||||
function normalizePatterns(patterns) {
|
||||
if (Array.isArray(patterns)) {
|
||||
return patterns.filter(Boolean);
|
||||
}
|
||||
if (typeof patterns === "string" && patterns) {
|
||||
return [patterns];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the matchers of given patterns.
|
||||
* @param {string[]} patterns The patterns.
|
||||
* @returns {InstanceType<Minimatch>[] | null} The matchers.
|
||||
*/
|
||||
function toMatcher(patterns) {
|
||||
if (patterns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return patterns.map(pattern => {
|
||||
if (/^\.[/\\]/u.test(pattern)) {
|
||||
return new Minimatch(
|
||||
pattern.slice(2),
|
||||
|
||||
// `./*.js` should not match with `subdir/foo.js`
|
||||
{ ...minimatchOpts, matchBase: false }
|
||||
);
|
||||
}
|
||||
return new Minimatch(pattern, minimatchOpts);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a given matcher to string.
|
||||
* @param {Pattern} matchers The matchers.
|
||||
* @returns {string} The string expression of the matcher.
|
||||
*/
|
||||
function patternToJson({ includes, excludes }) {
|
||||
return {
|
||||
includes: includes && includes.map(m => m.pattern),
|
||||
excludes: excludes && excludes.map(m => m.pattern)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The class to test given paths are matched by the patterns.
|
||||
*/
|
||||
class OverrideTester {
|
||||
|
||||
/**
|
||||
* Create a tester with given criteria.
|
||||
* If there are no criteria, returns `null`.
|
||||
* @param {string|string[]} files The glob patterns for included files.
|
||||
* @param {string|string[]} excludedFiles The glob patterns for excluded files.
|
||||
* @param {string} basePath The path to the base directory to test paths.
|
||||
* @returns {OverrideTester|null} The created instance or `null`.
|
||||
*/
|
||||
static create(files, excludedFiles, basePath) {
|
||||
const includePatterns = normalizePatterns(files);
|
||||
const excludePatterns = normalizePatterns(excludedFiles);
|
||||
let endsWithWildcard = false;
|
||||
|
||||
if (includePatterns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Rejects absolute paths or relative paths to parents.
|
||||
for (const pattern of includePatterns) {
|
||||
if (path.isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
if (pattern.endsWith("*")) {
|
||||
endsWithWildcard = true;
|
||||
}
|
||||
}
|
||||
for (const pattern of excludePatterns) {
|
||||
if (path.isAbsolute(pattern) || pattern.includes("..")) {
|
||||
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
|
||||
}
|
||||
}
|
||||
|
||||
const includes = toMatcher(includePatterns);
|
||||
const excludes = toMatcher(excludePatterns);
|
||||
|
||||
return new OverrideTester(
|
||||
[{ includes, excludes }],
|
||||
basePath,
|
||||
endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combine two testers by logical and.
|
||||
* If either of the testers was `null`, returns the other tester.
|
||||
* The `basePath` property of the two must be the same value.
|
||||
* @param {OverrideTester|null} a A tester.
|
||||
* @param {OverrideTester|null} b Another tester.
|
||||
* @returns {OverrideTester|null} Combined tester.
|
||||
*/
|
||||
static and(a, b) {
|
||||
if (!b) {
|
||||
return a && new OverrideTester(
|
||||
a.patterns,
|
||||
a.basePath,
|
||||
a.endsWithWildcard
|
||||
);
|
||||
}
|
||||
if (!a) {
|
||||
return new OverrideTester(
|
||||
b.patterns,
|
||||
b.basePath,
|
||||
b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
assert.strictEqual(a.basePath, b.basePath);
|
||||
return new OverrideTester(
|
||||
a.patterns.concat(b.patterns),
|
||||
a.basePath,
|
||||
a.endsWithWildcard || b.endsWithWildcard
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize this instance.
|
||||
* @param {Pattern[]} patterns The matchers.
|
||||
* @param {string} basePath The base path.
|
||||
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
|
||||
*/
|
||||
constructor(patterns, basePath, endsWithWildcard = false) {
|
||||
|
||||
/** @type {Pattern[]} */
|
||||
this.patterns = patterns;
|
||||
|
||||
/** @type {string} */
|
||||
this.basePath = basePath;
|
||||
|
||||
/** @type {boolean} */
|
||||
this.endsWithWildcard = endsWithWildcard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a given path is matched or not.
|
||||
* @param {string} filePath The absolute path to the target file.
|
||||
* @returns {boolean} `true` if the path was matched.
|
||||
*/
|
||||
test(filePath) {
|
||||
if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
|
||||
throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
|
||||
}
|
||||
const relativePath = path.relative(this.basePath, filePath);
|
||||
|
||||
return this.patterns.every(({ includes, excludes }) => (
|
||||
(!includes || includes.some(m => m.match(relativePath))) &&
|
||||
(!excludes || !excludes.some(m => m.match(relativePath)))
|
||||
));
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} a JSON compatible object.
|
||||
*/
|
||||
toJSON() {
|
||||
if (this.patterns.length === 1) {
|
||||
return {
|
||||
...patternToJson(this.patterns[0]),
|
||||
basePath: this.basePath
|
||||
};
|
||||
}
|
||||
return {
|
||||
AND: this.patterns.map(patternToJson),
|
||||
basePath: this.basePath
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line jsdoc/require-description
|
||||
/**
|
||||
* @returns {Object} an object to display by `console.log()`.
|
||||
*/
|
||||
[util.inspect.custom]() {
|
||||
return this.toJSON();
|
||||
}
|
||||
}
|
||||
|
||||
export { OverrideTester };
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* @fileoverview Compatibility class for flat config.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
import createDebug from "debug";
|
||||
import path from "path";
|
||||
|
||||
import environments from "../conf/environments.js";
|
||||
import { ConfigArrayFactory } from "./config-array-factory.js";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("../../shared/types").Environment} Environment */
|
||||
/** @typedef {import("../../shared/types").Processor} Processor */
|
||||
|
||||
const debug = createDebug("eslintrc:flat-compat");
|
||||
const cafactory = Symbol("cafactory");
|
||||
|
||||
/**
|
||||
* Translates an ESLintRC-style config object into a flag-config-style config
|
||||
* object.
|
||||
* @param {Object} eslintrcConfig An ESLintRC-style config object.
|
||||
* @param {Object} options Options to help translate the config.
|
||||
* @param {string} options.resolveConfigRelativeTo To the directory to resolve
|
||||
* configs from.
|
||||
* @param {string} options.resolvePluginsRelativeTo The directory to resolve
|
||||
* plugins from.
|
||||
* @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
|
||||
* names to objects.
|
||||
* @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
|
||||
* names to objects.
|
||||
* @returns {Object} A flag-config-style config object.
|
||||
*/
|
||||
function translateESLintRC(eslintrcConfig, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo,
|
||||
pluginEnvironments,
|
||||
pluginProcessors
|
||||
}) {
|
||||
|
||||
const flatConfig = {};
|
||||
const configs = [];
|
||||
const languageOptions = {};
|
||||
const linterOptions = {};
|
||||
const keysToCopy = ["settings", "rules", "processor"];
|
||||
const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
|
||||
const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
|
||||
|
||||
// copy over simple translations
|
||||
for (const key of keysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
flatConfig[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
|
||||
// copy over languageOptions
|
||||
for (const key of languageOptionsKeysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
|
||||
// create the languageOptions key in the flat config
|
||||
flatConfig.languageOptions = languageOptions;
|
||||
|
||||
if (key === "parser") {
|
||||
debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
|
||||
|
||||
if (eslintrcConfig[key].error) {
|
||||
throw eslintrcConfig[key].error;
|
||||
}
|
||||
|
||||
languageOptions[key] = eslintrcConfig[key].definition;
|
||||
continue;
|
||||
}
|
||||
|
||||
// clone any object values that are in the eslintrc config
|
||||
if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
|
||||
languageOptions[key] = {
|
||||
...eslintrcConfig[key]
|
||||
};
|
||||
} else {
|
||||
languageOptions[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// copy over linterOptions
|
||||
for (const key of linterOptionsKeysToCopy) {
|
||||
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
|
||||
flatConfig.linterOptions = linterOptions;
|
||||
linterOptions[key] = eslintrcConfig[key];
|
||||
}
|
||||
}
|
||||
|
||||
// move ecmaVersion a level up
|
||||
if (languageOptions.parserOptions) {
|
||||
|
||||
if ("ecmaVersion" in languageOptions.parserOptions) {
|
||||
languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
|
||||
delete languageOptions.parserOptions.ecmaVersion;
|
||||
}
|
||||
|
||||
if ("sourceType" in languageOptions.parserOptions) {
|
||||
languageOptions.sourceType = languageOptions.parserOptions.sourceType;
|
||||
delete languageOptions.parserOptions.sourceType;
|
||||
}
|
||||
|
||||
// check to see if we even need parserOptions anymore and remove it if not
|
||||
if (Object.keys(languageOptions.parserOptions).length === 0) {
|
||||
delete languageOptions.parserOptions;
|
||||
}
|
||||
}
|
||||
|
||||
// overrides
|
||||
if (eslintrcConfig.criteria) {
|
||||
flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
|
||||
}
|
||||
|
||||
// translate plugins
|
||||
if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
|
||||
debug(`Translating plugins: ${eslintrcConfig.plugins}`);
|
||||
|
||||
flatConfig.plugins = {};
|
||||
|
||||
for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
|
||||
|
||||
debug(`Translating plugin: ${pluginName}`);
|
||||
debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
|
||||
|
||||
const { original: plugin, error } = eslintrcConfig.plugins[pluginName];
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
flatConfig.plugins[pluginName] = plugin;
|
||||
|
||||
// create a config for any processors
|
||||
if (plugin.processors) {
|
||||
for (const processorName of Object.keys(plugin.processors)) {
|
||||
if (processorName.startsWith(".")) {
|
||||
debug(`Assigning processor: ${pluginName}/${processorName}`);
|
||||
|
||||
configs.unshift({
|
||||
files: [`**/*${processorName}`],
|
||||
processor: pluginProcessors.get(`${pluginName}/${processorName}`)
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// translate env - must come after plugins
|
||||
if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
|
||||
for (const envName of Object.keys(eslintrcConfig.env)) {
|
||||
|
||||
// only add environments that are true
|
||||
if (eslintrcConfig.env[envName]) {
|
||||
debug(`Translating environment: ${envName}`);
|
||||
|
||||
if (environments.has(envName)) {
|
||||
|
||||
// built-in environments should be defined first
|
||||
configs.unshift(...translateESLintRC({
|
||||
criteria: eslintrcConfig.criteria,
|
||||
...environments.get(envName)
|
||||
}, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo
|
||||
}));
|
||||
} else if (pluginEnvironments.has(envName)) {
|
||||
|
||||
// if the environment comes from a plugin, it should come after the plugin config
|
||||
configs.push(...translateESLintRC({
|
||||
criteria: eslintrcConfig.criteria,
|
||||
...pluginEnvironments.get(envName)
|
||||
}, {
|
||||
resolveConfigRelativeTo,
|
||||
resolvePluginsRelativeTo
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// only add if there are actually keys in the config
|
||||
if (Object.keys(flatConfig).length > 0) {
|
||||
configs.push(flatConfig);
|
||||
}
|
||||
|
||||
return configs;
|
||||
}
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A compatibility class for working with configs.
|
||||
*/
|
||||
class FlatCompat {
|
||||
|
||||
constructor({
|
||||
baseDirectory = process.cwd(),
|
||||
resolvePluginsRelativeTo = baseDirectory,
|
||||
recommendedConfig,
|
||||
allConfig
|
||||
} = {}) {
|
||||
this.baseDirectory = baseDirectory;
|
||||
this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
|
||||
this[cafactory] = new ConfigArrayFactory({
|
||||
cwd: baseDirectory,
|
||||
resolvePluginsRelativeTo,
|
||||
getEslintAllConfig: () => {
|
||||
|
||||
if (!allConfig) {
|
||||
throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
|
||||
}
|
||||
|
||||
return allConfig;
|
||||
},
|
||||
getEslintRecommendedConfig: () => {
|
||||
|
||||
if (!recommendedConfig) {
|
||||
throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
|
||||
}
|
||||
|
||||
return recommendedConfig;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates an ESLintRC-style config into a flag-config-style config.
|
||||
* @param {Object} eslintrcConfig The ESLintRC-style config object.
|
||||
* @returns {Object} A flag-config-style config object.
|
||||
*/
|
||||
config(eslintrcConfig) {
|
||||
const eslintrcArray = this[cafactory].create(eslintrcConfig, {
|
||||
basePath: this.baseDirectory
|
||||
});
|
||||
|
||||
const flatArray = [];
|
||||
let hasIgnorePatterns = false;
|
||||
|
||||
eslintrcArray.forEach(configData => {
|
||||
if (configData.type === "config") {
|
||||
hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
|
||||
flatArray.push(...translateESLintRC(configData, {
|
||||
resolveConfigRelativeTo: path.join(this.baseDirectory, "__placeholder.js"),
|
||||
resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, "__placeholder.js"),
|
||||
pluginEnvironments: eslintrcArray.pluginEnvironments,
|
||||
pluginProcessors: eslintrcArray.pluginProcessors
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
// combine ignorePatterns to emulate ESLintRC behavior better
|
||||
if (hasIgnorePatterns) {
|
||||
flatArray.unshift({
|
||||
ignores: [filePath => {
|
||||
|
||||
// Compute the final config for this file.
|
||||
// This filters config array elements by `files`/`excludedFiles` then merges the elements.
|
||||
const finalConfig = eslintrcArray.extractConfig(filePath);
|
||||
|
||||
// Test the `ignorePattern` properties of the final config.
|
||||
return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
|
||||
}]
|
||||
});
|
||||
}
|
||||
|
||||
return flatArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `env` section of an ESLintRC-style config.
|
||||
* @param {Object} envConfig The `env` section of an ESLintRC config.
|
||||
* @returns {Object[]} An array of flag-config objects representing the environments.
|
||||
*/
|
||||
env(envConfig) {
|
||||
return this.config({
|
||||
env: envConfig
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `extends` section of an ESLintRC-style config.
|
||||
* @param {...string} configsToExtend The names of the configs to load.
|
||||
* @returns {Object[]} An array of flag-config objects representing the config.
|
||||
*/
|
||||
extends(...configsToExtend) {
|
||||
return this.config({
|
||||
extends: configsToExtend
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the `plugins` section of an ESLintRC-style config.
|
||||
* @param {...string} plugins The names of the plugins to load.
|
||||
* @returns {Object[]} An array of flag-config objects representing the plugins.
|
||||
*/
|
||||
plugins(...plugins) {
|
||||
return this.config({
|
||||
plugins
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { FlatCompat };
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* @fileoverview Package exports for @eslint/eslintrc
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import * as ConfigOps from "./shared/config-ops.js";
|
||||
import ConfigValidator from "./shared/config-validator.js";
|
||||
import * as naming from "./shared/naming.js";
|
||||
import environments from "../conf/environments.js";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const Legacy = {
|
||||
environments,
|
||||
|
||||
// shared
|
||||
ConfigOps,
|
||||
ConfigValidator,
|
||||
naming
|
||||
};
|
||||
|
||||
export {
|
||||
Legacy
|
||||
};
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @fileoverview Package exports for @eslint/eslintrc
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import {
|
||||
ConfigArrayFactory,
|
||||
createContext as createConfigArrayFactoryContext
|
||||
} from "./config-array-factory.js";
|
||||
|
||||
import { CascadingConfigArrayFactory } from "./cascading-config-array-factory.js";
|
||||
import * as ModuleResolver from "./shared/relative-module-resolver.js";
|
||||
import { ConfigArray, getUsedExtractedConfigs } from "./config-array/index.js";
|
||||
import { ConfigDependency } from "./config-array/config-dependency.js";
|
||||
import { ExtractedConfig } from "./config-array/extracted-config.js";
|
||||
import { IgnorePattern } from "./config-array/ignore-pattern.js";
|
||||
import { OverrideTester } from "./config-array/override-tester.js";
|
||||
import * as ConfigOps from "./shared/config-ops.js";
|
||||
import ConfigValidator from "./shared/config-validator.js";
|
||||
import * as naming from "./shared/naming.js";
|
||||
import { FlatCompat } from "./flat-compat.js";
|
||||
import environments from "../conf/environments.js";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const Legacy = {
|
||||
ConfigArray,
|
||||
createConfigArrayFactoryContext,
|
||||
CascadingConfigArrayFactory,
|
||||
ConfigArrayFactory,
|
||||
ConfigDependency,
|
||||
ExtractedConfig,
|
||||
IgnorePattern,
|
||||
OverrideTester,
|
||||
getUsedExtractedConfigs,
|
||||
environments,
|
||||
|
||||
// shared
|
||||
ConfigOps,
|
||||
ConfigValidator,
|
||||
ModuleResolver,
|
||||
naming
|
||||
};
|
||||
|
||||
export {
|
||||
|
||||
Legacy,
|
||||
|
||||
FlatCompat
|
||||
|
||||
};
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* @fileoverview The instance of Ajv validator.
|
||||
* @author Evgeny Poberezkin
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import Ajv from "ajv";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*
|
||||
* Copied from ajv/lib/refs/json-schema-draft-04.json
|
||||
* The MIT License (MIT)
|
||||
* Copyright (c) 2015-2017 Evgeny Poberezkin
|
||||
*/
|
||||
const metaSchema = {
|
||||
id: "http://json-schema.org/draft-04/schema#",
|
||||
$schema: "http://json-schema.org/draft-04/schema#",
|
||||
description: "Core schema meta-schema",
|
||||
definitions: {
|
||||
schemaArray: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
items: { $ref: "#" }
|
||||
},
|
||||
positiveInteger: {
|
||||
type: "integer",
|
||||
minimum: 0
|
||||
},
|
||||
positiveIntegerDefault0: {
|
||||
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
|
||||
},
|
||||
simpleTypes: {
|
||||
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
|
||||
},
|
||||
stringArray: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
},
|
||||
type: "object",
|
||||
properties: {
|
||||
id: {
|
||||
type: "string"
|
||||
},
|
||||
$schema: {
|
||||
type: "string"
|
||||
},
|
||||
title: {
|
||||
type: "string"
|
||||
},
|
||||
description: {
|
||||
type: "string"
|
||||
},
|
||||
default: { },
|
||||
multipleOf: {
|
||||
type: "number",
|
||||
minimum: 0,
|
||||
exclusiveMinimum: true
|
||||
},
|
||||
maximum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMaximum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
minimum: {
|
||||
type: "number"
|
||||
},
|
||||
exclusiveMinimum: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxLength: { $ref: "#/definitions/positiveInteger" },
|
||||
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
pattern: {
|
||||
type: "string",
|
||||
format: "regex"
|
||||
},
|
||||
additionalItems: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
items: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/schemaArray" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
maxItems: { $ref: "#/definitions/positiveInteger" },
|
||||
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
uniqueItems: {
|
||||
type: "boolean",
|
||||
default: false
|
||||
},
|
||||
maxProperties: { $ref: "#/definitions/positiveInteger" },
|
||||
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
|
||||
required: { $ref: "#/definitions/stringArray" },
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ type: "boolean" },
|
||||
{ $ref: "#" }
|
||||
],
|
||||
default: { }
|
||||
},
|
||||
definitions: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
properties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
patternProperties: {
|
||||
type: "object",
|
||||
additionalProperties: { $ref: "#" },
|
||||
default: { }
|
||||
},
|
||||
dependencies: {
|
||||
type: "object",
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ $ref: "#" },
|
||||
{ $ref: "#/definitions/stringArray" }
|
||||
]
|
||||
}
|
||||
},
|
||||
enum: {
|
||||
type: "array",
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
},
|
||||
type: {
|
||||
anyOf: [
|
||||
{ $ref: "#/definitions/simpleTypes" },
|
||||
{
|
||||
type: "array",
|
||||
items: { $ref: "#/definitions/simpleTypes" },
|
||||
minItems: 1,
|
||||
uniqueItems: true
|
||||
}
|
||||
]
|
||||
},
|
||||
format: { type: "string" },
|
||||
allOf: { $ref: "#/definitions/schemaArray" },
|
||||
anyOf: { $ref: "#/definitions/schemaArray" },
|
||||
oneOf: { $ref: "#/definitions/schemaArray" },
|
||||
not: { $ref: "#" }
|
||||
},
|
||||
dependencies: {
|
||||
exclusiveMaximum: ["maximum"],
|
||||
exclusiveMinimum: ["minimum"]
|
||||
},
|
||||
default: { }
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export default (additionalOptions = {}) => {
|
||||
const ajv = new Ajv({
|
||||
meta: false,
|
||||
useDefaults: true,
|
||||
validateSchema: false,
|
||||
missingRefs: "ignore",
|
||||
verbose: true,
|
||||
schemaId: "auto",
|
||||
...additionalOptions
|
||||
});
|
||||
|
||||
ajv.addMetaSchema(metaSchema);
|
||||
// eslint-disable-next-line no-underscore-dangle
|
||||
ajv._opts.defaultMeta = metaSchema.id;
|
||||
|
||||
return ajv;
|
||||
};
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* @fileoverview Config file operations. This file must be usable in the browser,
|
||||
* so no Node-specific code can be here.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
|
||||
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
|
||||
map[value] = index;
|
||||
return map;
|
||||
}, {}),
|
||||
VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Normalizes the severity value of a rule's configuration to a number
|
||||
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
|
||||
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
|
||||
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
|
||||
* whose first element is one of the above values. Strings are matched case-insensitively.
|
||||
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
|
||||
*/
|
||||
function getRuleSeverity(ruleConfig) {
|
||||
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
|
||||
return severityValue;
|
||||
}
|
||||
|
||||
if (typeof severityValue === "string") {
|
||||
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts old-style severity settings (0, 1, 2) into new-style
|
||||
* severity settings (off, warn, error) for all rules. Assumption is that severity
|
||||
* values have already been validated as correct.
|
||||
* @param {Object} config The config object to normalize.
|
||||
* @returns {void}
|
||||
*/
|
||||
function normalizeToStrings(config) {
|
||||
|
||||
if (config.rules) {
|
||||
Object.keys(config.rules).forEach(ruleId => {
|
||||
const ruleConfig = config.rules[ruleId];
|
||||
|
||||
if (typeof ruleConfig === "number") {
|
||||
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
|
||||
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
|
||||
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the severity for the given rule configuration represents an error.
|
||||
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} True if the rule represents an error, false if not.
|
||||
*/
|
||||
function isErrorSeverity(ruleConfig) {
|
||||
return getRuleSeverity(ruleConfig) === 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given config has valid severity or not.
|
||||
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isValidSeverity(ruleConfig) {
|
||||
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
|
||||
|
||||
if (typeof severity === "string") {
|
||||
severity = severity.toLowerCase();
|
||||
}
|
||||
return VALID_SEVERITIES.indexOf(severity) !== -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether every rule of a given config has valid severity or not.
|
||||
* @param {Object} config The configuration for rules.
|
||||
* @returns {boolean} `true` if the configuration has valid severity.
|
||||
*/
|
||||
function isEverySeverityValid(config) {
|
||||
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a value for a global in a config
|
||||
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
|
||||
* a global directive comment
|
||||
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
|
||||
* @throws Error if global value is invalid
|
||||
*/
|
||||
function normalizeConfigGlobal(configuredValue) {
|
||||
switch (configuredValue) {
|
||||
case "off":
|
||||
return "off";
|
||||
|
||||
case true:
|
||||
case "true":
|
||||
case "writeable":
|
||||
case "writable":
|
||||
return "writable";
|
||||
|
||||
case null:
|
||||
case false:
|
||||
case "false":
|
||||
case "readable":
|
||||
case "readonly":
|
||||
return "readonly";
|
||||
|
||||
default:
|
||||
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
getRuleSeverity,
|
||||
normalizeToStrings,
|
||||
isErrorSeverity,
|
||||
isValidSeverity,
|
||||
isEverySeverityValid,
|
||||
normalizeConfigGlobal
|
||||
};
|
||||
Generated
Vendored
+325
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* @fileoverview Validates configs.
|
||||
* @author Brandon Mills
|
||||
*/
|
||||
|
||||
/* eslint class-methods-use-this: "off" */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import util from "util";
|
||||
import * as ConfigOps from "./config-ops.js";
|
||||
import { emitDeprecationWarning } from "./deprecation-warnings.js";
|
||||
import ajvOrig from "./ajv.js";
|
||||
import configSchema from "../../conf/config-schema.js";
|
||||
import BuiltInEnvironments from "../../conf/environments.js";
|
||||
|
||||
const ajv = ajvOrig();
|
||||
|
||||
const ruleValidators = new WeakMap();
|
||||
const noop = Function.prototype;
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
let validateSchema;
|
||||
const severityMap = {
|
||||
error: 2,
|
||||
warn: 1,
|
||||
off: 0
|
||||
};
|
||||
|
||||
const validated = new WeakSet();
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
export default class ConfigValidator {
|
||||
constructor({ builtInRules = new Map() } = {}) {
|
||||
this.builtInRules = builtInRules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a complete options schema for a rule.
|
||||
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
|
||||
* @returns {Object} JSON Schema for the rule's options.
|
||||
*/
|
||||
getRuleOptionsSchema(rule) {
|
||||
if (!rule) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const schema = rule.schema || rule.meta && rule.meta.schema;
|
||||
|
||||
// Given a tuple of schemas, insert warning level at the beginning
|
||||
if (Array.isArray(schema)) {
|
||||
if (schema.length) {
|
||||
return {
|
||||
type: "array",
|
||||
items: schema,
|
||||
minItems: 0,
|
||||
maxItems: schema.length
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "array",
|
||||
minItems: 0,
|
||||
maxItems: 0
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// Given a full schema, leave it alone
|
||||
return schema || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
|
||||
* @param {options} options The given options for the rule.
|
||||
* @returns {number|string} The rule's severity value
|
||||
*/
|
||||
validateRuleSeverity(options) {
|
||||
const severity = Array.isArray(options) ? options[0] : options;
|
||||
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
|
||||
|
||||
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
|
||||
return normSeverity;
|
||||
}
|
||||
|
||||
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the non-severity options passed to a rule, based on its schema.
|
||||
* @param {{create: Function}} rule The rule to validate
|
||||
* @param {Array} localOptions The options for the rule, excluding severity
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleSchema(rule, localOptions) {
|
||||
if (!ruleValidators.has(rule)) {
|
||||
const schema = this.getRuleOptionsSchema(rule);
|
||||
|
||||
if (schema) {
|
||||
ruleValidators.set(rule, ajv.compile(schema));
|
||||
}
|
||||
}
|
||||
|
||||
const validateRule = ruleValidators.get(rule);
|
||||
|
||||
if (validateRule) {
|
||||
validateRule(localOptions);
|
||||
if (validateRule.errors) {
|
||||
throw new Error(validateRule.errors.map(
|
||||
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
|
||||
).join(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rule's options against its schema.
|
||||
* @param {{create: Function}|null} rule The rule that the config is being validated for
|
||||
* @param {string} ruleId The rule's unique name.
|
||||
* @param {Array|number} options The given options for the rule.
|
||||
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
|
||||
* no source is prepended to the message.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRuleOptions(rule, ruleId, options, source = null) {
|
||||
try {
|
||||
const severity = this.validateRuleSeverity(options);
|
||||
|
||||
if (severity !== 0) {
|
||||
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
|
||||
}
|
||||
} catch (err) {
|
||||
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
|
||||
|
||||
if (typeof source === "string") {
|
||||
throw new Error(`${source}:\n\t${enhancedMessage}`);
|
||||
} else {
|
||||
throw new Error(enhancedMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an environment object
|
||||
* @param {Object} environment The environment config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateEnvironment(
|
||||
environment,
|
||||
source,
|
||||
getAdditionalEnv = noop
|
||||
) {
|
||||
|
||||
// not having an environment is ok
|
||||
if (!environment) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(environment).forEach(id => {
|
||||
const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
|
||||
|
||||
if (!env) {
|
||||
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
|
||||
|
||||
throw new Error(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a rules config object
|
||||
* @param {Object} rulesConfig The rules config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
|
||||
* @returns {void}
|
||||
*/
|
||||
validateRules(
|
||||
rulesConfig,
|
||||
source,
|
||||
getAdditionalRule = noop
|
||||
) {
|
||||
if (!rulesConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.keys(rulesConfig).forEach(id => {
|
||||
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
|
||||
|
||||
this.validateRuleOptions(rule, id, rulesConfig[id], source);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a `globals` section of a config file
|
||||
* @param {Object} globalsConfig The `globals` section
|
||||
* @param {string|null} source The name of the configuration source to report in the event of an error.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateGlobals(globalsConfig, source = null) {
|
||||
if (!globalsConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object.entries(globalsConfig)
|
||||
.forEach(([configuredGlobal, configuredValue]) => {
|
||||
try {
|
||||
ConfigOps.normalizeConfigGlobal(configuredValue);
|
||||
} catch (err) {
|
||||
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate `processor` configuration.
|
||||
* @param {string|undefined} processorName The processor name.
|
||||
* @param {string} source The name of config file.
|
||||
* @param {function(id:string): Processor} getProcessor The getter of defined processors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateProcessor(processorName, source, getProcessor) {
|
||||
if (processorName && !getProcessor(processorName)) {
|
||||
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats an array of schema validation errors.
|
||||
* @param {Array} errors An array of error messages to format.
|
||||
* @returns {string} Formatted error message
|
||||
*/
|
||||
formatErrors(errors) {
|
||||
return errors.map(error => {
|
||||
if (error.keyword === "additionalProperties") {
|
||||
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
|
||||
|
||||
return `Unexpected top-level property "${formattedPropertyPath}"`;
|
||||
}
|
||||
if (error.keyword === "type") {
|
||||
const formattedField = error.dataPath.slice(1);
|
||||
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
|
||||
const formattedValue = JSON.stringify(error.data);
|
||||
|
||||
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
|
||||
}
|
||||
|
||||
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
|
||||
|
||||
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
|
||||
}).map(message => `\t- ${message}.\n`).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the top level properties of the config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigSchema(config, source = null) {
|
||||
validateSchema = validateSchema || ajv.compile(configSchema);
|
||||
|
||||
if (!validateSchema(config)) {
|
||||
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
|
||||
}
|
||||
|
||||
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
|
||||
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an entire config object.
|
||||
* @param {Object} config The config object to validate.
|
||||
* @param {string} source The name of the configuration source to report in any errors.
|
||||
* @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
|
||||
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
|
||||
* @returns {void}
|
||||
*/
|
||||
validate(config, source, getAdditionalRule, getAdditionalEnv) {
|
||||
this.validateConfigSchema(config, source);
|
||||
this.validateRules(config.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(config.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
|
||||
for (const override of config.overrides || []) {
|
||||
this.validateRules(override.rules, source, getAdditionalRule);
|
||||
this.validateEnvironment(override.env, source, getAdditionalEnv);
|
||||
this.validateGlobals(config.globals, source);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate config array object.
|
||||
* @param {ConfigArray} configArray The config array to validate.
|
||||
* @returns {void}
|
||||
*/
|
||||
validateConfigArray(configArray) {
|
||||
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
|
||||
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
|
||||
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
|
||||
|
||||
// Validate.
|
||||
for (const element of configArray) {
|
||||
if (validated.has(element)) {
|
||||
continue;
|
||||
}
|
||||
validated.add(element);
|
||||
|
||||
this.validateEnvironment(element.env, element.name, getPluginEnv);
|
||||
this.validateGlobals(element.globals, element.name);
|
||||
this.validateProcessor(element.processor, element.name, getPluginProcessor);
|
||||
this.validateRules(element.rules, element.name, getPluginRule);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Generated
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @fileoverview Provide the function that emits deprecation warnings.
|
||||
* @author Toru Nagashima <http://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
import path from "path";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Private
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
// Defitions for deprecation warnings.
|
||||
const deprecationWarningMessages = {
|
||||
ESLINT_LEGACY_ECMAFEATURES:
|
||||
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
|
||||
ESLINT_PERSONAL_CONFIG_LOAD:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please use a config file per project or the '--config' option.",
|
||||
ESLINT_PERSONAL_CONFIG_SUPPRESS:
|
||||
"'~/.eslintrc.*' config files have been deprecated. " +
|
||||
"Please remove it or add 'root:true' to the config files in your " +
|
||||
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
|
||||
};
|
||||
|
||||
const sourceFileErrorCache = new Set();
|
||||
|
||||
/**
|
||||
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
|
||||
* for each unique file path, but repeated invocations with the same file path have no effect.
|
||||
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
|
||||
* @param {string} source The name of the configuration source to report the warning for.
|
||||
* @param {string} errorCode The warning message to show.
|
||||
* @returns {void}
|
||||
*/
|
||||
function emitDeprecationWarning(source, errorCode) {
|
||||
const cacheKey = JSON.stringify({ source, errorCode });
|
||||
|
||||
if (sourceFileErrorCache.has(cacheKey)) {
|
||||
return;
|
||||
}
|
||||
sourceFileErrorCache.add(cacheKey);
|
||||
|
||||
const rel = path.relative(process.cwd(), source);
|
||||
const message = deprecationWarningMessages[errorCode];
|
||||
|
||||
process.emitWarning(
|
||||
`${message} (found in "${rel}")`,
|
||||
"DeprecationWarning",
|
||||
errorCode
|
||||
);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export {
|
||||
emitDeprecationWarning
|
||||
};
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @fileoverview Common helpers for naming of plugins, formatters and configs
|
||||
*/
|
||||
|
||||
const NAMESPACE_REGEX = /^@.*\//iu;
|
||||
|
||||
/**
|
||||
* Brings package name to correct format based on prefix
|
||||
* @param {string} name The name of the package.
|
||||
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
|
||||
* @returns {string} Normalized name of the package
|
||||
* @private
|
||||
*/
|
||||
function normalizePackageName(name, prefix) {
|
||||
let normalizedName = name;
|
||||
|
||||
/**
|
||||
* On Windows, name can come in with Windows slashes instead of Unix slashes.
|
||||
* Normalize to Unix first to avoid errors later on.
|
||||
* https://github.com/eslint/eslint/issues/5644
|
||||
*/
|
||||
if (normalizedName.includes("\\")) {
|
||||
normalizedName = normalizedName.replace(/\\/gu, "/");
|
||||
}
|
||||
|
||||
if (normalizedName.charAt(0) === "@") {
|
||||
|
||||
/**
|
||||
* it's a scoped package
|
||||
* package name is the prefix, or just a username
|
||||
*/
|
||||
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
|
||||
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
|
||||
|
||||
if (scopedPackageShortcutRegex.test(normalizedName)) {
|
||||
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
|
||||
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
|
||||
|
||||
/**
|
||||
* for scoped packages, insert the prefix after the first / unless
|
||||
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
|
||||
*/
|
||||
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
|
||||
}
|
||||
} else if (!normalizedName.startsWith(`${prefix}-`)) {
|
||||
normalizedName = `${prefix}-${normalizedName}`;
|
||||
}
|
||||
|
||||
return normalizedName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the prefix from a fullname.
|
||||
* @param {string} fullname The term which may have the prefix.
|
||||
* @param {string} prefix The prefix to remove.
|
||||
* @returns {string} The term without prefix.
|
||||
*/
|
||||
function getShorthandName(fullname, prefix) {
|
||||
if (fullname[0] === "@") {
|
||||
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
|
||||
|
||||
if (matchResult) {
|
||||
return matchResult[1];
|
||||
}
|
||||
|
||||
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
|
||||
if (matchResult) {
|
||||
return `${matchResult[1]}/${matchResult[2]}`;
|
||||
}
|
||||
} else if (fullname.startsWith(`${prefix}-`)) {
|
||||
return fullname.slice(prefix.length + 1);
|
||||
}
|
||||
|
||||
return fullname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the scope (namespace) of a term.
|
||||
* @param {string} term The term which may have the namespace.
|
||||
* @returns {string} The namespace of the term if it has one.
|
||||
*/
|
||||
function getNamespaceFromTerm(term) {
|
||||
const match = term.match(NAMESPACE_REGEX);
|
||||
|
||||
return match ? match[0] : "";
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
export {
|
||||
normalizePackageName,
|
||||
getShorthandName,
|
||||
getNamespaceFromTerm
|
||||
};
|
||||
Generated
Vendored
+42
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Utility for resolving a module relative to another module
|
||||
* @author Teddy Katz
|
||||
*/
|
||||
|
||||
import Module from "module";
|
||||
|
||||
/*
|
||||
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
|
||||
* We only support the case where the argument is a filepath, not a URL.
|
||||
*/
|
||||
const createRequire = Module.createRequire;
|
||||
|
||||
/**
|
||||
* Resolves a Node module relative to another module
|
||||
* @param {string} moduleName The name of a Node module, or a path to a Node module.
|
||||
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
|
||||
* a file rather than a directory, but the file need not actually exist.
|
||||
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
|
||||
*/
|
||||
function resolve(moduleName, relativeToPath) {
|
||||
try {
|
||||
return createRequire(relativeToPath).resolve(moduleName);
|
||||
} catch (error) {
|
||||
|
||||
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
error.code === "MODULE_NOT_FOUND" &&
|
||||
!error.requireStack &&
|
||||
error.message.includes(moduleName)
|
||||
) {
|
||||
error.message += `\nRequire stack:\n- ${relativeToPath}`;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
resolve
|
||||
};
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* @fileoverview Define common types for input completion.
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
|
||||
/** @type {any} */
|
||||
export default {};
|
||||
|
||||
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
|
||||
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
|
||||
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
|
||||
|
||||
/**
|
||||
* @typedef {Object} EcmaFeatures
|
||||
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
|
||||
* @property {boolean} [jsx] Enabling JSX syntax.
|
||||
* @property {boolean} [impliedStrict] Enabling strict mode always.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ParserOptions
|
||||
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
|
||||
* @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number).
|
||||
* @property {"script"|"module"} [sourceType] The source code type.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ConfigData
|
||||
* @property {Record<string, boolean>} [env] The environment settings.
|
||||
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
|
||||
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
|
||||
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
|
||||
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
|
||||
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
|
||||
* @property {string} [parser] The path to a parser or the package name of a parser.
|
||||
* @property {ParserOptions} [parserOptions] The parser options.
|
||||
* @property {string[]} [plugins] The plugin specifiers.
|
||||
* @property {string} [processor] The processor specifier.
|
||||
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
|
||||
* @property {boolean} [root] The root flag.
|
||||
* @property {Record<string, RuleConf>} [rules] The rule settings.
|
||||
* @property {Object} [settings] The shared settings.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} OverrideConfigData
|
||||
* @property {Record<string, boolean>} [env] The environment settings.
|
||||
* @property {string | string[]} [excludedFiles] The glob pattarns for excluded files.
|
||||
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
|
||||
* @property {string | string[]} files The glob patterns for target files.
|
||||
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
|
||||
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
|
||||
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
|
||||
* @property {string} [parser] The path to a parser or the package name of a parser.
|
||||
* @property {ParserOptions} [parserOptions] The parser options.
|
||||
* @property {string[]} [plugins] The plugin specifiers.
|
||||
* @property {string} [processor] The processor specifier.
|
||||
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
|
||||
* @property {Record<string, RuleConf>} [rules] The rule settings.
|
||||
* @property {Object} [settings] The shared settings.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} ParseResult
|
||||
* @property {Object} ast The AST.
|
||||
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
|
||||
* @property {Record<string, any>} [services] The services that the parser provides.
|
||||
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Parser
|
||||
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
|
||||
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Environment
|
||||
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
|
||||
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} LintMessage
|
||||
* @property {number} column The 1-based column number.
|
||||
* @property {number} [endColumn] The 1-based column number of the end location.
|
||||
* @property {number} [endLine] The 1-based line number of the end location.
|
||||
* @property {boolean} fatal If `true` then this is a fatal error.
|
||||
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
|
||||
* @property {number} line The 1-based line number.
|
||||
* @property {string} message The error message.
|
||||
* @property {string|null} ruleId The ID of the rule which makes this message.
|
||||
* @property {0|1|2} severity The severity of this message.
|
||||
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} SuggestionResult
|
||||
* @property {string} desc A short description.
|
||||
* @property {string} [messageId] Id referencing a message for the description.
|
||||
* @property {{ text: string, range: number[] }} fix fix result info
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Processor
|
||||
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
|
||||
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
|
||||
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} RuleMetaDocs
|
||||
* @property {string} category The category of the rule.
|
||||
* @property {string} description The description of the rule.
|
||||
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
|
||||
* @property {string} url The URL of the rule documentation.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} RuleMeta
|
||||
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
|
||||
* @property {RuleMetaDocs} docs The document information of the rule.
|
||||
* @property {"code"|"whitespace"} [fixable] The autofix type.
|
||||
* @property {Record<string,string>} [messages] The messages the rule reports.
|
||||
* @property {string[]} [replacedBy] The IDs of the alternative rules.
|
||||
* @property {Array|Object} schema The option schema of the rule.
|
||||
* @property {"problem"|"suggestion"|"layout"} type The rule type.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Rule
|
||||
* @property {Function} create The factory of the rule.
|
||||
* @property {RuleMeta} meta The meta data of the rule.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} Plugin
|
||||
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
|
||||
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
|
||||
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
|
||||
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Information of deprecated rules.
|
||||
* @typedef {Object} DeprecatedRuleInfo
|
||||
* @property {string} ruleId The rule ID.
|
||||
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
|
||||
*/
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"name": "@eslint/eslintrc",
|
||||
"version": "2.1.4",
|
||||
"description": "The legacy ESLintRC config file format for ESLint",
|
||||
"type": "module",
|
||||
"main": "./dist/eslintrc.cjs",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./lib/index.js",
|
||||
"require": "./dist/eslintrc.cjs"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./universal": {
|
||||
"import": "./lib/index-universal.js",
|
||||
"require": "./dist/eslintrc-universal.cjs"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"conf",
|
||||
"LICENSE",
|
||||
"dist",
|
||||
"universal.js"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"lint": "eslint . --report-unused-disable-directives",
|
||||
"lint:fix": "npm run lint -- --fix",
|
||||
"prepare": "npm run build",
|
||||
"release:generate:latest": "eslint-generate-release",
|
||||
"release:generate:alpha": "eslint-generate-prerelease alpha",
|
||||
"release:generate:beta": "eslint-generate-prerelease beta",
|
||||
"release:generate:rc": "eslint-generate-prerelease rc",
|
||||
"release:publish": "eslint-publish-release",
|
||||
"test": "mocha -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'"
|
||||
},
|
||||
"repository": "eslint/eslintrc",
|
||||
"funding": "https://opencollective.com/eslint",
|
||||
"keywords": [
|
||||
"ESLint",
|
||||
"ESLintRC",
|
||||
"Configuration"
|
||||
],
|
||||
"author": "Nicholas C. Zakas",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/eslintrc/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/eslintrc#readme",
|
||||
"devDependencies": {
|
||||
"c8": "^7.7.3",
|
||||
"chai": "^4.3.4",
|
||||
"eslint": "^7.31.0",
|
||||
"eslint-config-eslint": "^7.0.0",
|
||||
"eslint-plugin-jsdoc": "^35.4.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-release": "^3.2.0",
|
||||
"fs-teardown": "^0.1.3",
|
||||
"mocha": "^9.0.3",
|
||||
"rollup": "^2.70.1",
|
||||
"shelljs": "^0.8.4",
|
||||
"sinon": "^11.1.2",
|
||||
"temp-dir": "^2.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "^6.12.4",
|
||||
"debug": "^4.3.2",
|
||||
"espree": "^9.6.0",
|
||||
"globals": "^13.19.0",
|
||||
"ignore": "^5.2.0",
|
||||
"import-fresh": "^3.2.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"minimatch": "^3.1.2",
|
||||
"strip-json-comments": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// Jest (and probably some other runtimes with custom implementations of
|
||||
// `require`) doesn't support `exports` in `package.json`, so this file is here
|
||||
// to help them load this module. Note that it is also `.js` and not `.cjs` for
|
||||
// the same reason - `cjs` files requires to be loaded with an extension, but
|
||||
// since Jest doesn't respect `module` outside of ESM mode it still works in
|
||||
// this case (and the `require` in _this_ file does specify the extension).
|
||||
|
||||
// eslint-disable-next-line no-undef
|
||||
module.exports = require("./dist/eslintrc-universal.cjs");
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
[](https://www.npmjs.com/package/@eslint/js)
|
||||
|
||||
# ESLint JavaScript Plugin
|
||||
|
||||
[Website](https://eslint.org) | [Configure ESLint](https://eslint.org/docs/latest/use/configure) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/latest/contribute) | [Twitter](https://twitter.com/geteslint) | [Chatroom](https://eslint.org/chat)
|
||||
|
||||
The beginnings of separating out JavaScript-specific functionality from ESLint.
|
||||
|
||||
Right now, this plugin contains two configurations:
|
||||
|
||||
* `recommended` - enables the rules recommended by the ESLint team (the replacement for `"eslint:recommended"`)
|
||||
* `all` - enables all ESLint rules (the replacement for `"eslint:all"`)
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
npm install @eslint/js -D
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Use in your `eslint.config.js` file anytime you want to extend one of the configs:
|
||||
|
||||
```js
|
||||
import js from "@eslint/js";
|
||||
|
||||
export default [
|
||||
|
||||
// apply recommended rules to JS files
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
rules: js.configs.recommended.rules
|
||||
},
|
||||
|
||||
// apply recommended rules to JS files with an override
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
rules: {
|
||||
...js.configs.recommended.rules,
|
||||
"no-unused-vars": "warn"
|
||||
}
|
||||
},
|
||||
|
||||
// apply all rules to JS files
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
rules: {
|
||||
...js.configs.all.rules,
|
||||
"no-unused-vars": "warn"
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@eslint/js",
|
||||
"version": "8.57.1",
|
||||
"description": "ESLint JavaScript language implementation",
|
||||
"main": "./src/index.js",
|
||||
"scripts": {},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"README.md",
|
||||
"src"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint/eslint.git",
|
||||
"directory": "packages/js"
|
||||
},
|
||||
"homepage": "https://eslint.org",
|
||||
"bugs": "https://github.com/eslint/eslint/issues/",
|
||||
"keywords": [
|
||||
"javascript",
|
||||
"eslint-plugin",
|
||||
"eslint"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* WARNING: This file is autogenerated using the tools/update-eslint-all.js
|
||||
* script. Do not edit manually.
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
/* eslint quote-props: off -- autogenerated so don't lint */
|
||||
|
||||
module.exports = Object.freeze({
|
||||
"rules": {
|
||||
"accessor-pairs": "error",
|
||||
"array-callback-return": "error",
|
||||
"arrow-body-style": "error",
|
||||
"block-scoped-var": "error",
|
||||
"camelcase": "error",
|
||||
"capitalized-comments": "error",
|
||||
"class-methods-use-this": "error",
|
||||
"complexity": "error",
|
||||
"consistent-return": "error",
|
||||
"consistent-this": "error",
|
||||
"constructor-super": "error",
|
||||
"curly": "error",
|
||||
"default-case": "error",
|
||||
"default-case-last": "error",
|
||||
"default-param-last": "error",
|
||||
"dot-notation": "error",
|
||||
"eqeqeq": "error",
|
||||
"for-direction": "error",
|
||||
"func-name-matching": "error",
|
||||
"func-names": "error",
|
||||
"func-style": "error",
|
||||
"getter-return": "error",
|
||||
"grouped-accessor-pairs": "error",
|
||||
"guard-for-in": "error",
|
||||
"id-denylist": "error",
|
||||
"id-length": "error",
|
||||
"id-match": "error",
|
||||
"init-declarations": "error",
|
||||
"line-comment-position": "error",
|
||||
"logical-assignment-operators": "error",
|
||||
"max-classes-per-file": "error",
|
||||
"max-depth": "error",
|
||||
"max-lines": "error",
|
||||
"max-lines-per-function": "error",
|
||||
"max-nested-callbacks": "error",
|
||||
"max-params": "error",
|
||||
"max-statements": "error",
|
||||
"multiline-comment-style": "error",
|
||||
"new-cap": "error",
|
||||
"no-alert": "error",
|
||||
"no-array-constructor": "error",
|
||||
"no-async-promise-executor": "error",
|
||||
"no-await-in-loop": "error",
|
||||
"no-bitwise": "error",
|
||||
"no-caller": "error",
|
||||
"no-case-declarations": "error",
|
||||
"no-class-assign": "error",
|
||||
"no-compare-neg-zero": "error",
|
||||
"no-cond-assign": "error",
|
||||
"no-console": "error",
|
||||
"no-const-assign": "error",
|
||||
"no-constant-binary-expression": "error",
|
||||
"no-constant-condition": "error",
|
||||
"no-constructor-return": "error",
|
||||
"no-continue": "error",
|
||||
"no-control-regex": "error",
|
||||
"no-debugger": "error",
|
||||
"no-delete-var": "error",
|
||||
"no-div-regex": "error",
|
||||
"no-dupe-args": "error",
|
||||
"no-dupe-class-members": "error",
|
||||
"no-dupe-else-if": "error",
|
||||
"no-dupe-keys": "error",
|
||||
"no-duplicate-case": "error",
|
||||
"no-duplicate-imports": "error",
|
||||
"no-else-return": "error",
|
||||
"no-empty": "error",
|
||||
"no-empty-character-class": "error",
|
||||
"no-empty-function": "error",
|
||||
"no-empty-pattern": "error",
|
||||
"no-empty-static-block": "error",
|
||||
"no-eq-null": "error",
|
||||
"no-eval": "error",
|
||||
"no-ex-assign": "error",
|
||||
"no-extend-native": "error",
|
||||
"no-extra-bind": "error",
|
||||
"no-extra-boolean-cast": "error",
|
||||
"no-extra-label": "error",
|
||||
"no-fallthrough": "error",
|
||||
"no-func-assign": "error",
|
||||
"no-global-assign": "error",
|
||||
"no-implicit-coercion": "error",
|
||||
"no-implicit-globals": "error",
|
||||
"no-implied-eval": "error",
|
||||
"no-import-assign": "error",
|
||||
"no-inline-comments": "error",
|
||||
"no-inner-declarations": "error",
|
||||
"no-invalid-regexp": "error",
|
||||
"no-invalid-this": "error",
|
||||
"no-irregular-whitespace": "error",
|
||||
"no-iterator": "error",
|
||||
"no-label-var": "error",
|
||||
"no-labels": "error",
|
||||
"no-lone-blocks": "error",
|
||||
"no-lonely-if": "error",
|
||||
"no-loop-func": "error",
|
||||
"no-loss-of-precision": "error",
|
||||
"no-magic-numbers": "error",
|
||||
"no-misleading-character-class": "error",
|
||||
"no-multi-assign": "error",
|
||||
"no-multi-str": "error",
|
||||
"no-negated-condition": "error",
|
||||
"no-nested-ternary": "error",
|
||||
"no-new": "error",
|
||||
"no-new-func": "error",
|
||||
"no-new-native-nonconstructor": "error",
|
||||
"no-new-symbol": "error",
|
||||
"no-new-wrappers": "error",
|
||||
"no-nonoctal-decimal-escape": "error",
|
||||
"no-obj-calls": "error",
|
||||
"no-object-constructor": "error",
|
||||
"no-octal": "error",
|
||||
"no-octal-escape": "error",
|
||||
"no-param-reassign": "error",
|
||||
"no-plusplus": "error",
|
||||
"no-promise-executor-return": "error",
|
||||
"no-proto": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
"no-redeclare": "error",
|
||||
"no-regex-spaces": "error",
|
||||
"no-restricted-exports": "error",
|
||||
"no-restricted-globals": "error",
|
||||
"no-restricted-imports": "error",
|
||||
"no-restricted-properties": "error",
|
||||
"no-restricted-syntax": "error",
|
||||
"no-return-assign": "error",
|
||||
"no-script-url": "error",
|
||||
"no-self-assign": "error",
|
||||
"no-self-compare": "error",
|
||||
"no-sequences": "error",
|
||||
"no-setter-return": "error",
|
||||
"no-shadow": "error",
|
||||
"no-shadow-restricted-names": "error",
|
||||
"no-sparse-arrays": "error",
|
||||
"no-template-curly-in-string": "error",
|
||||
"no-ternary": "error",
|
||||
"no-this-before-super": "error",
|
||||
"no-throw-literal": "error",
|
||||
"no-undef": "error",
|
||||
"no-undef-init": "error",
|
||||
"no-undefined": "error",
|
||||
"no-underscore-dangle": "error",
|
||||
"no-unexpected-multiline": "error",
|
||||
"no-unmodified-loop-condition": "error",
|
||||
"no-unneeded-ternary": "error",
|
||||
"no-unreachable": "error",
|
||||
"no-unreachable-loop": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unsafe-negation": "error",
|
||||
"no-unsafe-optional-chaining": "error",
|
||||
"no-unused-expressions": "error",
|
||||
"no-unused-labels": "error",
|
||||
"no-unused-private-class-members": "error",
|
||||
"no-unused-vars": "error",
|
||||
"no-use-before-define": "error",
|
||||
"no-useless-backreference": "error",
|
||||
"no-useless-call": "error",
|
||||
"no-useless-catch": "error",
|
||||
"no-useless-computed-key": "error",
|
||||
"no-useless-concat": "error",
|
||||
"no-useless-constructor": "error",
|
||||
"no-useless-escape": "error",
|
||||
"no-useless-rename": "error",
|
||||
"no-useless-return": "error",
|
||||
"no-var": "error",
|
||||
"no-void": "error",
|
||||
"no-warning-comments": "error",
|
||||
"no-with": "error",
|
||||
"object-shorthand": "error",
|
||||
"one-var": "error",
|
||||
"operator-assignment": "error",
|
||||
"prefer-arrow-callback": "error",
|
||||
"prefer-const": "error",
|
||||
"prefer-destructuring": "error",
|
||||
"prefer-exponentiation-operator": "error",
|
||||
"prefer-named-capture-group": "error",
|
||||
"prefer-numeric-literals": "error",
|
||||
"prefer-object-has-own": "error",
|
||||
"prefer-object-spread": "error",
|
||||
"prefer-promise-reject-errors": "error",
|
||||
"prefer-regex-literals": "error",
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error",
|
||||
"prefer-template": "error",
|
||||
"radix": "error",
|
||||
"require-atomic-updates": "error",
|
||||
"require-await": "error",
|
||||
"require-unicode-regexp": "error",
|
||||
"require-yield": "error",
|
||||
"sort-imports": "error",
|
||||
"sort-keys": "error",
|
||||
"sort-vars": "error",
|
||||
"strict": "error",
|
||||
"symbol-description": "error",
|
||||
"unicode-bom": "error",
|
||||
"use-isnan": "error",
|
||||
"valid-typeof": "error",
|
||||
"vars-on-top": "error",
|
||||
"yoda": "error"
|
||||
}
|
||||
});
|
||||
Generated
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* @fileoverview Configuration applied when a user configuration extends from
|
||||
* eslint:recommended.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
/* eslint sort-keys: ["error", "asc"] -- Long, so make more readable */
|
||||
|
||||
/** @type {import("../lib/shared/types").ConfigData} */
|
||||
module.exports = Object.freeze({
|
||||
rules: Object.freeze({
|
||||
"constructor-super": "error",
|
||||
"for-direction": "error",
|
||||
"getter-return": "error",
|
||||
"no-async-promise-executor": "error",
|
||||
"no-case-declarations": "error",
|
||||
"no-class-assign": "error",
|
||||
"no-compare-neg-zero": "error",
|
||||
"no-cond-assign": "error",
|
||||
"no-const-assign": "error",
|
||||
"no-constant-condition": "error",
|
||||
"no-control-regex": "error",
|
||||
"no-debugger": "error",
|
||||
"no-delete-var": "error",
|
||||
"no-dupe-args": "error",
|
||||
"no-dupe-class-members": "error",
|
||||
"no-dupe-else-if": "error",
|
||||
"no-dupe-keys": "error",
|
||||
"no-duplicate-case": "error",
|
||||
"no-empty": "error",
|
||||
"no-empty-character-class": "error",
|
||||
"no-empty-pattern": "error",
|
||||
"no-ex-assign": "error",
|
||||
"no-extra-boolean-cast": "error",
|
||||
"no-extra-semi": "error",
|
||||
"no-fallthrough": "error",
|
||||
"no-func-assign": "error",
|
||||
"no-global-assign": "error",
|
||||
"no-import-assign": "error",
|
||||
"no-inner-declarations": "error",
|
||||
"no-invalid-regexp": "error",
|
||||
"no-irregular-whitespace": "error",
|
||||
"no-loss-of-precision": "error",
|
||||
"no-misleading-character-class": "error",
|
||||
"no-mixed-spaces-and-tabs": "error",
|
||||
"no-new-symbol": "error",
|
||||
"no-nonoctal-decimal-escape": "error",
|
||||
"no-obj-calls": "error",
|
||||
"no-octal": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
"no-redeclare": "error",
|
||||
"no-regex-spaces": "error",
|
||||
"no-self-assign": "error",
|
||||
"no-setter-return": "error",
|
||||
"no-shadow-restricted-names": "error",
|
||||
"no-sparse-arrays": "error",
|
||||
"no-this-before-super": "error",
|
||||
"no-undef": "error",
|
||||
"no-unexpected-multiline": "error",
|
||||
"no-unreachable": "error",
|
||||
"no-unsafe-finally": "error",
|
||||
"no-unsafe-negation": "error",
|
||||
"no-unsafe-optional-chaining": "error",
|
||||
"no-unused-labels": "error",
|
||||
"no-unused-vars": "error",
|
||||
"no-useless-backreference": "error",
|
||||
"no-useless-catch": "error",
|
||||
"no-useless-escape": "error",
|
||||
"no-with": "error",
|
||||
"require-yield": "error",
|
||||
"use-isnan": "error",
|
||||
"valid-typeof": "error"
|
||||
})
|
||||
});
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* @fileoverview Main package entrypoint.
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
configs: {
|
||||
all: require("./configs/eslint-all"),
|
||||
recommended: require("./configs/eslint-recommended")
|
||||
}
|
||||
};
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
# Config Array
|
||||
|
||||
by [Nicholas C. Zakas](https://humanwhocodes.com)
|
||||
|
||||
If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
|
||||
|
||||
## Description
|
||||
|
||||
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
|
||||
|
||||
## Background
|
||||
|
||||
In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born.
|
||||
|
||||
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
|
||||
|
||||
## Installation
|
||||
|
||||
You can install the package using npm or Yarn:
|
||||
|
||||
```bash
|
||||
npm install @humanwhocodes/config-array --save
|
||||
|
||||
# or
|
||||
|
||||
yarn add @humanwhocodes/config-array
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
First, import the `ConfigArray` constructor:
|
||||
|
||||
```js
|
||||
import { ConfigArray } from "@humanwhocodes/config-array";
|
||||
|
||||
// or using CommonJS
|
||||
|
||||
const { ConfigArray } = require("@humanwhocodes/config-array");
|
||||
```
|
||||
|
||||
When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional items in each config
|
||||
schema: mySchema
|
||||
});
|
||||
```
|
||||
|
||||
This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
|
||||
|
||||
### Specifying a Schema
|
||||
|
||||
The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
|
||||
const mySchema = {
|
||||
|
||||
// define the handler key in configs
|
||||
handler: {
|
||||
required: true,
|
||||
merge(a, b) {
|
||||
if (!b) return a;
|
||||
if (!a) return b;
|
||||
},
|
||||
validate(value) {
|
||||
if (typeof value !== "function") {
|
||||
throw new TypeError("Function expected.");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional item schemas in each config
|
||||
schema: mySchema,
|
||||
|
||||
// additional config types supported (default: [])
|
||||
extraConfigTypes: ["array", "function"];
|
||||
});
|
||||
```
|
||||
|
||||
### Config Arrays
|
||||
|
||||
Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
[
|
||||
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler
|
||||
}
|
||||
],
|
||||
|
||||
// filename must match function
|
||||
{
|
||||
files: [ filePath => filePath.endsWith(".md") ],
|
||||
handler: markdownHandler
|
||||
},
|
||||
|
||||
// filename must match all patterns in subarray
|
||||
{
|
||||
files: [ ["*.test.*", "*.js"] ],
|
||||
handler: jsTestHandler
|
||||
},
|
||||
|
||||
// filename must not match patterns beginning with !
|
||||
{
|
||||
name: "Non-JS files",
|
||||
files: ["!*.js"],
|
||||
settings: {
|
||||
js: false
|
||||
}
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
|
||||
|
||||
If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
|
||||
|
||||
If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
|
||||
|
||||
If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`.
|
||||
|
||||
You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// Always ignored
|
||||
{
|
||||
ignores: ["**/.git/**", "**/node_modules/**"]
|
||||
},
|
||||
|
||||
// .eslintrc.js file is ignored only when .js file matches
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
ignores: [".eslintrc.js"]
|
||||
handler: jsHandler
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
You can use negated patterns in `ignores` to exclude a file that was already ignored, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// Ignore all JSON files except tsconfig.json
|
||||
{
|
||||
files: ["**/*"],
|
||||
ignores: ["**/*.json", "!tsconfig.json"]
|
||||
},
|
||||
|
||||
];
|
||||
```
|
||||
|
||||
### Config Functions
|
||||
|
||||
Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
function (context) {
|
||||
return [
|
||||
|
||||
// match all JSON files
|
||||
{
|
||||
name: context.name + " JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: context.name + " package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
When a config array is normalized, each function is executed and replaced in the config array with the return value.
|
||||
|
||||
**Note:** Config functions can also be async.
|
||||
|
||||
### Normalizing Config Arrays
|
||||
|
||||
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
|
||||
|
||||
To normalize a config array, call the `normalize()` method and pass in a context object:
|
||||
|
||||
```js
|
||||
await configs.normalize({
|
||||
name: "MyApp"
|
||||
});
|
||||
```
|
||||
|
||||
The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
|
||||
|
||||
If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise:
|
||||
|
||||
```js
|
||||
await configs.normalizeSync({
|
||||
name: "MyApp"
|
||||
});
|
||||
```
|
||||
|
||||
**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
|
||||
|
||||
### Getting Config for a File
|
||||
|
||||
To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
|
||||
|
||||
```js
|
||||
// pass in absolute filename
|
||||
const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json"));
|
||||
```
|
||||
|
||||
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
|
||||
|
||||
A few things to keep in mind:
|
||||
|
||||
* You must pass in the absolute filename to get a config for.
|
||||
* The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
|
||||
* The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
|
||||
* A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry ending with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches.
|
||||
|
||||
## Determining Ignored Paths
|
||||
|
||||
You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the absolute path of any file, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isFileIgnored('/foo/bar/baz.txt');
|
||||
```
|
||||
|
||||
A file is considered ignored if any of the following is true:
|
||||
|
||||
* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored.
|
||||
* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored.
|
||||
* **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
For directories, use the `isDirectoryIgnored()` method and pass in the absolute path of any directory, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isDirectoryIgnored('/foo/bar/');
|
||||
```
|
||||
|
||||
A directory is considered ignored if any of the following is true:
|
||||
|
||||
* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored.
|
||||
* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored.
|
||||
* **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are *not* ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`.
|
||||
|
||||
## Caching Mechanisms
|
||||
|
||||
Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways:
|
||||
|
||||
1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in.
|
||||
2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
|
||||
|
||||
* Teddy Katz (@not-an-aardvark)
|
||||
* Toru Nagashima (@mysticatea)
|
||||
* Kai Cataldo (@kaicataldo)
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
+1128
@@ -0,0 +1,1128 @@
|
||||
'use strict';
|
||||
|
||||
var path = require('path');
|
||||
var minimatch = require('minimatch');
|
||||
var createDebug = require('debug');
|
||||
var objectSchema = require('@humanwhocodes/object-schema');
|
||||
|
||||
/**
|
||||
* @fileoverview ConfigSchema
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const NOOP_STRATEGY = {
|
||||
required: false,
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate() { }
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Exports
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The base schema that every ConfigArray uses.
|
||||
* @type Object
|
||||
*/
|
||||
const baseSchema = Object.freeze({
|
||||
name: {
|
||||
required: false,
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate(value) {
|
||||
if (typeof value !== 'string') {
|
||||
throw new TypeError('Property must be a string.');
|
||||
}
|
||||
}
|
||||
},
|
||||
files: NOOP_STRATEGY,
|
||||
ignores: NOOP_STRATEGY
|
||||
});
|
||||
|
||||
/**
|
||||
* @fileoverview ConfigSchema
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Asserts that a given value is an array.
|
||||
* @param {*} value The value to check.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} When the value is not an array.
|
||||
*/
|
||||
function assertIsArray(value) {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError('Expected value to be an array.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a given value is an array containing only strings and functions.
|
||||
* @param {*} value The value to check.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} When the value is not an array of strings and functions.
|
||||
*/
|
||||
function assertIsArrayOfStringsAndFunctions(value, name) {
|
||||
assertIsArray(value);
|
||||
|
||||
if (value.some(item => typeof item !== 'string' && typeof item !== 'function')) {
|
||||
throw new TypeError('Expected array to only contain strings and functions.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a given value is a non-empty array.
|
||||
* @param {*} value The value to check.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} When the value is not an array or an empty array.
|
||||
*/
|
||||
function assertIsNonEmptyArray(value) {
|
||||
if (!Array.isArray(value) || value.length === 0) {
|
||||
throw new TypeError('Expected value to be a non-empty array.');
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Exports
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The schema for `files` and `ignores` that every ConfigArray uses.
|
||||
* @type Object
|
||||
*/
|
||||
const filesAndIgnoresSchema = Object.freeze({
|
||||
files: {
|
||||
required: false,
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate(value) {
|
||||
|
||||
// first check if it's an array
|
||||
assertIsNonEmptyArray(value);
|
||||
|
||||
// then check each member
|
||||
value.forEach(item => {
|
||||
if (Array.isArray(item)) {
|
||||
assertIsArrayOfStringsAndFunctions(item);
|
||||
} else if (typeof item !== 'string' && typeof item !== 'function') {
|
||||
throw new TypeError('Items must be a string, a function, or an array of strings and functions.');
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
},
|
||||
ignores: {
|
||||
required: false,
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate: assertIsArrayOfStringsAndFunctions
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @fileoverview ConfigArray
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const Minimatch = minimatch.Minimatch;
|
||||
const minimatchCache = new Map();
|
||||
const negatedMinimatchCache = new Map();
|
||||
const debug = createDebug('@hwc/config-array');
|
||||
|
||||
const MINIMATCH_OPTIONS = {
|
||||
// matchBase: true,
|
||||
dot: true
|
||||
};
|
||||
|
||||
const CONFIG_TYPES = new Set(['array', 'function']);
|
||||
|
||||
/**
|
||||
* Fields that are considered metadata and not part of the config object.
|
||||
*/
|
||||
const META_FIELDS = new Set(['name']);
|
||||
|
||||
const FILES_AND_IGNORES_SCHEMA = new objectSchema.ObjectSchema(filesAndIgnoresSchema);
|
||||
|
||||
/**
|
||||
* Wrapper error for config validation errors that adds a name to the front of the
|
||||
* error message.
|
||||
*/
|
||||
class ConfigError extends Error {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} name The config object name causing the error.
|
||||
* @param {number} index The index of the config object in the array.
|
||||
* @param {Error} source The source error.
|
||||
*/
|
||||
constructor(name, index, { cause, message }) {
|
||||
|
||||
|
||||
const finalMessage = message || cause.message;
|
||||
|
||||
super(`Config ${name}: ${finalMessage}`, { cause });
|
||||
|
||||
// copy over custom properties that aren't represented
|
||||
if (cause) {
|
||||
for (const key of Object.keys(cause)) {
|
||||
if (!(key in this)) {
|
||||
this[key] = cause[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of the error.
|
||||
* @type {string}
|
||||
* @readonly
|
||||
*/
|
||||
this.name = 'ConfigError';
|
||||
|
||||
/**
|
||||
* The index of the config object in the array.
|
||||
* @type {number}
|
||||
* @readonly
|
||||
*/
|
||||
this.index = index;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the name of a config object.
|
||||
* @param {object} config The config object to get the name of.
|
||||
* @returns {string} The name of the config object.
|
||||
*/
|
||||
function getConfigName(config) {
|
||||
if (config && typeof config.name === 'string' && config.name) {
|
||||
return `"${config.name}"`;
|
||||
}
|
||||
|
||||
return '(unnamed)';
|
||||
}
|
||||
|
||||
/**
|
||||
* Rethrows a config error with additional information about the config object.
|
||||
* @param {object} config The config object to get the name of.
|
||||
* @param {number} index The index of the config object in the array.
|
||||
* @param {Error} error The error to rethrow.
|
||||
* @throws {ConfigError} When the error is rethrown for a config.
|
||||
*/
|
||||
function rethrowConfigError(config, index, error) {
|
||||
const configName = getConfigName(config);
|
||||
throw new ConfigError(configName, index, error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand for checking if a value is a string.
|
||||
* @param {any} value The value to check.
|
||||
* @returns {boolean} True if a string, false if not.
|
||||
*/
|
||||
function isString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a function that asserts that the config is valid
|
||||
* during normalization. This checks that the config is not nullish
|
||||
* and that files and ignores keys of a config object are valid as per base schema.
|
||||
* @param {Object} config The config object to check.
|
||||
* @param {number} index The index of the config object in the array.
|
||||
* @returns {void}
|
||||
* @throws {ConfigError} If the files and ignores keys of a config object are not valid.
|
||||
*/
|
||||
function assertValidBaseConfig(config, index) {
|
||||
|
||||
if (config === null) {
|
||||
throw new ConfigError(getConfigName(config), index, { message: 'Unexpected null config.' });
|
||||
}
|
||||
|
||||
if (config === undefined) {
|
||||
throw new ConfigError(getConfigName(config), index, { message: 'Unexpected undefined config.' });
|
||||
}
|
||||
|
||||
if (typeof config !== 'object') {
|
||||
throw new ConfigError(getConfigName(config), index, { message: 'Unexpected non-object config.' });
|
||||
}
|
||||
|
||||
const validateConfig = { };
|
||||
|
||||
if ('files' in config) {
|
||||
validateConfig.files = config.files;
|
||||
}
|
||||
|
||||
if ('ignores' in config) {
|
||||
validateConfig.ignores = config.ignores;
|
||||
}
|
||||
|
||||
try {
|
||||
FILES_AND_IGNORES_SCHEMA.validate(validateConfig);
|
||||
} catch (validationError) {
|
||||
rethrowConfigError(config, index, { cause: validationError });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper around minimatch that caches minimatch patterns for
|
||||
* faster matching speed over multiple file path evaluations.
|
||||
* @param {string} filepath The file path to match.
|
||||
* @param {string} pattern The glob pattern to match against.
|
||||
* @param {object} options The minimatch options to use.
|
||||
* @returns
|
||||
*/
|
||||
function doMatch(filepath, pattern, options = {}) {
|
||||
|
||||
let cache = minimatchCache;
|
||||
|
||||
if (options.flipNegate) {
|
||||
cache = negatedMinimatchCache;
|
||||
}
|
||||
|
||||
let matcher = cache.get(pattern);
|
||||
|
||||
if (!matcher) {
|
||||
matcher = new Minimatch(pattern, Object.assign({}, MINIMATCH_OPTIONS, options));
|
||||
cache.set(pattern, matcher);
|
||||
}
|
||||
|
||||
return matcher.match(filepath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a `ConfigArray` by flattening it and executing any functions
|
||||
* that are found inside.
|
||||
* @param {Array} items The items in a `ConfigArray`.
|
||||
* @param {Object} context The context object to pass into any function
|
||||
* found.
|
||||
* @param {Array<string>} extraConfigTypes The config types to check.
|
||||
* @returns {Promise<Array>} A flattened array containing only config objects.
|
||||
* @throws {TypeError} When a config function returns a function.
|
||||
*/
|
||||
async function normalize(items, context, extraConfigTypes) {
|
||||
|
||||
const allowFunctions = extraConfigTypes.includes('function');
|
||||
const allowArrays = extraConfigTypes.includes('array');
|
||||
|
||||
async function* flatTraverse(array) {
|
||||
for (let item of array) {
|
||||
if (typeof item === 'function') {
|
||||
if (!allowFunctions) {
|
||||
throw new TypeError('Unexpected function.');
|
||||
}
|
||||
|
||||
item = item(context);
|
||||
if (item.then) {
|
||||
item = await item;
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(item)) {
|
||||
if (!allowArrays) {
|
||||
throw new TypeError('Unexpected array.');
|
||||
}
|
||||
yield* flatTraverse(item);
|
||||
} else if (typeof item === 'function') {
|
||||
throw new TypeError('A config function can only return an object or array.');
|
||||
} else {
|
||||
yield item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Async iterables cannot be used with the spread operator, so we need to manually
|
||||
* create the array to return.
|
||||
*/
|
||||
const asyncIterable = await flatTraverse(items);
|
||||
const configs = [];
|
||||
|
||||
for await (const config of asyncIterable) {
|
||||
configs.push(config);
|
||||
}
|
||||
|
||||
return configs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a `ConfigArray` by flattening it and executing any functions
|
||||
* that are found inside.
|
||||
* @param {Array} items The items in a `ConfigArray`.
|
||||
* @param {Object} context The context object to pass into any function
|
||||
* found.
|
||||
* @param {Array<string>} extraConfigTypes The config types to check.
|
||||
* @returns {Array} A flattened array containing only config objects.
|
||||
* @throws {TypeError} When a config function returns a function.
|
||||
*/
|
||||
function normalizeSync(items, context, extraConfigTypes) {
|
||||
|
||||
const allowFunctions = extraConfigTypes.includes('function');
|
||||
const allowArrays = extraConfigTypes.includes('array');
|
||||
|
||||
function* flatTraverse(array) {
|
||||
for (let item of array) {
|
||||
if (typeof item === 'function') {
|
||||
|
||||
if (!allowFunctions) {
|
||||
throw new TypeError('Unexpected function.');
|
||||
}
|
||||
|
||||
item = item(context);
|
||||
if (item.then) {
|
||||
throw new TypeError('Async config functions are not supported.');
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(item)) {
|
||||
|
||||
if (!allowArrays) {
|
||||
throw new TypeError('Unexpected array.');
|
||||
}
|
||||
|
||||
yield* flatTraverse(item);
|
||||
} else if (typeof item === 'function') {
|
||||
throw new TypeError('A config function can only return an object or array.');
|
||||
} else {
|
||||
yield item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...flatTraverse(items)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given file path should be ignored based on the given
|
||||
* matcher.
|
||||
* @param {Array<string|() => boolean>} ignores The ignore patterns to check.
|
||||
* @param {string} filePath The absolute path of the file to check.
|
||||
* @param {string} relativeFilePath The relative path of the file to check.
|
||||
* @returns {boolean} True if the path should be ignored and false if not.
|
||||
*/
|
||||
function shouldIgnorePath(ignores, filePath, relativeFilePath) {
|
||||
|
||||
// all files outside of the basePath are ignored
|
||||
if (relativeFilePath.startsWith('..')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ignores.reduce((ignored, matcher) => {
|
||||
|
||||
if (!ignored) {
|
||||
|
||||
if (typeof matcher === 'function') {
|
||||
return matcher(filePath);
|
||||
}
|
||||
|
||||
// don't check negated patterns because we're not ignored yet
|
||||
if (!matcher.startsWith('!')) {
|
||||
return doMatch(relativeFilePath, matcher);
|
||||
}
|
||||
|
||||
// otherwise we're still not ignored
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
// only need to check negated patterns because we're ignored
|
||||
if (typeof matcher === 'string' && matcher.startsWith('!')) {
|
||||
return !doMatch(relativeFilePath, matcher, {
|
||||
flipNegate: true
|
||||
});
|
||||
}
|
||||
|
||||
return ignored;
|
||||
|
||||
}, false);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given file path is matched by a config based on
|
||||
* `ignores` only.
|
||||
* @param {string} filePath The absolute file path to check.
|
||||
* @param {string} basePath The base path for the config.
|
||||
* @param {Object} config The config object to check.
|
||||
* @returns {boolean} True if the file path is matched by the config,
|
||||
* false if not.
|
||||
*/
|
||||
function pathMatchesIgnores(filePath, basePath, config) {
|
||||
|
||||
/*
|
||||
* For both files and ignores, functions are passed the absolute
|
||||
* file path while strings are compared against the relative
|
||||
* file path.
|
||||
*/
|
||||
const relativeFilePath = path.relative(basePath, filePath);
|
||||
|
||||
return Object.keys(config).filter(key => !META_FIELDS.has(key)).length > 1 &&
|
||||
!shouldIgnorePath(config.ignores, filePath, relativeFilePath);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determines if a given file path is matched by a config. If the config
|
||||
* has no `files` field, then it matches; otherwise, if a `files` field
|
||||
* is present then we match the globs in `files` and exclude any globs in
|
||||
* `ignores`.
|
||||
* @param {string} filePath The absolute file path to check.
|
||||
* @param {string} basePath The base path for the config.
|
||||
* @param {Object} config The config object to check.
|
||||
* @returns {boolean} True if the file path is matched by the config,
|
||||
* false if not.
|
||||
*/
|
||||
function pathMatches(filePath, basePath, config) {
|
||||
|
||||
/*
|
||||
* For both files and ignores, functions are passed the absolute
|
||||
* file path while strings are compared against the relative
|
||||
* file path.
|
||||
*/
|
||||
const relativeFilePath = path.relative(basePath, filePath);
|
||||
|
||||
// match both strings and functions
|
||||
const match = pattern => {
|
||||
|
||||
if (isString(pattern)) {
|
||||
return doMatch(relativeFilePath, pattern);
|
||||
}
|
||||
|
||||
if (typeof pattern === 'function') {
|
||||
return pattern(filePath);
|
||||
}
|
||||
|
||||
throw new TypeError(`Unexpected matcher type ${pattern}.`);
|
||||
};
|
||||
|
||||
// check for all matches to config.files
|
||||
let filePathMatchesPattern = config.files.some(pattern => {
|
||||
if (Array.isArray(pattern)) {
|
||||
return pattern.every(match);
|
||||
}
|
||||
|
||||
return match(pattern);
|
||||
});
|
||||
|
||||
/*
|
||||
* If the file path matches the config.files patterns, then check to see
|
||||
* if there are any files to ignore.
|
||||
*/
|
||||
if (filePathMatchesPattern && config.ignores) {
|
||||
filePathMatchesPattern = !shouldIgnorePath(config.ignores, filePath, relativeFilePath);
|
||||
}
|
||||
|
||||
return filePathMatchesPattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that a ConfigArray has been normalized.
|
||||
* @param {ConfigArray} configArray The ConfigArray to check.
|
||||
* @returns {void}
|
||||
* @throws {Error} When the `ConfigArray` is not normalized.
|
||||
*/
|
||||
function assertNormalized(configArray) {
|
||||
// TODO: Throw more verbose error
|
||||
if (!configArray.isNormalized()) {
|
||||
throw new Error('ConfigArray must be normalized to perform this operation.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that config types are valid.
|
||||
* @param {Array<string>} extraConfigTypes The config types to check.
|
||||
* @returns {void}
|
||||
* @throws {Error} When the config types array is invalid.
|
||||
*/
|
||||
function assertExtraConfigTypes(extraConfigTypes) {
|
||||
if (extraConfigTypes.length > 2) {
|
||||
throw new TypeError('configTypes must be an array with at most two items.');
|
||||
}
|
||||
|
||||
for (const configType of extraConfigTypes) {
|
||||
if (!CONFIG_TYPES.has(configType)) {
|
||||
throw new TypeError(`Unexpected config type "${configType}" found. Expected one of: "object", "array", "function".`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const ConfigArraySymbol = {
|
||||
isNormalized: Symbol('isNormalized'),
|
||||
configCache: Symbol('configCache'),
|
||||
schema: Symbol('schema'),
|
||||
finalizeConfig: Symbol('finalizeConfig'),
|
||||
preprocessConfig: Symbol('preprocessConfig')
|
||||
};
|
||||
|
||||
// used to store calculate data for faster lookup
|
||||
const dataCache = new WeakMap();
|
||||
|
||||
/**
|
||||
* Represents an array of config objects and provides method for working with
|
||||
* those config objects.
|
||||
*/
|
||||
class ConfigArray extends Array {
|
||||
|
||||
/**
|
||||
* Creates a new instance of ConfigArray.
|
||||
* @param {Iterable|Function|Object} configs An iterable yielding config
|
||||
* objects, or a config function, or a config object.
|
||||
* @param {string} [options.basePath=""] The path of the config file
|
||||
* @param {boolean} [options.normalized=false] Flag indicating if the
|
||||
* configs have already been normalized.
|
||||
* @param {Object} [options.schema] The additional schema
|
||||
* definitions to use for the ConfigArray schema.
|
||||
* @param {Array<string>} [options.configTypes] List of config types supported.
|
||||
*/
|
||||
constructor(configs, {
|
||||
basePath = '',
|
||||
normalized = false,
|
||||
schema: customSchema,
|
||||
extraConfigTypes = []
|
||||
} = {}
|
||||
) {
|
||||
super();
|
||||
|
||||
/**
|
||||
* Tracks if the array has been normalized.
|
||||
* @property isNormalized
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
this[ConfigArraySymbol.isNormalized] = normalized;
|
||||
|
||||
/**
|
||||
* The schema used for validating and merging configs.
|
||||
* @property schema
|
||||
* @type ObjectSchema
|
||||
* @private
|
||||
*/
|
||||
this[ConfigArraySymbol.schema] = new objectSchema.ObjectSchema(
|
||||
Object.assign({}, customSchema, baseSchema)
|
||||
);
|
||||
|
||||
/**
|
||||
* The path of the config file that this array was loaded from.
|
||||
* This is used to calculate filename matches.
|
||||
* @property basePath
|
||||
* @type {string}
|
||||
*/
|
||||
this.basePath = basePath;
|
||||
|
||||
assertExtraConfigTypes(extraConfigTypes);
|
||||
|
||||
/**
|
||||
* The supported config types.
|
||||
* @property configTypes
|
||||
* @type {Array<string>}
|
||||
*/
|
||||
this.extraConfigTypes = Object.freeze([...extraConfigTypes]);
|
||||
|
||||
/**
|
||||
* A cache to store calculated configs for faster repeat lookup.
|
||||
* @property configCache
|
||||
* @type {Map<string, Object>}
|
||||
* @private
|
||||
*/
|
||||
this[ConfigArraySymbol.configCache] = new Map();
|
||||
|
||||
// init cache
|
||||
dataCache.set(this, {
|
||||
explicitMatches: new Map(),
|
||||
directoryMatches: new Map(),
|
||||
files: undefined,
|
||||
ignores: undefined
|
||||
});
|
||||
|
||||
// load the configs into this array
|
||||
if (Array.isArray(configs)) {
|
||||
this.push(...configs);
|
||||
} else {
|
||||
this.push(configs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent normal array methods from creating a new `ConfigArray` instance.
|
||||
* This is to ensure that methods such as `slice()` won't try to create a
|
||||
* new instance of `ConfigArray` behind the scenes as doing so may throw
|
||||
* an error due to the different constructor signature.
|
||||
* @returns {Function} The `Array` constructor.
|
||||
*/
|
||||
static get [Symbol.species]() {
|
||||
return Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `files` globs from every config object in the array.
|
||||
* This can be used to determine which files will be matched by a
|
||||
* config array or to use as a glob pattern when no patterns are provided
|
||||
* for a command line interface.
|
||||
* @returns {Array<string|Function>} An array of matchers.
|
||||
*/
|
||||
get files() {
|
||||
|
||||
assertNormalized(this);
|
||||
|
||||
// if this data has been cached, retrieve it
|
||||
const cache = dataCache.get(this);
|
||||
|
||||
if (cache.files) {
|
||||
return cache.files;
|
||||
}
|
||||
|
||||
// otherwise calculate it
|
||||
|
||||
const result = [];
|
||||
|
||||
for (const config of this) {
|
||||
if (config.files) {
|
||||
config.files.forEach(filePattern => {
|
||||
result.push(filePattern);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// store result
|
||||
cache.files = result;
|
||||
dataCache.set(this, cache);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns ignore matchers that should always be ignored regardless of
|
||||
* the matching `files` fields in any configs. This is necessary to mimic
|
||||
* the behavior of things like .gitignore and .eslintignore, allowing a
|
||||
* globbing operation to be faster.
|
||||
* @returns {string[]} An array of string patterns and functions to be ignored.
|
||||
*/
|
||||
get ignores() {
|
||||
|
||||
assertNormalized(this);
|
||||
|
||||
// if this data has been cached, retrieve it
|
||||
const cache = dataCache.get(this);
|
||||
|
||||
if (cache.ignores) {
|
||||
return cache.ignores;
|
||||
}
|
||||
|
||||
// otherwise calculate it
|
||||
|
||||
const result = [];
|
||||
|
||||
for (const config of this) {
|
||||
|
||||
/*
|
||||
* We only count ignores if there are no other keys in the object.
|
||||
* In this case, it acts list a globally ignored pattern. If there
|
||||
* are additional keys, then ignores act like exclusions.
|
||||
*/
|
||||
if (config.ignores && Object.keys(config).filter(key => !META_FIELDS.has(key)).length === 1) {
|
||||
result.push(...config.ignores);
|
||||
}
|
||||
}
|
||||
|
||||
// store result
|
||||
cache.ignores = result;
|
||||
dataCache.set(this, cache);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the config array has been normalized.
|
||||
* @returns {boolean} True if the config array is normalized, false if not.
|
||||
*/
|
||||
isNormalized() {
|
||||
return this[ConfigArraySymbol.isNormalized];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a config array by flattening embedded arrays and executing
|
||||
* config functions.
|
||||
* @param {ConfigContext} context The context object for config functions.
|
||||
* @returns {Promise<ConfigArray>} The current ConfigArray instance.
|
||||
*/
|
||||
async normalize(context = {}) {
|
||||
|
||||
if (!this.isNormalized()) {
|
||||
const normalizedConfigs = await normalize(this, context, this.extraConfigTypes);
|
||||
this.length = 0;
|
||||
this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this)));
|
||||
this.forEach(assertValidBaseConfig);
|
||||
this[ConfigArraySymbol.isNormalized] = true;
|
||||
|
||||
// prevent further changes
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a config array by flattening embedded arrays and executing
|
||||
* config functions.
|
||||
* @param {ConfigContext} context The context object for config functions.
|
||||
* @returns {ConfigArray} The current ConfigArray instance.
|
||||
*/
|
||||
normalizeSync(context = {}) {
|
||||
|
||||
if (!this.isNormalized()) {
|
||||
const normalizedConfigs = normalizeSync(this, context, this.extraConfigTypes);
|
||||
this.length = 0;
|
||||
this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this)));
|
||||
this.forEach(assertValidBaseConfig);
|
||||
this[ConfigArraySymbol.isNormalized] = true;
|
||||
|
||||
// prevent further changes
|
||||
Object.freeze(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizes the state of a config before being cached and returned by
|
||||
* `getConfig()`. Does nothing by default but is provided to be
|
||||
* overridden by subclasses as necessary.
|
||||
* @param {Object} config The config to finalize.
|
||||
* @returns {Object} The finalized config.
|
||||
*/
|
||||
[ConfigArraySymbol.finalizeConfig](config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Preprocesses a config during the normalization process. This is the
|
||||
* method to override if you want to convert an array item before it is
|
||||
* validated for the first time. For example, if you want to replace a
|
||||
* string with an object, this is the method to override.
|
||||
* @param {Object} config The config to preprocess.
|
||||
* @returns {Object} The config to use in place of the argument.
|
||||
*/
|
||||
[ConfigArraySymbol.preprocessConfig](config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given file path explicitly matches a `files` entry
|
||||
* and also doesn't match an `ignores` entry. Configs that don't have
|
||||
* a `files` property are not considered an explicit match.
|
||||
* @param {string} filePath The complete path of a file to check.
|
||||
* @returns {boolean} True if the file path matches a `files` entry
|
||||
* or false if not.
|
||||
*/
|
||||
isExplicitMatch(filePath) {
|
||||
|
||||
assertNormalized(this);
|
||||
|
||||
const cache = dataCache.get(this);
|
||||
|
||||
// first check the cache to avoid duplicate work
|
||||
let result = cache.explicitMatches.get(filePath);
|
||||
|
||||
if (typeof result == 'boolean') {
|
||||
return result;
|
||||
}
|
||||
|
||||
// TODO: Maybe move elsewhere? Maybe combine with getConfig() logic?
|
||||
const relativeFilePath = path.relative(this.basePath, filePath);
|
||||
|
||||
if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) {
|
||||
debug(`Ignoring ${filePath}`);
|
||||
|
||||
// cache and return result
|
||||
cache.explicitMatches.set(filePath, false);
|
||||
return false;
|
||||
}
|
||||
|
||||
// filePath isn't automatically ignored, so try to find a match
|
||||
|
||||
for (const config of this) {
|
||||
|
||||
if (!config.files) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (pathMatches(filePath, this.basePath, config)) {
|
||||
debug(`Matching config found for ${filePath}`);
|
||||
cache.explicitMatches.set(filePath, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the config object for a given file path.
|
||||
* @param {string} filePath The complete path of a file to get a config for.
|
||||
* @returns {Object} The config object for this file.
|
||||
*/
|
||||
getConfig(filePath) {
|
||||
|
||||
assertNormalized(this);
|
||||
|
||||
const cache = this[ConfigArraySymbol.configCache];
|
||||
|
||||
// first check the cache for a filename match to avoid duplicate work
|
||||
if (cache.has(filePath)) {
|
||||
return cache.get(filePath);
|
||||
}
|
||||
|
||||
let finalConfig;
|
||||
|
||||
// next check to see if the file should be ignored
|
||||
|
||||
// check if this should be ignored due to its directory
|
||||
if (this.isDirectoryIgnored(path.dirname(filePath))) {
|
||||
debug(`Ignoring ${filePath} based on directory pattern`);
|
||||
|
||||
// cache and return result - finalConfig is undefined at this point
|
||||
cache.set(filePath, finalConfig);
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
// TODO: Maybe move elsewhere?
|
||||
const relativeFilePath = path.relative(this.basePath, filePath);
|
||||
|
||||
if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) {
|
||||
debug(`Ignoring ${filePath} based on file pattern`);
|
||||
|
||||
// cache and return result - finalConfig is undefined at this point
|
||||
cache.set(filePath, finalConfig);
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
// filePath isn't automatically ignored, so try to construct config
|
||||
|
||||
const matchingConfigIndices = [];
|
||||
let matchFound = false;
|
||||
const universalPattern = /\/\*{1,2}$/;
|
||||
|
||||
this.forEach((config, index) => {
|
||||
|
||||
if (!config.files) {
|
||||
|
||||
if (!config.ignores) {
|
||||
debug(`Anonymous universal config found for ${filePath}`);
|
||||
matchingConfigIndices.push(index);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathMatchesIgnores(filePath, this.basePath, config)) {
|
||||
debug(`Matching config found for ${filePath} (based on ignores: ${config.ignores})`);
|
||||
matchingConfigIndices.push(index);
|
||||
return;
|
||||
}
|
||||
|
||||
debug(`Skipped config found for ${filePath} (based on ignores: ${config.ignores})`);
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* If a config has a files pattern ending in /** or /*, and the
|
||||
* filePath only matches those patterns, then the config is only
|
||||
* applied if there is another config where the filePath matches
|
||||
* a file with a specific extensions such as *.js.
|
||||
*/
|
||||
|
||||
const universalFiles = config.files.filter(
|
||||
pattern => universalPattern.test(pattern)
|
||||
);
|
||||
|
||||
// universal patterns were found so we need to check the config twice
|
||||
if (universalFiles.length) {
|
||||
|
||||
debug('Universal files patterns found. Checking carefully.');
|
||||
|
||||
const nonUniversalFiles = config.files.filter(
|
||||
pattern => !universalPattern.test(pattern)
|
||||
);
|
||||
|
||||
// check that the config matches without the non-universal files first
|
||||
if (
|
||||
nonUniversalFiles.length &&
|
||||
pathMatches(
|
||||
filePath, this.basePath,
|
||||
{ files: nonUniversalFiles, ignores: config.ignores }
|
||||
)
|
||||
) {
|
||||
debug(`Matching config found for ${filePath}`);
|
||||
matchingConfigIndices.push(index);
|
||||
matchFound = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// if there wasn't a match then check if it matches with universal files
|
||||
if (
|
||||
universalFiles.length &&
|
||||
pathMatches(
|
||||
filePath, this.basePath,
|
||||
{ files: universalFiles, ignores: config.ignores }
|
||||
)
|
||||
) {
|
||||
debug(`Matching config found for ${filePath}`);
|
||||
matchingConfigIndices.push(index);
|
||||
return;
|
||||
}
|
||||
|
||||
// if we make here, then there was no match
|
||||
return;
|
||||
}
|
||||
|
||||
// the normal case
|
||||
if (pathMatches(filePath, this.basePath, config)) {
|
||||
debug(`Matching config found for ${filePath}`);
|
||||
matchingConfigIndices.push(index);
|
||||
matchFound = true;
|
||||
return;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// if matching both files and ignores, there will be no config to create
|
||||
if (!matchFound) {
|
||||
debug(`No matching configs found for ${filePath}`);
|
||||
|
||||
// cache and return result - finalConfig is undefined at this point
|
||||
cache.set(filePath, finalConfig);
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
// check to see if there is a config cached by indices
|
||||
finalConfig = cache.get(matchingConfigIndices.toString());
|
||||
|
||||
if (finalConfig) {
|
||||
|
||||
// also store for filename for faster lookup next time
|
||||
cache.set(filePath, finalConfig);
|
||||
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
// otherwise construct the config
|
||||
|
||||
finalConfig = matchingConfigIndices.reduce((result, index) => {
|
||||
try {
|
||||
return this[ConfigArraySymbol.schema].merge(result, this[index]);
|
||||
} catch (validationError) {
|
||||
rethrowConfigError(this[index], index, { cause: validationError});
|
||||
}
|
||||
}, {}, this);
|
||||
|
||||
finalConfig = this[ConfigArraySymbol.finalizeConfig](finalConfig);
|
||||
|
||||
cache.set(filePath, finalConfig);
|
||||
cache.set(matchingConfigIndices.toString(), finalConfig);
|
||||
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the given filepath is ignored based on the configs.
|
||||
* @param {string} filePath The complete path of a file to check.
|
||||
* @returns {boolean} True if the path is ignored, false if not.
|
||||
* @deprecated Use `isFileIgnored` instead.
|
||||
*/
|
||||
isIgnored(filePath) {
|
||||
return this.isFileIgnored(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the given filepath is ignored based on the configs.
|
||||
* @param {string} filePath The complete path of a file to check.
|
||||
* @returns {boolean} True if the path is ignored, false if not.
|
||||
*/
|
||||
isFileIgnored(filePath) {
|
||||
return this.getConfig(filePath) === undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the given directory is ignored based on the configs.
|
||||
* This checks only default `ignores` that don't have `files` in the
|
||||
* same config. A pattern such as `/foo` be considered to ignore the directory
|
||||
* while a pattern such as `/foo/**` is not considered to ignore the
|
||||
* directory because it is matching files.
|
||||
* @param {string} directoryPath The complete path of a directory to check.
|
||||
* @returns {boolean} True if the directory is ignored, false if not. Will
|
||||
* return true for any directory that is not inside of `basePath`.
|
||||
* @throws {Error} When the `ConfigArray` is not normalized.
|
||||
*/
|
||||
isDirectoryIgnored(directoryPath) {
|
||||
|
||||
assertNormalized(this);
|
||||
|
||||
const relativeDirectoryPath = path.relative(this.basePath, directoryPath)
|
||||
.replace(/\\/g, '/');
|
||||
|
||||
if (relativeDirectoryPath.startsWith('..')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// first check the cache
|
||||
const cache = dataCache.get(this).directoryMatches;
|
||||
|
||||
if (cache.has(relativeDirectoryPath)) {
|
||||
return cache.get(relativeDirectoryPath);
|
||||
}
|
||||
|
||||
const directoryParts = relativeDirectoryPath.split('/');
|
||||
let relativeDirectoryToCheck = '';
|
||||
let result = false;
|
||||
|
||||
/*
|
||||
* In order to get the correct gitignore-style ignores, where an
|
||||
* ignored parent directory cannot have any descendants unignored,
|
||||
* we need to check every directory starting at the parent all
|
||||
* the way down to the actual requested directory.
|
||||
*
|
||||
* We aggressively cache all of this info to make sure we don't
|
||||
* have to recalculate everything for every call.
|
||||
*/
|
||||
do {
|
||||
|
||||
relativeDirectoryToCheck += directoryParts.shift() + '/';
|
||||
|
||||
result = shouldIgnorePath(
|
||||
this.ignores,
|
||||
path.join(this.basePath, relativeDirectoryToCheck),
|
||||
relativeDirectoryToCheck
|
||||
);
|
||||
|
||||
cache.set(relativeDirectoryToCheck, result);
|
||||
|
||||
} while (!result && directoryParts.length);
|
||||
|
||||
// also cache the result for the requested path
|
||||
cache.set(relativeDirectoryPath, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
exports.ConfigArray = ConfigArray;
|
||||
exports.ConfigArraySymbol = ConfigArraySymbol;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@humanwhocodes/config-array",
|
||||
"version": "0.13.0",
|
||||
"description": "Glob-based configuration matching.",
|
||||
"author": "Nicholas C. Zakas",
|
||||
"main": "api.js",
|
||||
"files": [
|
||||
"api.js",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/humanwhocodes/config-array.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/humanwhocodes/config-array/issues"
|
||||
},
|
||||
"homepage": "https://github.com/humanwhocodes/config-array#readme",
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"format": "nitpik",
|
||||
"lint": "eslint *.config.js src/*.js tests/*.js",
|
||||
"lint:fix": "eslint --fix *.config.js src/*.js tests/*.js",
|
||||
"prepublish": "npm run build",
|
||||
"test:coverage": "nyc --include src/*.js npm run test",
|
||||
"test": "mocha -r esm tests/ --recursive"
|
||||
},
|
||||
"gitHooks": {
|
||||
"pre-commit": "lint-staged"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.js": [
|
||||
"eslint --fix --ignore-pattern '!.eslintrc.js'"
|
||||
]
|
||||
},
|
||||
"keywords": [
|
||||
"configuration",
|
||||
"configarray",
|
||||
"config file"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=10.10.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@humanwhocodes/object-schema": "^2.0.3",
|
||||
"debug": "^4.3.1",
|
||||
"minimatch": "^3.0.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nitpik/javascript": "0.4.0",
|
||||
"@nitpik/node": "0.0.5",
|
||||
"chai": "4.3.10",
|
||||
"eslint": "8.52.0",
|
||||
"esm": "3.2.25",
|
||||
"lint-staged": "15.0.2",
|
||||
"mocha": "6.2.3",
|
||||
"nyc": "15.1.0",
|
||||
"rollup": "3.28.1",
|
||||
"yorkie": "2.0.0"
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Changelog
|
||||
|
||||
## [1.0.1](https://github.com/humanwhocodes/module-importer/compare/v1.0.0...v1.0.1) (2022-08-18)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Ensure CommonJS mode works correctly. ([cf54a0b](https://github.com/humanwhocodes/module-importer/commit/cf54a0b998085066fbe1776dd0b4cacd808cc192)), closes [#6](https://github.com/humanwhocodes/module-importer/issues/6)
|
||||
|
||||
## 1.0.0 (2022-08-17)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Implement ModuleImporter ([3ce4e82](https://www.github.com/humanwhocodes/module-importer/commit/3ce4e820c30c114e787bfed00a0966ac4772f563))
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
# ModuleImporter
|
||||
|
||||
by [Nicholas C. Zakas](https://humanwhocodes.com)
|
||||
|
||||
If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
|
||||
|
||||
## Description
|
||||
|
||||
A utility for seamlessly importing modules in Node.js regardless if they are CommonJS or ESM format. Under the hood, this uses `import()` and relies on Node.js's CommonJS compatibility to work correctly. This ensures that the correct locations and formats are used for CommonJS so you can call one method and not worry about any compatibility issues.
|
||||
|
||||
The problem with the default `import()` is that it always resolves relative to the file location in which it is called. If you want to resolve from a different location, you need to jump through a few hoops to achieve that. This package makes it easy to both resolve and import modules from any directory.
|
||||
|
||||
## Usage
|
||||
|
||||
### Node.js
|
||||
|
||||
Install using [npm][npm] or [yarn][yarn]:
|
||||
|
||||
```
|
||||
npm install @humanwhocodes/module-importer
|
||||
|
||||
# or
|
||||
|
||||
yarn add @humanwhocodes/module-importer
|
||||
```
|
||||
|
||||
Import into your Node.js project:
|
||||
|
||||
```js
|
||||
// CommonJS
|
||||
const { ModuleImporter } = require("@humanwhocodes/module-importer");
|
||||
|
||||
// ESM
|
||||
import { ModuleImporter } from "@humanwhocodes/module-importer";
|
||||
```
|
||||
|
||||
### Bun
|
||||
|
||||
Install using this command:
|
||||
|
||||
```
|
||||
bun add @humanwhocodes/module-importer
|
||||
```
|
||||
|
||||
Import into your Bun project:
|
||||
|
||||
```js
|
||||
import { ModuleImporter } from "@humanwhocodes/module-importer";
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
After importing, create a new instance of `ModuleImporter` to start emitting events:
|
||||
|
||||
```js
|
||||
// cwd can be omitted to use process.cwd()
|
||||
const importer = new ModuleImporter(cwd);
|
||||
|
||||
// you can resolve the location of any package
|
||||
const location = importer.resolve("./some-file.cjs");
|
||||
|
||||
// you can also import directly
|
||||
const module = importer.import("./some-file.cjs");
|
||||
```
|
||||
|
||||
For both `resolve()` and `import()`, you can pass in package names and filenames.
|
||||
|
||||
## Developer Setup
|
||||
|
||||
1. Fork the repository
|
||||
2. Clone your fork
|
||||
3. Run `npm install` to setup dependencies
|
||||
4. Run `npm test` to run tests
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
|
||||
[npm]: https://npmjs.com/
|
||||
[yarn]: https://yarnpkg.com/
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var module$1 = require('module');
|
||||
var url = require('url');
|
||||
var path = require('path');
|
||||
|
||||
/**
|
||||
* @fileoverview Universal module importer
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('module-importer.cjs', document.baseURI).href)));
|
||||
const __dirname$1 = path.dirname(__filename$1);
|
||||
const require$1 = module$1.createRequire(__dirname$1 + "/");
|
||||
const { ModuleImporter } = require$1("./module-importer.cjs");
|
||||
|
||||
exports.ModuleImporter = ModuleImporter;
|
||||
Generated
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
export class ModuleImporter {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} [cwd] The current working directory to resolve from.
|
||||
*/
|
||||
constructor(cwd?: string);
|
||||
/**
|
||||
* The base directory from which paths should be resolved.
|
||||
* @type {string}
|
||||
*/
|
||||
cwd: string;
|
||||
/**
|
||||
* Resolves a module based on its name or location.
|
||||
* @param {string} specifier Either an npm package name or
|
||||
* relative file path.
|
||||
* @returns {string|undefined} The location of the import.
|
||||
* @throws {Error} If specifier cannot be located.
|
||||
*/
|
||||
resolve(specifier: string): string | undefined;
|
||||
/**
|
||||
* Imports a module based on its name or location.
|
||||
* @param {string} specifier Either an npm package name or
|
||||
* relative file path.
|
||||
* @returns {Promise<object>} The module's object.
|
||||
*/
|
||||
import(specifier: string): Promise<object>;
|
||||
}
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
export { ModuleImporter };
|
||||
import { ModuleImporter } from "./module-importer.cjs";
|
||||
Generated
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
import { createRequire } from 'module';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname } from 'path';
|
||||
|
||||
/**
|
||||
* @fileoverview Universal module importer
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const require = createRequire(__dirname + "/");
|
||||
const { ModuleImporter } = require("./module-importer.cjs");
|
||||
|
||||
export { ModuleImporter };
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "@humanwhocodes/module-importer",
|
||||
"version": "1.0.1",
|
||||
"description": "Universal module importer for Node.js",
|
||||
"main": "src/module-importer.cjs",
|
||||
"module": "src/module-importer.js",
|
||||
"type": "module",
|
||||
"types": "dist/module-importer.d.ts",
|
||||
"exports": {
|
||||
"require": "./src/module-importer.cjs",
|
||||
"import": "./src/module-importer.js"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"gitHooks": {
|
||||
"pre-commit": "lint-staged"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.js": [
|
||||
"eslint --fix"
|
||||
]
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nzakas"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rollup -c && tsc",
|
||||
"prepare": "npm run build",
|
||||
"lint": "eslint src/ tests/",
|
||||
"test:unit": "c8 mocha tests/module-importer.test.js",
|
||||
"test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs",
|
||||
"test": "npm run test:unit && npm run test:build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/humanwhocodes/module-importer.git"
|
||||
},
|
||||
"keywords": [
|
||||
"modules",
|
||||
"esm",
|
||||
"commonjs"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=12.22"
|
||||
},
|
||||
"author": "Nicholas C. Zaks",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.7.6",
|
||||
"c8": "7.12.0",
|
||||
"chai": "4.3.6",
|
||||
"eslint": "8.22.0",
|
||||
"lint-staged": "13.0.3",
|
||||
"mocha": "9.2.2",
|
||||
"rollup": "2.78.0",
|
||||
"typescript": "4.7.4",
|
||||
"yorkie": "2.0.0"
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+81
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @fileoverview Universal module importer
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Imports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const { createRequire } = require("module");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const SLASHES = new Set(["/", "\\"]);
|
||||
|
||||
/**
|
||||
* Normalizes directories to have a trailing slash.
|
||||
* Resolve is pretty finicky -- if the directory name doesn't have
|
||||
* a trailing slash then it tries to look in the parent directory.
|
||||
* i.e., if the directory is "/usr/nzakas/foo" it will start the
|
||||
* search in /usr/nzakas. However, if the directory is "/user/nzakas/foo/",
|
||||
* then it will start the search in /user/nzakas/foo.
|
||||
* @param {string} directory The directory to check.
|
||||
* @returns {string} The normalized directory.
|
||||
*/
|
||||
function normalizeDirectory(directory) {
|
||||
if (!SLASHES.has(directory[directory.length-1])) {
|
||||
return directory + "/";
|
||||
}
|
||||
|
||||
return directory;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Class for importing both CommonJS and ESM modules in Node.js.
|
||||
*/
|
||||
exports.ModuleImporter = class ModuleImporter {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} [cwd] The current working directory to resolve from.
|
||||
*/
|
||||
constructor(cwd = process.cwd()) {
|
||||
|
||||
/**
|
||||
* The base directory from which paths should be resolved.
|
||||
* @type {string}
|
||||
*/
|
||||
this.cwd = normalizeDirectory(cwd);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a module based on its name or location.
|
||||
* @param {string} specifier Either an npm package name or
|
||||
* relative file path.
|
||||
* @returns {string|undefined} The location of the import.
|
||||
* @throws {Error} If specifier cannot be located.
|
||||
*/
|
||||
resolve(specifier) {
|
||||
const require = createRequire(this.cwd);
|
||||
return require.resolve(specifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports a module based on its name or location.
|
||||
* @param {string} specifier Either an npm package name or
|
||||
* relative file path.
|
||||
* @returns {Promise<object>} The module's object.
|
||||
*/
|
||||
import(specifier) {
|
||||
const location = this.resolve(specifier);
|
||||
return import(pathToFileURL(location).href);
|
||||
}
|
||||
|
||||
}
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @fileoverview Universal module importer
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Imports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
import { createRequire } from "module";
|
||||
import { fileURLToPath } from "url";
|
||||
import { dirname } from "path";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const require = createRequire(__dirname + "/");
|
||||
const { ModuleImporter } = require("./module-importer.cjs");
|
||||
|
||||
export { ModuleImporter };
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
# Changelog
|
||||
|
||||
## [2.0.3](https://github.com/humanwhocodes/object-schema/compare/v2.0.2...v2.0.3) (2024-04-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Ensure test files are not including in package ([6eeb32c](https://github.com/humanwhocodes/object-schema/commit/6eeb32cc76a3e37d76b2990bd603d72061c816e0)), closes [#19](https://github.com/humanwhocodes/object-schema/issues/19)
|
||||
|
||||
## [2.0.2](https://github.com/humanwhocodes/object-schema/compare/v2.0.1...v2.0.2) (2024-01-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* WrapperError should be an actual error ([2523f01](https://github.com/humanwhocodes/object-schema/commit/2523f014168167e5a40bb63e0cc03231b2c0f1bf))
|
||||
|
||||
## [2.0.1](https://github.com/humanwhocodes/object-schema/compare/v2.0.0...v2.0.1) (2023-10-20)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Custom properties should be available on thrown errors ([6ca80b0](https://github.com/humanwhocodes/object-schema/commit/6ca80b001a4ffb678b9b5544fc53322117374376))
|
||||
|
||||
## [2.0.0](https://github.com/humanwhocodes/object-schema/compare/v1.2.1...v2.0.0) (2023-10-18)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Throw custom errors instead of generics.
|
||||
|
||||
### Features
|
||||
|
||||
* Throw custom errors instead of generics. ([c6c01d7](https://github.com/humanwhocodes/object-schema/commit/c6c01d71eb354bf7b1fb3e883c40f7bd9b61647c))
|
||||
|
||||
### [1.2.1](https://www.github.com/humanwhocodes/object-schema/compare/v1.2.0...v1.2.1) (2021-11-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Never return original object from individual config ([5463c5c](https://www.github.com/humanwhocodes/object-schema/commit/5463c5c6d2cb35a7b7948dffc37c899a41d1775f))
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2019, Human Who Codes
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
# JavaScript ObjectSchema Package
|
||||
|
||||
by [Nicholas C. Zakas](https://humanwhocodes.com)
|
||||
|
||||
If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
|
||||
|
||||
## Overview
|
||||
|
||||
A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`.
|
||||
|
||||
## Installation
|
||||
|
||||
You can install using either npm:
|
||||
|
||||
```
|
||||
npm install @humanwhocodes/object-schema
|
||||
```
|
||||
|
||||
Or Yarn:
|
||||
|
||||
```
|
||||
yarn add @humanwhocodes/object-schema
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Use CommonJS to get access to the `ObjectSchema` constructor:
|
||||
|
||||
```js
|
||||
const { ObjectSchema } = require("@humanwhocodes/object-schema");
|
||||
|
||||
const schema = new ObjectSchema({
|
||||
|
||||
// define a definition for the "downloads" key
|
||||
downloads: {
|
||||
required: true,
|
||||
merge(value1, value2) {
|
||||
return value1 + value2;
|
||||
},
|
||||
validate(value) {
|
||||
if (typeof value !== "number") {
|
||||
throw new Error("Expected downloads to be a number.");
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// define a strategy for the "versions" key
|
||||
version: {
|
||||
required: true,
|
||||
merge(value1, value2) {
|
||||
return value1.concat(value2);
|
||||
},
|
||||
validate(value) {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error("Expected versions to be an array.");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const record1 = {
|
||||
downloads: 25,
|
||||
versions: [
|
||||
"v1.0.0",
|
||||
"v1.1.0",
|
||||
"v1.2.0"
|
||||
]
|
||||
};
|
||||
|
||||
const record2 = {
|
||||
downloads: 125,
|
||||
versions: [
|
||||
"v2.0.0",
|
||||
"v2.1.0",
|
||||
"v3.0.0"
|
||||
]
|
||||
};
|
||||
|
||||
// make sure the records are valid
|
||||
schema.validate(record1);
|
||||
schema.validate(record2);
|
||||
|
||||
// merge together (schema.merge() accepts any number of objects)
|
||||
const result = schema.merge(record1, record2);
|
||||
|
||||
// result looks like this:
|
||||
|
||||
const result = {
|
||||
downloads: 75,
|
||||
versions: [
|
||||
"v1.0.0",
|
||||
"v1.1.0",
|
||||
"v1.2.0",
|
||||
"v2.0.0",
|
||||
"v2.1.0",
|
||||
"v3.0.0"
|
||||
]
|
||||
};
|
||||
```
|
||||
|
||||
## Tips and Tricks
|
||||
|
||||
### Named merge strategies
|
||||
|
||||
Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy:
|
||||
|
||||
* `"assign"` - use `Object.assign()` to merge the two values into one object.
|
||||
* `"overwrite"` - the second value always replaces the first.
|
||||
* `"replace"` - the second value replaces the first if the second is not `undefined`.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
const schema = new ObjectSchema({
|
||||
name: {
|
||||
merge: "replace",
|
||||
validate() {}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Named validation strategies
|
||||
|
||||
Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy:
|
||||
|
||||
* `"array"` - value must be an array.
|
||||
* `"boolean"` - value must be a boolean.
|
||||
* `"number"` - value must be a number.
|
||||
* `"object"` - value must be an object.
|
||||
* `"object?"` - value must be an object or null.
|
||||
* `"string"` - value must be a string.
|
||||
* `"string!"` - value must be a non-empty string.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
const schema = new ObjectSchema({
|
||||
name: {
|
||||
merge: "replace",
|
||||
validate: "string"
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Subschemas
|
||||
|
||||
If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, assign a `schema` key that contains a schema definition, like this:
|
||||
|
||||
```js
|
||||
const schema = new ObjectSchema({
|
||||
name: {
|
||||
schema: {
|
||||
first: {
|
||||
merge: "replace",
|
||||
validate: "string"
|
||||
},
|
||||
last: {
|
||||
merge: "replace",
|
||||
validate: "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
schema.validate({
|
||||
name: {
|
||||
first: "n",
|
||||
last: "z"
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Remove Keys During Merge
|
||||
|
||||
If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example:
|
||||
|
||||
```js
|
||||
const schema = new ObjectSchema({
|
||||
date: {
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate(value) {
|
||||
Date.parse(value); // throws an error when invalid
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const object1 = { date: "5/5/2005" };
|
||||
const object2 = { date: "6/6/2006" };
|
||||
|
||||
const result = schema.merge(object1, object2);
|
||||
|
||||
console.log("date" in result); // false
|
||||
```
|
||||
|
||||
### Requiring Another Key Be Present
|
||||
|
||||
If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example:
|
||||
|
||||
```js
|
||||
const schema = new ObjectSchema();
|
||||
|
||||
const schema = new ObjectSchema({
|
||||
date: {
|
||||
merge() {
|
||||
return undefined;
|
||||
},
|
||||
validate(value) {
|
||||
Date.parse(value); // throws an error when invalid
|
||||
}
|
||||
},
|
||||
time: {
|
||||
requires: ["date"],
|
||||
merge(first, second) {
|
||||
return second;
|
||||
},
|
||||
validate(value) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// throws error: Key "time" requires keys "date"
|
||||
schema.validate({
|
||||
time: "13:45"
|
||||
});
|
||||
```
|
||||
|
||||
In this example, even though `date` is an optional key, it is required to be present whenever `time` is present.
|
||||
|
||||
## License
|
||||
|
||||
BSD 3-Clause
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@humanwhocodes/object-schema",
|
||||
"version": "2.0.3",
|
||||
"description": "An object schema merger/validator",
|
||||
"main": "src/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
],
|
||||
"directories": {
|
||||
"test": "tests"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "mocha tests/"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/humanwhocodes/object-schema.git"
|
||||
},
|
||||
"keywords": [
|
||||
"object",
|
||||
"validation",
|
||||
"schema",
|
||||
"merge"
|
||||
],
|
||||
"author": "Nicholas C. Zakas",
|
||||
"license": "BSD-3-Clause",
|
||||
"bugs": {
|
||||
"url": "https://github.com/humanwhocodes/object-schema/issues"
|
||||
},
|
||||
"homepage": "https://github.com/humanwhocodes/object-schema#readme",
|
||||
"devDependencies": {
|
||||
"chai": "^4.2.0",
|
||||
"eslint": "^5.13.0",
|
||||
"mocha": "^5.2.0"
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @filedescription Object Schema Package
|
||||
*/
|
||||
|
||||
exports.ObjectSchema = require("./object-schema").ObjectSchema;
|
||||
exports.MergeStrategy = require("./merge-strategy").MergeStrategy;
|
||||
exports.ValidationStrategy = require("./validation-strategy").ValidationStrategy;
|
||||
Generated
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* @filedescription Merge Strategy
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Class
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Container class for several different merge strategies.
|
||||
*/
|
||||
class MergeStrategy {
|
||||
|
||||
/**
|
||||
* Merges two keys by overwriting the first with the second.
|
||||
* @param {*} value1 The value from the first object key.
|
||||
* @param {*} value2 The value from the second object key.
|
||||
* @returns {*} The second value.
|
||||
*/
|
||||
static overwrite(value1, value2) {
|
||||
return value2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges two keys by replacing the first with the second only if the
|
||||
* second is defined.
|
||||
* @param {*} value1 The value from the first object key.
|
||||
* @param {*} value2 The value from the second object key.
|
||||
* @returns {*} The second value if it is defined.
|
||||
*/
|
||||
static replace(value1, value2) {
|
||||
if (typeof value2 !== "undefined") {
|
||||
return value2;
|
||||
}
|
||||
|
||||
return value1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges two properties by assigning properties from the second to the first.
|
||||
* @param {*} value1 The value from the first object key.
|
||||
* @param {*} value2 The value from the second object key.
|
||||
* @returns {*} A new object containing properties from both value1 and
|
||||
* value2.
|
||||
*/
|
||||
static assign(value1, value2) {
|
||||
return Object.assign({}, value1, value2);
|
||||
}
|
||||
}
|
||||
|
||||
exports.MergeStrategy = MergeStrategy;
|
||||
Generated
Vendored
+301
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* @filedescription Object Schema
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const { MergeStrategy } = require("./merge-strategy");
|
||||
const { ValidationStrategy } = require("./validation-strategy");
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Private
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const strategies = Symbol("strategies");
|
||||
const requiredKeys = Symbol("requiredKeys");
|
||||
|
||||
/**
|
||||
* Validates a schema strategy.
|
||||
* @param {string} name The name of the key this strategy is for.
|
||||
* @param {Object} strategy The strategy for the object key.
|
||||
* @param {boolean} [strategy.required=true] Whether the key is required.
|
||||
* @param {string[]} [strategy.requires] Other keys that are required when
|
||||
* this key is present.
|
||||
* @param {Function} strategy.merge A method to call when merging two objects
|
||||
* with the same key.
|
||||
* @param {Function} strategy.validate A method to call when validating an
|
||||
* object with the key.
|
||||
* @returns {void}
|
||||
* @throws {Error} When the strategy is missing a name.
|
||||
* @throws {Error} When the strategy is missing a merge() method.
|
||||
* @throws {Error} When the strategy is missing a validate() method.
|
||||
*/
|
||||
function validateDefinition(name, strategy) {
|
||||
|
||||
let hasSchema = false;
|
||||
if (strategy.schema) {
|
||||
if (typeof strategy.schema === "object") {
|
||||
hasSchema = true;
|
||||
} else {
|
||||
throw new TypeError("Schema must be an object.");
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof strategy.merge === "string") {
|
||||
if (!(strategy.merge in MergeStrategy)) {
|
||||
throw new TypeError(`Definition for key "${name}" missing valid merge strategy.`);
|
||||
}
|
||||
} else if (!hasSchema && typeof strategy.merge !== "function") {
|
||||
throw new TypeError(`Definition for key "${name}" must have a merge property.`);
|
||||
}
|
||||
|
||||
if (typeof strategy.validate === "string") {
|
||||
if (!(strategy.validate in ValidationStrategy)) {
|
||||
throw new TypeError(`Definition for key "${name}" missing valid validation strategy.`);
|
||||
}
|
||||
} else if (!hasSchema && typeof strategy.validate !== "function") {
|
||||
throw new TypeError(`Definition for key "${name}" must have a validate() method.`);
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Errors
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Error when an unexpected key is found.
|
||||
*/
|
||||
class UnexpectedKeyError extends Error {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} key The key that was unexpected.
|
||||
*/
|
||||
constructor(key) {
|
||||
super(`Unexpected key "${key}" found.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error when a required key is missing.
|
||||
*/
|
||||
class MissingKeyError extends Error {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} key The key that was missing.
|
||||
*/
|
||||
constructor(key) {
|
||||
super(`Missing required key "${key}".`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error when a key requires other keys that are missing.
|
||||
*/
|
||||
class MissingDependentKeysError extends Error {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} key The key that was unexpected.
|
||||
* @param {Array<string>} requiredKeys The keys that are required.
|
||||
*/
|
||||
constructor(key, requiredKeys) {
|
||||
super(`Key "${key}" requires keys "${requiredKeys.join("\", \"")}".`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper error for errors occuring during a merge or validate operation.
|
||||
*/
|
||||
class WrapperError extends Error {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {string} key The object key causing the error.
|
||||
* @param {Error} source The source error.
|
||||
*/
|
||||
constructor(key, source) {
|
||||
super(`Key "${key}": ${source.message}`, { cause: source });
|
||||
|
||||
// copy over custom properties that aren't represented
|
||||
for (const key of Object.keys(source)) {
|
||||
if (!(key in this)) {
|
||||
this[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Main
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Represents an object validation/merging schema.
|
||||
*/
|
||||
class ObjectSchema {
|
||||
|
||||
/**
|
||||
* Creates a new instance.
|
||||
*/
|
||||
constructor(definitions) {
|
||||
|
||||
if (!definitions) {
|
||||
throw new Error("Schema definitions missing.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Track all strategies in the schema by key.
|
||||
* @type {Map}
|
||||
* @property strategies
|
||||
*/
|
||||
this[strategies] = new Map();
|
||||
|
||||
/**
|
||||
* Separately track any keys that are required for faster validation.
|
||||
* @type {Map}
|
||||
* @property requiredKeys
|
||||
*/
|
||||
this[requiredKeys] = new Map();
|
||||
|
||||
// add in all strategies
|
||||
for (const key of Object.keys(definitions)) {
|
||||
validateDefinition(key, definitions[key]);
|
||||
|
||||
// normalize merge and validate methods if subschema is present
|
||||
if (typeof definitions[key].schema === "object") {
|
||||
const schema = new ObjectSchema(definitions[key].schema);
|
||||
definitions[key] = {
|
||||
...definitions[key],
|
||||
merge(first = {}, second = {}) {
|
||||
return schema.merge(first, second);
|
||||
},
|
||||
validate(value) {
|
||||
ValidationStrategy.object(value);
|
||||
schema.validate(value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// normalize the merge method in case there's a string
|
||||
if (typeof definitions[key].merge === "string") {
|
||||
definitions[key] = {
|
||||
...definitions[key],
|
||||
merge: MergeStrategy[definitions[key].merge]
|
||||
};
|
||||
};
|
||||
|
||||
// normalize the validate method in case there's a string
|
||||
if (typeof definitions[key].validate === "string") {
|
||||
definitions[key] = {
|
||||
...definitions[key],
|
||||
validate: ValidationStrategy[definitions[key].validate]
|
||||
};
|
||||
};
|
||||
|
||||
this[strategies].set(key, definitions[key]);
|
||||
|
||||
if (definitions[key].required) {
|
||||
this[requiredKeys].set(key, definitions[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a strategy has been registered for the given object key.
|
||||
* @param {string} key The object key to find a strategy for.
|
||||
* @returns {boolean} True if the key has a strategy registered, false if not.
|
||||
*/
|
||||
hasKey(key) {
|
||||
return this[strategies].has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges objects together to create a new object comprised of the keys
|
||||
* of the all objects. Keys are merged based on the each key's merge
|
||||
* strategy.
|
||||
* @param {...Object} objects The objects to merge.
|
||||
* @returns {Object} A new object with a mix of all objects' keys.
|
||||
* @throws {Error} If any object is invalid.
|
||||
*/
|
||||
merge(...objects) {
|
||||
|
||||
// double check arguments
|
||||
if (objects.length < 2) {
|
||||
throw new TypeError("merge() requires at least two arguments.");
|
||||
}
|
||||
|
||||
if (objects.some(object => (object == null || typeof object !== "object"))) {
|
||||
throw new TypeError("All arguments must be objects.");
|
||||
}
|
||||
|
||||
return objects.reduce((result, object) => {
|
||||
|
||||
this.validate(object);
|
||||
|
||||
for (const [key, strategy] of this[strategies]) {
|
||||
try {
|
||||
if (key in result || key in object) {
|
||||
const value = strategy.merge.call(this, result[key], object[key]);
|
||||
if (value !== undefined) {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
} catch (ex) {
|
||||
throw new WrapperError(key, ex);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an object's keys based on the validate strategy for each key.
|
||||
* @param {Object} object The object to validate.
|
||||
* @returns {void}
|
||||
* @throws {Error} When the object is invalid.
|
||||
*/
|
||||
validate(object) {
|
||||
|
||||
// check existing keys first
|
||||
for (const key of Object.keys(object)) {
|
||||
|
||||
// check to see if the key is defined
|
||||
if (!this.hasKey(key)) {
|
||||
throw new UnexpectedKeyError(key);
|
||||
}
|
||||
|
||||
// validate existing keys
|
||||
const strategy = this[strategies].get(key);
|
||||
|
||||
// first check to see if any other keys are required
|
||||
if (Array.isArray(strategy.requires)) {
|
||||
if (!strategy.requires.every(otherKey => otherKey in object)) {
|
||||
throw new MissingDependentKeysError(key, strategy.requires);
|
||||
}
|
||||
}
|
||||
|
||||
// now apply remaining validation strategy
|
||||
try {
|
||||
strategy.validate.call(strategy, object[key]);
|
||||
} catch (ex) {
|
||||
throw new WrapperError(key, ex);
|
||||
}
|
||||
}
|
||||
|
||||
// ensure required keys aren't missing
|
||||
for (const [key] of this[requiredKeys]) {
|
||||
if (!(key in object)) {
|
||||
throw new MissingKeyError(key);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
exports.ObjectSchema = ObjectSchema;
|
||||
Generated
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* @filedescription Validation Strategy
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Class
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Container class for several different validation strategies.
|
||||
*/
|
||||
class ValidationStrategy {
|
||||
|
||||
/**
|
||||
* Validates that a value is an array.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static array(value) {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError("Expected an array.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a boolean.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static boolean(value) {
|
||||
if (typeof value !== "boolean") {
|
||||
throw new TypeError("Expected a Boolean.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a number.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static number(value) {
|
||||
if (typeof value !== "number") {
|
||||
throw new TypeError("Expected a number.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a object.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static object(value) {
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new TypeError("Expected an object.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a object or null.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static "object?"(value) {
|
||||
if (typeof value !== "object") {
|
||||
throw new TypeError("Expected an object or null.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a string.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static string(value) {
|
||||
if (typeof value !== "string") {
|
||||
throw new TypeError("Expected a string.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a value is a non-empty string.
|
||||
* @param {*} value The value to validate.
|
||||
* @returns {void}
|
||||
* @throws {TypeError} If the value is invalid.
|
||||
*/
|
||||
static "string!"(value) {
|
||||
if (typeof value !== "string" || value.length === 0) {
|
||||
throw new TypeError("Expected a non-empty string.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
exports.ValidationStrategy = ValidationStrategy;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# `@jest/schemas`
|
||||
|
||||
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
import {Static} from '@sinclair/typebox';
|
||||
import {TBoolean} from '@sinclair/typebox';
|
||||
import {TNull} from '@sinclair/typebox';
|
||||
import {TNumber} from '@sinclair/typebox';
|
||||
import {TObject} from '@sinclair/typebox';
|
||||
import {TReadonlyOptional} from '@sinclair/typebox';
|
||||
import {TString} from '@sinclair/typebox';
|
||||
|
||||
declare const RawSnapshotFormat: TObject<{
|
||||
callToJSON: TReadonlyOptional<TBoolean>;
|
||||
compareKeys: TReadonlyOptional<TNull>;
|
||||
escapeRegex: TReadonlyOptional<TBoolean>;
|
||||
escapeString: TReadonlyOptional<TBoolean>;
|
||||
highlight: TReadonlyOptional<TBoolean>;
|
||||
indent: TReadonlyOptional<TNumber>;
|
||||
maxDepth: TReadonlyOptional<TNumber>;
|
||||
maxWidth: TReadonlyOptional<TNumber>;
|
||||
min: TReadonlyOptional<TBoolean>;
|
||||
printBasicPrototype: TReadonlyOptional<TBoolean>;
|
||||
printFunctionName: TReadonlyOptional<TBoolean>;
|
||||
theme: TReadonlyOptional<
|
||||
TObject<{
|
||||
comment: TReadonlyOptional<TString<string>>;
|
||||
content: TReadonlyOptional<TString<string>>;
|
||||
prop: TReadonlyOptional<TString<string>>;
|
||||
tag: TReadonlyOptional<TString<string>>;
|
||||
value: TReadonlyOptional<TString<string>>;
|
||||
}>
|
||||
>;
|
||||
}>;
|
||||
|
||||
export declare const SnapshotFormat: TObject<{
|
||||
callToJSON: TReadonlyOptional<TBoolean>;
|
||||
compareKeys: TReadonlyOptional<TNull>;
|
||||
escapeRegex: TReadonlyOptional<TBoolean>;
|
||||
escapeString: TReadonlyOptional<TBoolean>;
|
||||
highlight: TReadonlyOptional<TBoolean>;
|
||||
indent: TReadonlyOptional<TNumber>;
|
||||
maxDepth: TReadonlyOptional<TNumber>;
|
||||
maxWidth: TReadonlyOptional<TNumber>;
|
||||
min: TReadonlyOptional<TBoolean>;
|
||||
printBasicPrototype: TReadonlyOptional<TBoolean>;
|
||||
printFunctionName: TReadonlyOptional<TBoolean>;
|
||||
theme: TReadonlyOptional<
|
||||
TObject<{
|
||||
comment: TReadonlyOptional<TString<string>>;
|
||||
content: TReadonlyOptional<TString<string>>;
|
||||
prop: TReadonlyOptional<TString<string>>;
|
||||
tag: TReadonlyOptional<TString<string>>;
|
||||
value: TReadonlyOptional<TString<string>>;
|
||||
}>
|
||||
>;
|
||||
}>;
|
||||
|
||||
export declare type SnapshotFormat = Static<typeof RawSnapshotFormat>;
|
||||
|
||||
export {};
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', {
|
||||
value: true
|
||||
});
|
||||
exports.SnapshotFormat = void 0;
|
||||
function _typebox() {
|
||||
const data = require('@sinclair/typebox');
|
||||
_typebox = function () {
|
||||
return data;
|
||||
};
|
||||
return data;
|
||||
}
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
const RawSnapshotFormat = _typebox().Type.Partial(
|
||||
_typebox().Type.Object({
|
||||
callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()),
|
||||
escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
indent: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
maxDepth: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
maxWidth: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
min: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
theme: _typebox().Type.Readonly(
|
||||
_typebox().Type.Partial(
|
||||
_typebox().Type.Object({
|
||||
comment: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
content: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
prop: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
tag: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
value: _typebox().Type.Readonly(_typebox().Type.String())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
);
|
||||
const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat);
|
||||
exports.SnapshotFormat = SnapshotFormat;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@jest/schemas",
|
||||
"version": "29.6.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/jestjs/jest.git",
|
||||
"directory": "packages/jest-schemas"
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "./build/index.js",
|
||||
"types": "./build/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./build/index.d.ts",
|
||||
"default": "./build/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.27.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
# @jridgewell/sourcemap-codec
|
||||
|
||||
Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit).
|
||||
|
||||
|
||||
## Why?
|
||||
|
||||
Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap.
|
||||
|
||||
This package makes the process slightly easier.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @jridgewell/sourcemap-codec
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { encode, decode } from '@jridgewell/sourcemap-codec';
|
||||
|
||||
var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||
|
||||
assert.deepEqual( decoded, [
|
||||
// the first line (of the generated code) has no mappings,
|
||||
// as shown by the starting semi-colon (which separates lines)
|
||||
[],
|
||||
|
||||
// the second line contains four (comma-separated) segments
|
||||
[
|
||||
// segments are encoded as you'd expect:
|
||||
// [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ]
|
||||
|
||||
// i.e. the first segment begins at column 2, and maps back to the second column
|
||||
// of the second line (both zero-based) of the 0th source, and uses the 0th
|
||||
// name in the `map.names` array
|
||||
[ 2, 0, 2, 2, 0 ],
|
||||
|
||||
// the remaining segments are 4-length rather than 5-length,
|
||||
// because they don't map a name
|
||||
[ 4, 0, 2, 4 ],
|
||||
[ 6, 0, 2, 5 ],
|
||||
[ 7, 0, 2, 7 ]
|
||||
],
|
||||
|
||||
// the final line contains two segments
|
||||
[
|
||||
[ 2, 1, 10, 19 ],
|
||||
[ 12, 1, 11, 20 ]
|
||||
]
|
||||
]);
|
||||
|
||||
var encoded = encode( decoded );
|
||||
assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
```
|
||||
node v20.10.0
|
||||
|
||||
amp.js.map - 45120 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 5815135 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 5868160 bytes
|
||||
sourcemap-codec 5492584 bytes
|
||||
source-map-0.6.1 13569984 bytes
|
||||
source-map-0.8.0 6390584 bytes
|
||||
chrome dev tools 8011136 bytes
|
||||
Smallest memory usage is sourcemap-codec
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 492 ops/sec ±1.22% (90 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled)
|
||||
decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled)
|
||||
decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled)
|
||||
decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled)
|
||||
chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 444248 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 623024 bytes
|
||||
sourcemap-codec 8696280 bytes
|
||||
source-map-0.6.1 8745176 bytes
|
||||
source-map-0.8.0 8736624 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 796 ops/sec ±0.11% (97 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled)
|
||||
encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled)
|
||||
encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled)
|
||||
encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled)
|
||||
Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
babel.min.js.map - 347793 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 35424960 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 35424696 bytes
|
||||
sourcemap-codec 36033464 bytes
|
||||
source-map-0.6.1 62253704 bytes
|
||||
source-map-0.8.0 43843920 bytes
|
||||
chrome dev tools 45111400 bytes
|
||||
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled)
|
||||
decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled)
|
||||
decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled)
|
||||
decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled)
|
||||
chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled)
|
||||
Fastest is decode: source-map-0.8.0
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 2606016 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 2626440 bytes
|
||||
sourcemap-codec 21152576 bytes
|
||||
source-map-0.6.1 25023928 bytes
|
||||
source-map-0.8.0 25256448 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 127 ops/sec ±0.18% (83 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled)
|
||||
encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled)
|
||||
encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled)
|
||||
encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
preact.js.map - 1992 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 261696 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 244296 bytes
|
||||
sourcemap-codec 302816 bytes
|
||||
source-map-0.6.1 939176 bytes
|
||||
source-map-0.8.0 336 bytes
|
||||
chrome dev tools 587368 bytes
|
||||
Smallest memory usage is source-map-0.8.0
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled)
|
||||
decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled)
|
||||
decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled)
|
||||
decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled)
|
||||
chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 262944 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 25544 bytes
|
||||
sourcemap-codec 323048 bytes
|
||||
source-map-0.6.1 507808 bytes
|
||||
source-map-0.8.0 507480 bytes
|
||||
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled)
|
||||
encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled)
|
||||
encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled)
|
||||
encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
react.js.map - 5726 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 678816 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 678816 bytes
|
||||
sourcemap-codec 816400 bytes
|
||||
source-map-0.6.1 2288864 bytes
|
||||
source-map-0.8.0 721360 bytes
|
||||
chrome dev tools 1012512 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled)
|
||||
decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled)
|
||||
decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled)
|
||||
decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled)
|
||||
chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 140960 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 159808 bytes
|
||||
sourcemap-codec 969304 bytes
|
||||
source-map-0.6.1 930520 bytes
|
||||
source-map-0.8.0 930248 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled)
|
||||
encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled)
|
||||
encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled)
|
||||
encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled)
|
||||
Fastest is encode: local code
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
vscode.map - 2141001 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 198955264 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 199175352 bytes
|
||||
sourcemap-codec 199102688 bytes
|
||||
source-map-0.6.1 386323432 bytes
|
||||
source-map-0.8.0 244116432 bytes
|
||||
chrome dev tools 293734280 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled)
|
||||
decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled)
|
||||
decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled)
|
||||
decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled)
|
||||
chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled)
|
||||
Fastest is decode: source-map-0.8.0
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 13509880 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 13537648 bytes
|
||||
sourcemap-codec 32540104 bytes
|
||||
source-map-0.6.1 127531040 bytes
|
||||
source-map-0.8.0 127535312 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled)
|
||||
encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled)
|
||||
encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled)
|
||||
encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
MIT
|
||||
Generated
Vendored
+423
@@ -0,0 +1,423 @@
|
||||
// src/vlq.ts
|
||||
var comma = ",".charCodeAt(0);
|
||||
var semicolon = ";".charCodeAt(0);
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decodeInteger(reader, relative) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -2147483648 | -value;
|
||||
}
|
||||
return relative + value;
|
||||
}
|
||||
function encodeInteger(builder, num, relative) {
|
||||
let delta = num - relative;
|
||||
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 31;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 32;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
return num;
|
||||
}
|
||||
function hasMoreVlq(reader, max) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
|
||||
// src/strings.ts
|
||||
var bufLength = 1024 * 16;
|
||||
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||
decode(buf) {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
}
|
||||
} : {
|
||||
decode(buf) {
|
||||
let out = "";
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
var StringWriter = class {
|
||||
constructor() {
|
||||
this.pos = 0;
|
||||
this.out = "";
|
||||
this.buffer = new Uint8Array(bufLength);
|
||||
}
|
||||
write(v) {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
flush() {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
};
|
||||
var StringReader = class {
|
||||
constructor(buffer) {
|
||||
this.pos = 0;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
next() {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
peek() {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
indexOf(char) {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
};
|
||||
|
||||
// src/scopes.ts
|
||||
var EMPTY = [];
|
||||
function decodeOriginalScopes(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes = [];
|
||||
const stack = [];
|
||||
let line = 0;
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop();
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 1;
|
||||
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||
let vars = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
function encodeOriginalScopes(scopes) {
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
if (index > 0) writer.write(comma);
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
const fields = scope.length === 6 ? 1 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
return index;
|
||||
}
|
||||
function decodeGeneratedRanges(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges = [];
|
||||
const stack = [];
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
let genColumn = 0;
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop();
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 1;
|
||||
const hasCallsite = fields & 2;
|
||||
const hasScope = fields & 4;
|
||||
let callsite = null;
|
||||
let bindings = EMPTY;
|
||||
let range;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||
);
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0];
|
||||
}
|
||||
range.isScope = !!hasScope;
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||
);
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges;
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
return ranges;
|
||||
}
|
||||
function encodeGeneratedRanges(ranges) {
|
||||
if (ranges.length === 0) return "";
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings
|
||||
} = range;
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
return index;
|
||||
}
|
||||
function catchupLine(writer, lastLine, line) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
function decode(mappings) {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
while (reader.pos < semi) {
|
||||
let seg;
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
return decoded;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
function sortComparator(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
function encode(decoded) {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
let genColumn = 0;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
export {
|
||||
decode,
|
||||
decodeGeneratedRanges,
|
||||
decodeOriginalScopes,
|
||||
encode,
|
||||
encodeGeneratedRanges,
|
||||
encodeOriginalScopes
|
||||
};
|
||||
//# sourceMappingURL=sourcemap-codec.mjs.map
|
||||
Generated
Vendored
+6
File diff suppressed because one or more lines are too long
Generated
Vendored
+464
@@ -0,0 +1,464 @@
|
||||
(function (global, factory) {
|
||||
if (typeof exports === 'object' && typeof module !== 'undefined') {
|
||||
factory(module);
|
||||
module.exports = def(module);
|
||||
} else if (typeof define === 'function' && define.amd) {
|
||||
define(['module'], function(mod) {
|
||||
factory.apply(this, arguments);
|
||||
mod.exports = def(mod);
|
||||
});
|
||||
} else {
|
||||
const mod = { exports: {} };
|
||||
factory(mod);
|
||||
global = typeof globalThis !== 'undefined' ? globalThis : global || self;
|
||||
global.sourcemapCodec = def(mod);
|
||||
}
|
||||
function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; }
|
||||
})(this, (function (module) {
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
var sourcemap_codec_exports = {};
|
||||
__export(sourcemap_codec_exports, {
|
||||
decode: () => decode,
|
||||
decodeGeneratedRanges: () => decodeGeneratedRanges,
|
||||
decodeOriginalScopes: () => decodeOriginalScopes,
|
||||
encode: () => encode,
|
||||
encodeGeneratedRanges: () => encodeGeneratedRanges,
|
||||
encodeOriginalScopes: () => encodeOriginalScopes
|
||||
});
|
||||
module.exports = __toCommonJS(sourcemap_codec_exports);
|
||||
|
||||
// src/vlq.ts
|
||||
var comma = ",".charCodeAt(0);
|
||||
var semicolon = ";".charCodeAt(0);
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decodeInteger(reader, relative) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -2147483648 | -value;
|
||||
}
|
||||
return relative + value;
|
||||
}
|
||||
function encodeInteger(builder, num, relative) {
|
||||
let delta = num - relative;
|
||||
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 31;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 32;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
return num;
|
||||
}
|
||||
function hasMoreVlq(reader, max) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
|
||||
// src/strings.ts
|
||||
var bufLength = 1024 * 16;
|
||||
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||
decode(buf) {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
}
|
||||
} : {
|
||||
decode(buf) {
|
||||
let out = "";
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
var StringWriter = class {
|
||||
constructor() {
|
||||
this.pos = 0;
|
||||
this.out = "";
|
||||
this.buffer = new Uint8Array(bufLength);
|
||||
}
|
||||
write(v) {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
flush() {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
};
|
||||
var StringReader = class {
|
||||
constructor(buffer) {
|
||||
this.pos = 0;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
next() {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
peek() {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
indexOf(char) {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
};
|
||||
|
||||
// src/scopes.ts
|
||||
var EMPTY = [];
|
||||
function decodeOriginalScopes(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes = [];
|
||||
const stack = [];
|
||||
let line = 0;
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop();
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 1;
|
||||
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||
let vars = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
function encodeOriginalScopes(scopes) {
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
if (index > 0) writer.write(comma);
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
const fields = scope.length === 6 ? 1 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
return index;
|
||||
}
|
||||
function decodeGeneratedRanges(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges = [];
|
||||
const stack = [];
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
let genColumn = 0;
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop();
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 1;
|
||||
const hasCallsite = fields & 2;
|
||||
const hasScope = fields & 4;
|
||||
let callsite = null;
|
||||
let bindings = EMPTY;
|
||||
let range;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||
);
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0];
|
||||
}
|
||||
range.isScope = !!hasScope;
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||
);
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges;
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
return ranges;
|
||||
}
|
||||
function encodeGeneratedRanges(ranges) {
|
||||
if (ranges.length === 0) return "";
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings
|
||||
} = range;
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
return index;
|
||||
}
|
||||
function catchupLine(writer, lastLine, line) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
function decode(mappings) {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
while (reader.pos < semi) {
|
||||
let seg;
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
return decoded;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
function sortComparator(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
function encode(decoded) {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
let genColumn = 0;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
}));
|
||||
//# sourceMappingURL=sourcemap-codec.umd.js.map
|
||||
Generated
Vendored
+6
File diff suppressed because one or more lines are too long
+63
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@jridgewell/sourcemap-codec",
|
||||
"version": "1.5.5",
|
||||
"description": "Encode/decode sourcemap mappings",
|
||||
"keywords": [
|
||||
"sourcemap",
|
||||
"vlq"
|
||||
],
|
||||
"main": "dist/sourcemap-codec.umd.js",
|
||||
"module": "dist/sourcemap-codec.mjs",
|
||||
"types": "types/sourcemap-codec.d.cts",
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"types"
|
||||
],
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": {
|
||||
"types": "./types/sourcemap-codec.d.mts",
|
||||
"default": "./dist/sourcemap-codec.mjs"
|
||||
},
|
||||
"default": {
|
||||
"types": "./types/sourcemap-codec.d.cts",
|
||||
"default": "./dist/sourcemap-codec.umd.js"
|
||||
}
|
||||
},
|
||||
"./dist/sourcemap-codec.umd.js"
|
||||
],
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"benchmark": "run-s build:code benchmark:*",
|
||||
"benchmark:install": "cd benchmark && npm install",
|
||||
"benchmark:only": "node --expose-gc benchmark/index.js",
|
||||
"build": "run-s -n build:code build:types",
|
||||
"build:code": "node ../../esbuild.mjs sourcemap-codec.ts",
|
||||
"build:types": "run-s build:types:force build:types:emit build:types:mts",
|
||||
"build:types:force": "rimraf tsconfig.build.tsbuildinfo",
|
||||
"build:types:emit": "tsc --project tsconfig.build.json",
|
||||
"build:types:mts": "node ../../mts-types.mjs",
|
||||
"clean": "run-s -n clean:code clean:types",
|
||||
"clean:code": "tsc --build --clean tsconfig.build.json",
|
||||
"clean:types": "rimraf dist types",
|
||||
"test": "run-s -n test:types test:only test:format",
|
||||
"test:format": "prettier --check '{src,test}/**/*.ts'",
|
||||
"test:only": "mocha",
|
||||
"test:types": "eslint '{src,test}/**/*.ts'",
|
||||
"lint": "run-s -n lint:types lint:format",
|
||||
"lint:format": "npm run test:format -- --write",
|
||||
"lint:types": "npm run test:types -- --fix",
|
||||
"prepublishOnly": "npm run-s -n build test"
|
||||
},
|
||||
"homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/jridgewell/sourcemaps.git",
|
||||
"directory": "packages/sourcemap-codec"
|
||||
},
|
||||
"author": "Justin Ridgewell <justin@ridgewell.name>",
|
||||
"license": "MIT"
|
||||
}
|
||||
+345
@@ -0,0 +1,345 @@
|
||||
import { StringReader, StringWriter } from './strings';
|
||||
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||
|
||||
const EMPTY: any[] = [];
|
||||
|
||||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
|
||||
export type OriginalScope = Mix<
|
||||
[Line, Column, Line, Column, Kind],
|
||||
[Line, Column, Line, Column, Kind, Name],
|
||||
{ vars: Var[] }
|
||||
>;
|
||||
|
||||
export type GeneratedRange = Mix<
|
||||
[Line, Column, Line, Column],
|
||||
[Line, Column, Line, Column, SourcesIndex, ScopesIndex],
|
||||
{
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}
|
||||
>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
|
||||
export function decodeOriginalScopes(input: string): OriginalScope[] {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes: OriginalScope[] = [];
|
||||
const stack: OriginalScope[] = [];
|
||||
let line = 0;
|
||||
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop()!;
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 0b0001;
|
||||
|
||||
const scope: OriginalScope = (
|
||||
hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]
|
||||
) as OriginalScope;
|
||||
|
||||
let vars: Var[] = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
|
||||
return scopes;
|
||||
}
|
||||
|
||||
export function encodeOriginalScopes(scopes: OriginalScope[]): string {
|
||||
const writer = new StringWriter();
|
||||
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
|
||||
function _encodeOriginalScopes(
|
||||
scopes: OriginalScope[],
|
||||
index: number,
|
||||
writer: StringWriter,
|
||||
state: [
|
||||
number, // GenColumn
|
||||
],
|
||||
): number {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
|
||||
if (index > 0) writer.write(comma);
|
||||
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
|
||||
const fields = scope.length === 6 ? 0b0001 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
export function decodeGeneratedRanges(input: string): GeneratedRange[] {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges: GeneratedRange[] = [];
|
||||
const stack: GeneratedRange[] = [];
|
||||
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
|
||||
do {
|
||||
const semi = reader.indexOf(';');
|
||||
let genColumn = 0;
|
||||
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop()!;
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 0b0001;
|
||||
const hasCallsite = fields & 0b0010;
|
||||
const hasScope = fields & 0b0100;
|
||||
|
||||
let callsite: CallSite | null = null;
|
||||
let bindings: Binding[] = EMPTY;
|
||||
let range: GeneratedRange;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,
|
||||
);
|
||||
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0] as GeneratedRange;
|
||||
}
|
||||
|
||||
range.isScope = !!hasScope;
|
||||
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0,
|
||||
);
|
||||
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges: BindingExpressionRange[];
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
export function encodeGeneratedRanges(ranges: GeneratedRange[]): string {
|
||||
if (ranges.length === 0) return '';
|
||||
|
||||
const writer = new StringWriter();
|
||||
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
|
||||
function _encodeGeneratedRanges(
|
||||
ranges: GeneratedRange[],
|
||||
index: number,
|
||||
writer: StringWriter,
|
||||
state: [
|
||||
number, // GenLine
|
||||
number, // GenColumn
|
||||
number, // DefSourcesIndex
|
||||
number, // DefScopesIndex
|
||||
number, // CallSourcesIndex
|
||||
number, // CallLine
|
||||
number, // CallColumn
|
||||
],
|
||||
): number {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings,
|
||||
} = range;
|
||||
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
|
||||
const fields =
|
||||
(range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0]!, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
function catchupLine(writer: StringWriter, lastLine: number, line: number) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
Generated
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||
import { StringWriter, StringReader } from './strings';
|
||||
|
||||
export {
|
||||
decodeOriginalScopes,
|
||||
encodeOriginalScopes,
|
||||
decodeGeneratedRanges,
|
||||
encodeGeneratedRanges,
|
||||
} from './scopes';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';
|
||||
|
||||
export type SourceMapSegment =
|
||||
| [number]
|
||||
| [number, number, number, number]
|
||||
| [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
|
||||
export function decode(mappings: string): SourceMapMappings {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded: SourceMapMappings = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
|
||||
do {
|
||||
const semi = reader.indexOf(';');
|
||||
const line: SourceMapLine = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
|
||||
while (reader.pos < semi) {
|
||||
let seg: SourceMapSegment;
|
||||
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
function sort(line: SourceMapSegment[]) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
|
||||
function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
|
||||
export function encode(decoded: SourceMapMappings): string;
|
||||
export function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
export function encode(decoded: Readonly<SourceMapMappings>): string {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
|
||||
let genColumn = 0;
|
||||
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
const bufLength = 1024 * 16;
|
||||
|
||||
// Provide a fallback for older environments.
|
||||
const td =
|
||||
typeof TextDecoder !== 'undefined'
|
||||
? /* #__PURE__ */ new TextDecoder()
|
||||
: typeof Buffer !== 'undefined'
|
||||
? {
|
||||
decode(buf: Uint8Array): string {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
},
|
||||
}
|
||||
: {
|
||||
decode(buf: Uint8Array): string {
|
||||
let out = '';
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
|
||||
export class StringWriter {
|
||||
pos = 0;
|
||||
private out = '';
|
||||
private buffer = new Uint8Array(bufLength);
|
||||
|
||||
write(v: number): void {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
flush(): string {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
}
|
||||
|
||||
export class StringReader {
|
||||
pos = 0;
|
||||
declare private buffer: string;
|
||||
|
||||
constructor(buffer: string) {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
next(): number {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
|
||||
peek(): number {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
|
||||
indexOf(char: string): number {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import type { StringReader, StringWriter } from './strings';
|
||||
|
||||
export const comma = ','.charCodeAt(0);
|
||||
export const semicolon = ';'.charCodeAt(0);
|
||||
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
const intToChar = new Uint8Array(64); // 64 possible chars.
|
||||
const charToInt = new Uint8Array(128); // z is 122 in ASCII
|
||||
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
|
||||
export function decodeInteger(reader: StringReader, relative: number): number {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
|
||||
if (shouldNegate) {
|
||||
value = -0x80000000 | -value;
|
||||
}
|
||||
|
||||
return relative + value;
|
||||
}
|
||||
|
||||
export function encodeInteger(builder: StringWriter, num: number, relative: number): number {
|
||||
let delta = num - relative;
|
||||
|
||||
delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 0b011111;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 0b100000;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
|
||||
return num;
|
||||
}
|
||||
|
||||
export function hasMoreVlq(reader: StringReader, max: number) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
export type OriginalScope = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind,
|
||||
Name
|
||||
], {
|
||||
vars: Var[];
|
||||
}>;
|
||||
export type GeneratedRange = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
SourcesIndex,
|
||||
ScopesIndex
|
||||
], {
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
export declare function decodeOriginalScopes(input: string): OriginalScope[];
|
||||
export declare function encodeOriginalScopes(scopes: OriginalScope[]): string;
|
||||
export declare function decodeGeneratedRanges(input: string): GeneratedRange[];
|
||||
export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string;
|
||||
export {};
|
||||
//# sourceMappingURL=scopes.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"}
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
export type OriginalScope = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind,
|
||||
Name
|
||||
], {
|
||||
vars: Var[];
|
||||
}>;
|
||||
export type GeneratedRange = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
SourcesIndex,
|
||||
ScopesIndex
|
||||
], {
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
export declare function decodeOriginalScopes(input: string): OriginalScope[];
|
||||
export declare function encodeOriginalScopes(scopes: OriginalScope[]): string;
|
||||
export declare function decodeGeneratedRanges(input: string): GeneratedRange[];
|
||||
export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string;
|
||||
export {};
|
||||
//# sourceMappingURL=scopes.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"}
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts';
|
||||
export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
export declare function decode(mappings: string): SourceMapMappings;
|
||||
export declare function encode(decoded: SourceMapMappings): string;
|
||||
export declare function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
//# sourceMappingURL=sourcemap-codec.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"}
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts';
|
||||
export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
export declare function decode(mappings: string): SourceMapMappings;
|
||||
export declare function encode(decoded: SourceMapMappings): string;
|
||||
export declare function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
//# sourceMappingURL=sourcemap-codec.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"}
|
||||
Generated
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
export declare class StringWriter {
|
||||
pos: number;
|
||||
private out;
|
||||
private buffer;
|
||||
write(v: number): void;
|
||||
flush(): string;
|
||||
}
|
||||
export declare class StringReader {
|
||||
pos: number;
|
||||
private buffer;
|
||||
constructor(buffer: string);
|
||||
next(): number;
|
||||
peek(): number;
|
||||
indexOf(char: string): number;
|
||||
}
|
||||
//# sourceMappingURL=strings.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"}
|
||||
Generated
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
export declare class StringWriter {
|
||||
pos: number;
|
||||
private out;
|
||||
private buffer;
|
||||
write(v: number): void;
|
||||
flush(): string;
|
||||
}
|
||||
export declare class StringReader {
|
||||
pos: number;
|
||||
private buffer;
|
||||
constructor(buffer: string);
|
||||
next(): number;
|
||||
peek(): number;
|
||||
indexOf(char: string): number;
|
||||
}
|
||||
//# sourceMappingURL=strings.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { StringReader, StringWriter } from './strings.cts';
|
||||
export declare const comma: number;
|
||||
export declare const semicolon: number;
|
||||
export declare function decodeInteger(reader: StringReader, relative: number): number;
|
||||
export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number;
|
||||
export declare function hasMoreVlq(reader: StringReader, max: number): boolean;
|
||||
//# sourceMappingURL=vlq.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { StringReader, StringWriter } from './strings.mts';
|
||||
export declare const comma: number;
|
||||
export declare const semicolon: number;
|
||||
export declare function decodeInteger(reader: StringReader, relative: number): number;
|
||||
export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number;
|
||||
export declare function hasMoreVlq(reader: StringReader, max: number): boolean;
|
||||
//# sourceMappingURL=vlq.d.ts.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Denis Malinochkin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
# @nodelib/fs.scandir
|
||||
|
||||
> List files and directories inside the specified directory.
|
||||
|
||||
## :bulb: Highlights
|
||||
|
||||
The package is aimed at obtaining information about entries in the directory.
|
||||
|
||||
* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional).
|
||||
* :gear: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type. See [`old` and `modern` mode](#old-and-modern-mode).
|
||||
* :link: Can safely work with broken symbolic links.
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
npm install @nodelib/fs.scandir
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import * as fsScandir from '@nodelib/fs.scandir';
|
||||
|
||||
fsScandir.scandir('path', (error, stats) => { /* … */ });
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### .scandir(path, [optionsOrSettings], callback)
|
||||
|
||||
Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path with standard callback-style.
|
||||
|
||||
```ts
|
||||
fsScandir.scandir('path', (error, entries) => { /* … */ });
|
||||
fsScandir.scandir('path', {}, (error, entries) => { /* … */ });
|
||||
fsScandir.scandir('path', new fsScandir.Settings(), (error, entries) => { /* … */ });
|
||||
```
|
||||
|
||||
### .scandirSync(path, [optionsOrSettings])
|
||||
|
||||
Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path.
|
||||
|
||||
```ts
|
||||
const entries = fsScandir.scandirSync('path');
|
||||
const entries = fsScandir.scandirSync('path', {});
|
||||
const entries = fsScandir.scandirSync(('path', new fsScandir.Settings());
|
||||
```
|
||||
|
||||
#### path
|
||||
|
||||
* Required: `true`
|
||||
* Type: `string | Buffer | URL`
|
||||
|
||||
A path to a file. If a URL is provided, it must use the `file:` protocol.
|
||||
|
||||
#### optionsOrSettings
|
||||
|
||||
* Required: `false`
|
||||
* Type: `Options | Settings`
|
||||
* Default: An instance of `Settings` class
|
||||
|
||||
An [`Options`](#options) object or an instance of [`Settings`](#settingsoptions) class.
|
||||
|
||||
> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class.
|
||||
|
||||
### Settings([options])
|
||||
|
||||
A class of full settings of the package.
|
||||
|
||||
```ts
|
||||
const settings = new fsScandir.Settings({ followSymbolicLinks: false });
|
||||
|
||||
const entries = fsScandir.scandirSync('path', settings);
|
||||
```
|
||||
|
||||
## Entry
|
||||
|
||||
* `name` — The name of the entry (`unknown.txt`).
|
||||
* `path` — The path of the entry relative to call directory (`root/unknown.txt`).
|
||||
* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. On Node.js below 10.10 will be emulated by [`DirentFromStats`](./src/utils/fs.ts) class.
|
||||
* `stats` (optional) — An instance of `fs.Stats` class.
|
||||
|
||||
For example, the `scandir` call for `tools` directory with one directory inside:
|
||||
|
||||
```ts
|
||||
{
|
||||
dirent: Dirent { name: 'typedoc', /* … */ },
|
||||
name: 'typedoc',
|
||||
path: 'tools/typedoc'
|
||||
}
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
### stats
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `false`
|
||||
|
||||
Adds an instance of `fs.Stats` class to the [`Entry`](#entry).
|
||||
|
||||
> :book: Always use `fs.readdir` without the `withFileTypes` option. ??TODO??
|
||||
|
||||
### followSymbolicLinks
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `false`
|
||||
|
||||
Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`.
|
||||
|
||||
### `throwErrorOnBrokenSymbolicLink`
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `true`
|
||||
|
||||
Throw an error when symbolic link is broken if `true` or safely use `lstat` call if `false`.
|
||||
|
||||
### `pathSegmentSeparator`
|
||||
|
||||
* Type: `string`
|
||||
* Default: `path.sep`
|
||||
|
||||
By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead.
|
||||
|
||||
### `fs`
|
||||
|
||||
* Type: [`FileSystemAdapter`](./src/adapters/fs.ts)
|
||||
* Default: A default FS methods
|
||||
|
||||
By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own.
|
||||
|
||||
```ts
|
||||
interface FileSystemAdapter {
|
||||
lstat?: typeof fs.lstat;
|
||||
stat?: typeof fs.stat;
|
||||
lstatSync?: typeof fs.lstatSync;
|
||||
statSync?: typeof fs.statSync;
|
||||
readdir?: typeof fs.readdir;
|
||||
readdirSync?: typeof fs.readdirSync;
|
||||
}
|
||||
|
||||
const settings = new fsScandir.Settings({
|
||||
fs: { lstat: fakeLstat }
|
||||
});
|
||||
```
|
||||
|
||||
## `old` and `modern` mode
|
||||
|
||||
This package has two modes that are used depending on the environment and parameters of use.
|
||||
|
||||
### old
|
||||
|
||||
* Node.js below `10.10` or when the `stats` option is enabled
|
||||
|
||||
When working in the old mode, the directory is read first (`fs.readdir`), then the type of entries is determined (`fs.lstat` and/or `fs.stat` for symbolic links).
|
||||
|
||||
### modern
|
||||
|
||||
* Node.js 10.10+ and the `stats` option is disabled
|
||||
|
||||
In the modern mode, reading the directory (`fs.readdir` with the `withFileTypes` option) is combined with obtaining information about its entries. An additional call for symbolic links (`fs.stat`) is still present.
|
||||
|
||||
This mode makes fewer calls to the file system. It's faster.
|
||||
|
||||
## Changelog
|
||||
|
||||
See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version.
|
||||
|
||||
## License
|
||||
|
||||
This software is released under the terms of the MIT license.
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import type * as fsStat from '@nodelib/fs.stat';
|
||||
import type { Dirent, ErrnoException } from '../types';
|
||||
export interface ReaddirAsynchronousMethod {
|
||||
(filepath: string, options: {
|
||||
withFileTypes: true;
|
||||
}, callback: (error: ErrnoException | null, files: Dirent[]) => void): void;
|
||||
(filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void;
|
||||
}
|
||||
export interface ReaddirSynchronousMethod {
|
||||
(filepath: string, options: {
|
||||
withFileTypes: true;
|
||||
}): Dirent[];
|
||||
(filepath: string): string[];
|
||||
}
|
||||
export declare type FileSystemAdapter = fsStat.FileSystemAdapter & {
|
||||
readdir: ReaddirAsynchronousMethod;
|
||||
readdirSync: ReaddirSynchronousMethod;
|
||||
};
|
||||
export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter;
|
||||
export declare function createFileSystemAdapter(fsMethods?: Partial<FileSystemAdapter>): FileSystemAdapter;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
|
||||
const fs = require("fs");
|
||||
exports.FILE_SYSTEM_ADAPTER = {
|
||||
lstat: fs.lstat,
|
||||
stat: fs.stat,
|
||||
lstatSync: fs.lstatSync,
|
||||
statSync: fs.statSync,
|
||||
readdir: fs.readdir,
|
||||
readdirSync: fs.readdirSync
|
||||
};
|
||||
function createFileSystemAdapter(fsMethods) {
|
||||
if (fsMethods === undefined) {
|
||||
return exports.FILE_SYSTEM_ADAPTER;
|
||||
}
|
||||
return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
|
||||
}
|
||||
exports.createFileSystemAdapter = createFileSystemAdapter;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* IS `true` for Node.js 10.10 and greater.
|
||||
*/
|
||||
export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
|
||||
const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
|
||||
if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
|
||||
throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
|
||||
}
|
||||
const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
|
||||
const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
|
||||
const SUPPORTED_MAJOR_VERSION = 10;
|
||||
const SUPPORTED_MINOR_VERSION = 10;
|
||||
const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
|
||||
const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
|
||||
/**
|
||||
* IS `true` for Node.js 10.10 and greater.
|
||||
*/
|
||||
exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod } from './adapters/fs';
|
||||
import * as async from './providers/async';
|
||||
import Settings, { Options } from './settings';
|
||||
import type { Dirent, Entry } from './types';
|
||||
declare type AsyncCallback = async.AsyncCallback;
|
||||
declare function scandir(path: string, callback: AsyncCallback): void;
|
||||
declare function scandir(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void;
|
||||
declare namespace scandir {
|
||||
function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise<Entry[]>;
|
||||
}
|
||||
declare function scandirSync(path: string, optionsOrSettings?: Options | Settings): Entry[];
|
||||
export { scandir, scandirSync, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod, Options };
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Settings = exports.scandirSync = exports.scandir = void 0;
|
||||
const async = require("./providers/async");
|
||||
const sync = require("./providers/sync");
|
||||
const settings_1 = require("./settings");
|
||||
exports.Settings = settings_1.default;
|
||||
function scandir(path, optionsOrSettingsOrCallback, callback) {
|
||||
if (typeof optionsOrSettingsOrCallback === 'function') {
|
||||
async.read(path, getSettings(), optionsOrSettingsOrCallback);
|
||||
return;
|
||||
}
|
||||
async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
|
||||
}
|
||||
exports.scandir = scandir;
|
||||
function scandirSync(path, optionsOrSettings) {
|
||||
const settings = getSettings(optionsOrSettings);
|
||||
return sync.read(path, settings);
|
||||
}
|
||||
exports.scandirSync = scandirSync;
|
||||
function getSettings(settingsOrOptions = {}) {
|
||||
if (settingsOrOptions instanceof settings_1.default) {
|
||||
return settingsOrOptions;
|
||||
}
|
||||
return new settings_1.default(settingsOrOptions);
|
||||
}
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
/// <reference types="node" />
|
||||
import type Settings from '../settings';
|
||||
import type { Entry } from '../types';
|
||||
export declare type AsyncCallback = (error: NodeJS.ErrnoException, entries: Entry[]) => void;
|
||||
export declare function read(directory: string, settings: Settings, callback: AsyncCallback): void;
|
||||
export declare function readdirWithFileTypes(directory: string, settings: Settings, callback: AsyncCallback): void;
|
||||
export declare function readdir(directory: string, settings: Settings, callback: AsyncCallback): void;
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
|
||||
const fsStat = require("@nodelib/fs.stat");
|
||||
const rpl = require("run-parallel");
|
||||
const constants_1 = require("../constants");
|
||||
const utils = require("../utils");
|
||||
const common = require("./common");
|
||||
function read(directory, settings, callback) {
|
||||
if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
|
||||
readdirWithFileTypes(directory, settings, callback);
|
||||
return;
|
||||
}
|
||||
readdir(directory, settings, callback);
|
||||
}
|
||||
exports.read = read;
|
||||
function readdirWithFileTypes(directory, settings, callback) {
|
||||
settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
|
||||
if (readdirError !== null) {
|
||||
callFailureCallback(callback, readdirError);
|
||||
return;
|
||||
}
|
||||
const entries = dirents.map((dirent) => ({
|
||||
dirent,
|
||||
name: dirent.name,
|
||||
path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
|
||||
}));
|
||||
if (!settings.followSymbolicLinks) {
|
||||
callSuccessCallback(callback, entries);
|
||||
return;
|
||||
}
|
||||
const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
|
||||
rpl(tasks, (rplError, rplEntries) => {
|
||||
if (rplError !== null) {
|
||||
callFailureCallback(callback, rplError);
|
||||
return;
|
||||
}
|
||||
callSuccessCallback(callback, rplEntries);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.readdirWithFileTypes = readdirWithFileTypes;
|
||||
function makeRplTaskEntry(entry, settings) {
|
||||
return (done) => {
|
||||
if (!entry.dirent.isSymbolicLink()) {
|
||||
done(null, entry);
|
||||
return;
|
||||
}
|
||||
settings.fs.stat(entry.path, (statError, stats) => {
|
||||
if (statError !== null) {
|
||||
if (settings.throwErrorOnBrokenSymbolicLink) {
|
||||
done(statError);
|
||||
return;
|
||||
}
|
||||
done(null, entry);
|
||||
return;
|
||||
}
|
||||
entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
|
||||
done(null, entry);
|
||||
});
|
||||
};
|
||||
}
|
||||
function readdir(directory, settings, callback) {
|
||||
settings.fs.readdir(directory, (readdirError, names) => {
|
||||
if (readdirError !== null) {
|
||||
callFailureCallback(callback, readdirError);
|
||||
return;
|
||||
}
|
||||
const tasks = names.map((name) => {
|
||||
const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
|
||||
return (done) => {
|
||||
fsStat.stat(path, settings.fsStatSettings, (error, stats) => {
|
||||
if (error !== null) {
|
||||
done(error);
|
||||
return;
|
||||
}
|
||||
const entry = {
|
||||
name,
|
||||
path,
|
||||
dirent: utils.fs.createDirentFromStats(name, stats)
|
||||
};
|
||||
if (settings.stats) {
|
||||
entry.stats = stats;
|
||||
}
|
||||
done(null, entry);
|
||||
});
|
||||
};
|
||||
});
|
||||
rpl(tasks, (rplError, entries) => {
|
||||
if (rplError !== null) {
|
||||
callFailureCallback(callback, rplError);
|
||||
return;
|
||||
}
|
||||
callSuccessCallback(callback, entries);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.readdir = readdir;
|
||||
function callFailureCallback(callback, error) {
|
||||
callback(error);
|
||||
}
|
||||
function callSuccessCallback(callback, result) {
|
||||
callback(null, result);
|
||||
}
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export declare function joinPathSegments(a: string, b: string, separator: string): string;
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.joinPathSegments = void 0;
|
||||
function joinPathSegments(a, b, separator) {
|
||||
/**
|
||||
* The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
|
||||
*/
|
||||
if (a.endsWith(separator)) {
|
||||
return a + b;
|
||||
}
|
||||
return a + separator + b;
|
||||
}
|
||||
exports.joinPathSegments = joinPathSegments;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type Settings from '../settings';
|
||||
import type { Entry } from '../types';
|
||||
export declare function read(directory: string, settings: Settings): Entry[];
|
||||
export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[];
|
||||
export declare function readdir(directory: string, settings: Settings): Entry[];
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.readdir = exports.readdirWithFileTypes = exports.read = void 0;
|
||||
const fsStat = require("@nodelib/fs.stat");
|
||||
const constants_1 = require("../constants");
|
||||
const utils = require("../utils");
|
||||
const common = require("./common");
|
||||
function read(directory, settings) {
|
||||
if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
|
||||
return readdirWithFileTypes(directory, settings);
|
||||
}
|
||||
return readdir(directory, settings);
|
||||
}
|
||||
exports.read = read;
|
||||
function readdirWithFileTypes(directory, settings) {
|
||||
const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
|
||||
return dirents.map((dirent) => {
|
||||
const entry = {
|
||||
dirent,
|
||||
name: dirent.name,
|
||||
path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
|
||||
};
|
||||
if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
|
||||
try {
|
||||
const stats = settings.fs.statSync(entry.path);
|
||||
entry.dirent = utils.fs.createDirentFromStats(entry.name, stats);
|
||||
}
|
||||
catch (error) {
|
||||
if (settings.throwErrorOnBrokenSymbolicLink) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
exports.readdirWithFileTypes = readdirWithFileTypes;
|
||||
function readdir(directory, settings) {
|
||||
const names = settings.fs.readdirSync(directory);
|
||||
return names.map((name) => {
|
||||
const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator);
|
||||
const stats = fsStat.statSync(entryPath, settings.fsStatSettings);
|
||||
const entry = {
|
||||
name,
|
||||
path: entryPath,
|
||||
dirent: utils.fs.createDirentFromStats(name, stats)
|
||||
};
|
||||
if (settings.stats) {
|
||||
entry.stats = stats;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
exports.readdir = readdir;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import * as fsStat from '@nodelib/fs.stat';
|
||||
import * as fs from './adapters/fs';
|
||||
export interface Options {
|
||||
followSymbolicLinks?: boolean;
|
||||
fs?: Partial<fs.FileSystemAdapter>;
|
||||
pathSegmentSeparator?: string;
|
||||
stats?: boolean;
|
||||
throwErrorOnBrokenSymbolicLink?: boolean;
|
||||
}
|
||||
export default class Settings {
|
||||
private readonly _options;
|
||||
readonly followSymbolicLinks: boolean;
|
||||
readonly fs: fs.FileSystemAdapter;
|
||||
readonly pathSegmentSeparator: string;
|
||||
readonly stats: boolean;
|
||||
readonly throwErrorOnBrokenSymbolicLink: boolean;
|
||||
readonly fsStatSettings: fsStat.Settings;
|
||||
constructor(_options?: Options);
|
||||
private _getValue;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const fsStat = require("@nodelib/fs.stat");
|
||||
const fs = require("./adapters/fs");
|
||||
class Settings {
|
||||
constructor(_options = {}) {
|
||||
this._options = _options;
|
||||
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
|
||||
this.fs = fs.createFileSystemAdapter(this._options.fs);
|
||||
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
|
||||
this.stats = this._getValue(this._options.stats, false);
|
||||
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
|
||||
this.fsStatSettings = new fsStat.Settings({
|
||||
followSymbolicLink: this.followSymbolicLinks,
|
||||
fs: this.fs,
|
||||
throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
|
||||
});
|
||||
}
|
||||
_getValue(option, value) {
|
||||
return option !== null && option !== void 0 ? option : value;
|
||||
}
|
||||
}
|
||||
exports.default = Settings;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/// <reference types="node" />
|
||||
import type * as fs from 'fs';
|
||||
export interface Entry {
|
||||
dirent: Dirent;
|
||||
name: string;
|
||||
path: string;
|
||||
stats?: Stats;
|
||||
}
|
||||
export declare type Stats = fs.Stats;
|
||||
export declare type ErrnoException = NodeJS.ErrnoException;
|
||||
export interface Dirent {
|
||||
isBlockDevice: () => boolean;
|
||||
isCharacterDevice: () => boolean;
|
||||
isDirectory: () => boolean;
|
||||
isFIFO: () => boolean;
|
||||
isFile: () => boolean;
|
||||
isSocket: () => boolean;
|
||||
isSymbolicLink: () => boolean;
|
||||
name: string;
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { Dirent, Stats } from '../types';
|
||||
export declare function createDirentFromStats(name: string, stats: Stats): Dirent;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createDirentFromStats = void 0;
|
||||
class DirentFromStats {
|
||||
constructor(name, stats) {
|
||||
this.name = name;
|
||||
this.isBlockDevice = stats.isBlockDevice.bind(stats);
|
||||
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
|
||||
this.isDirectory = stats.isDirectory.bind(stats);
|
||||
this.isFIFO = stats.isFIFO.bind(stats);
|
||||
this.isFile = stats.isFile.bind(stats);
|
||||
this.isSocket = stats.isSocket.bind(stats);
|
||||
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
|
||||
}
|
||||
}
|
||||
function createDirentFromStats(name, stats) {
|
||||
return new DirentFromStats(name, stats);
|
||||
}
|
||||
exports.createDirentFromStats = createDirentFromStats;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import * as fs from './fs';
|
||||
export { fs };
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fs = void 0;
|
||||
const fs = require("./fs");
|
||||
exports.fs = fs;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@nodelib/fs.scandir",
|
||||
"version": "2.1.5",
|
||||
"description": "List files and directories inside the specified directory",
|
||||
"license": "MIT",
|
||||
"repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir",
|
||||
"keywords": [
|
||||
"NodeLib",
|
||||
"fs",
|
||||
"FileSystem",
|
||||
"file system",
|
||||
"scandir",
|
||||
"readdir",
|
||||
"dirent"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
},
|
||||
"files": [
|
||||
"out/**",
|
||||
"!out/**/*.map",
|
||||
"!out/**/*.spec.*"
|
||||
],
|
||||
"main": "out/index.js",
|
||||
"typings": "out/index.d.ts",
|
||||
"scripts": {
|
||||
"clean": "rimraf {tsconfig.tsbuildinfo,out}",
|
||||
"lint": "eslint \"src/**/*.ts\" --cache",
|
||||
"compile": "tsc -b .",
|
||||
"compile:watch": "tsc -p . --watch --sourceMap",
|
||||
"test": "mocha \"out/**/*.spec.js\" -s 0",
|
||||
"build": "npm run clean && npm run compile && npm run lint && npm test",
|
||||
"watch": "npm run clean && npm run compile:watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "2.0.5",
|
||||
"run-parallel": "^1.1.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nodelib/fs.macchiato": "1.0.4",
|
||||
"@types/run-parallel": "^1.1.0"
|
||||
},
|
||||
"gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Denis Malinochkin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
# @nodelib/fs.stat
|
||||
|
||||
> Get the status of a file with some features.
|
||||
|
||||
## :bulb: Highlights
|
||||
|
||||
Wrapper around standard method `fs.lstat` and `fs.stat` with some features.
|
||||
|
||||
* :beginner: Normally follows symbolic link.
|
||||
* :gear: Can safely work with broken symbolic link.
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
npm install @nodelib/fs.stat
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import * as fsStat from '@nodelib/fs.stat';
|
||||
|
||||
fsStat.stat('path', (error, stats) => { /* … */ });
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### .stat(path, [optionsOrSettings], callback)
|
||||
|
||||
Returns an instance of `fs.Stats` class for provided path with standard callback-style.
|
||||
|
||||
```ts
|
||||
fsStat.stat('path', (error, stats) => { /* … */ });
|
||||
fsStat.stat('path', {}, (error, stats) => { /* … */ });
|
||||
fsStat.stat('path', new fsStat.Settings(), (error, stats) => { /* … */ });
|
||||
```
|
||||
|
||||
### .statSync(path, [optionsOrSettings])
|
||||
|
||||
Returns an instance of `fs.Stats` class for provided path.
|
||||
|
||||
```ts
|
||||
const stats = fsStat.stat('path');
|
||||
const stats = fsStat.stat('path', {});
|
||||
const stats = fsStat.stat('path', new fsStat.Settings());
|
||||
```
|
||||
|
||||
#### path
|
||||
|
||||
* Required: `true`
|
||||
* Type: `string | Buffer | URL`
|
||||
|
||||
A path to a file. If a URL is provided, it must use the `file:` protocol.
|
||||
|
||||
#### optionsOrSettings
|
||||
|
||||
* Required: `false`
|
||||
* Type: `Options | Settings`
|
||||
* Default: An instance of `Settings` class
|
||||
|
||||
An [`Options`](#options) object or an instance of [`Settings`](#settings) class.
|
||||
|
||||
> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class.
|
||||
|
||||
### Settings([options])
|
||||
|
||||
A class of full settings of the package.
|
||||
|
||||
```ts
|
||||
const settings = new fsStat.Settings({ followSymbolicLink: false });
|
||||
|
||||
const stats = fsStat.stat('path', settings);
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
### `followSymbolicLink`
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `true`
|
||||
|
||||
Follow symbolic link or not. Call `fs.stat` on symbolic link if `true`.
|
||||
|
||||
### `markSymbolicLink`
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `false`
|
||||
|
||||
Mark symbolic link by setting the return value of `isSymbolicLink` function to always `true` (even after `fs.stat`).
|
||||
|
||||
> :book: Can be used if you want to know what is hidden behind a symbolic link, but still continue to know that it is a symbolic link.
|
||||
|
||||
### `throwErrorOnBrokenSymbolicLink`
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `true`
|
||||
|
||||
Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`.
|
||||
|
||||
### `fs`
|
||||
|
||||
* Type: [`FileSystemAdapter`](./src/adapters/fs.ts)
|
||||
* Default: A default FS methods
|
||||
|
||||
By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own.
|
||||
|
||||
```ts
|
||||
interface FileSystemAdapter {
|
||||
lstat?: typeof fs.lstat;
|
||||
stat?: typeof fs.stat;
|
||||
lstatSync?: typeof fs.lstatSync;
|
||||
statSync?: typeof fs.statSync;
|
||||
}
|
||||
|
||||
const settings = new fsStat.Settings({
|
||||
fs: { lstat: fakeLstat }
|
||||
});
|
||||
```
|
||||
|
||||
## Changelog
|
||||
|
||||
See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version.
|
||||
|
||||
## License
|
||||
|
||||
This software is released under the terms of the MIT license.
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/// <reference types="node" />
|
||||
import * as fs from 'fs';
|
||||
import type { ErrnoException } from '../types';
|
||||
export declare type StatAsynchronousMethod = (path: string, callback: (error: ErrnoException | null, stats: fs.Stats) => void) => void;
|
||||
export declare type StatSynchronousMethod = (path: string) => fs.Stats;
|
||||
export interface FileSystemAdapter {
|
||||
lstat: StatAsynchronousMethod;
|
||||
stat: StatAsynchronousMethod;
|
||||
lstatSync: StatSynchronousMethod;
|
||||
statSync: StatSynchronousMethod;
|
||||
}
|
||||
export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter;
|
||||
export declare function createFileSystemAdapter(fsMethods?: Partial<FileSystemAdapter>): FileSystemAdapter;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
|
||||
const fs = require("fs");
|
||||
exports.FILE_SYSTEM_ADAPTER = {
|
||||
lstat: fs.lstat,
|
||||
stat: fs.stat,
|
||||
lstatSync: fs.lstatSync,
|
||||
statSync: fs.statSync
|
||||
};
|
||||
function createFileSystemAdapter(fsMethods) {
|
||||
if (fsMethods === undefined) {
|
||||
return exports.FILE_SYSTEM_ADAPTER;
|
||||
}
|
||||
return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
|
||||
}
|
||||
exports.createFileSystemAdapter = createFileSystemAdapter;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod } from './adapters/fs';
|
||||
import * as async from './providers/async';
|
||||
import Settings, { Options } from './settings';
|
||||
import type { Stats } from './types';
|
||||
declare type AsyncCallback = async.AsyncCallback;
|
||||
declare function stat(path: string, callback: AsyncCallback): void;
|
||||
declare function stat(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void;
|
||||
declare namespace stat {
|
||||
function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise<Stats>;
|
||||
}
|
||||
declare function statSync(path: string, optionsOrSettings?: Options | Settings): Stats;
|
||||
export { Settings, stat, statSync, AsyncCallback, FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod, Options, Stats };
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.statSync = exports.stat = exports.Settings = void 0;
|
||||
const async = require("./providers/async");
|
||||
const sync = require("./providers/sync");
|
||||
const settings_1 = require("./settings");
|
||||
exports.Settings = settings_1.default;
|
||||
function stat(path, optionsOrSettingsOrCallback, callback) {
|
||||
if (typeof optionsOrSettingsOrCallback === 'function') {
|
||||
async.read(path, getSettings(), optionsOrSettingsOrCallback);
|
||||
return;
|
||||
}
|
||||
async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
|
||||
}
|
||||
exports.stat = stat;
|
||||
function statSync(path, optionsOrSettings) {
|
||||
const settings = getSettings(optionsOrSettings);
|
||||
return sync.read(path, settings);
|
||||
}
|
||||
exports.statSync = statSync;
|
||||
function getSettings(settingsOrOptions = {}) {
|
||||
if (settingsOrOptions instanceof settings_1.default) {
|
||||
return settingsOrOptions;
|
||||
}
|
||||
return new settings_1.default(settingsOrOptions);
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import type Settings from '../settings';
|
||||
import type { ErrnoException, Stats } from '../types';
|
||||
export declare type AsyncCallback = (error: ErrnoException, stats: Stats) => void;
|
||||
export declare function read(path: string, settings: Settings, callback: AsyncCallback): void;
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.read = void 0;
|
||||
function read(path, settings, callback) {
|
||||
settings.fs.lstat(path, (lstatError, lstat) => {
|
||||
if (lstatError !== null) {
|
||||
callFailureCallback(callback, lstatError);
|
||||
return;
|
||||
}
|
||||
if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
|
||||
callSuccessCallback(callback, lstat);
|
||||
return;
|
||||
}
|
||||
settings.fs.stat(path, (statError, stat) => {
|
||||
if (statError !== null) {
|
||||
if (settings.throwErrorOnBrokenSymbolicLink) {
|
||||
callFailureCallback(callback, statError);
|
||||
return;
|
||||
}
|
||||
callSuccessCallback(callback, lstat);
|
||||
return;
|
||||
}
|
||||
if (settings.markSymbolicLink) {
|
||||
stat.isSymbolicLink = () => true;
|
||||
}
|
||||
callSuccessCallback(callback, stat);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.read = read;
|
||||
function callFailureCallback(callback, error) {
|
||||
callback(error);
|
||||
}
|
||||
function callSuccessCallback(callback, result) {
|
||||
callback(null, result);
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type Settings from '../settings';
|
||||
import type { Stats } from '../types';
|
||||
export declare function read(path: string, settings: Settings): Stats;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.read = void 0;
|
||||
function read(path, settings) {
|
||||
const lstat = settings.fs.lstatSync(path);
|
||||
if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
|
||||
return lstat;
|
||||
}
|
||||
try {
|
||||
const stat = settings.fs.statSync(path);
|
||||
if (settings.markSymbolicLink) {
|
||||
stat.isSymbolicLink = () => true;
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
catch (error) {
|
||||
if (!settings.throwErrorOnBrokenSymbolicLink) {
|
||||
return lstat;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
exports.read = read;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import * as fs from './adapters/fs';
|
||||
export interface Options {
|
||||
followSymbolicLink?: boolean;
|
||||
fs?: Partial<fs.FileSystemAdapter>;
|
||||
markSymbolicLink?: boolean;
|
||||
throwErrorOnBrokenSymbolicLink?: boolean;
|
||||
}
|
||||
export default class Settings {
|
||||
private readonly _options;
|
||||
readonly followSymbolicLink: boolean;
|
||||
readonly fs: fs.FileSystemAdapter;
|
||||
readonly markSymbolicLink: boolean;
|
||||
readonly throwErrorOnBrokenSymbolicLink: boolean;
|
||||
constructor(_options?: Options);
|
||||
private _getValue;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs = require("./adapters/fs");
|
||||
class Settings {
|
||||
constructor(_options = {}) {
|
||||
this._options = _options;
|
||||
this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
|
||||
this.fs = fs.createFileSystemAdapter(this._options.fs);
|
||||
this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
|
||||
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
|
||||
}
|
||||
_getValue(option, value) {
|
||||
return option !== null && option !== void 0 ? option : value;
|
||||
}
|
||||
}
|
||||
exports.default = Settings;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
/// <reference types="node" />
|
||||
import type * as fs from 'fs';
|
||||
export declare type Stats = fs.Stats;
|
||||
export declare type ErrnoException = NodeJS.ErrnoException;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@nodelib/fs.stat",
|
||||
"version": "2.0.5",
|
||||
"description": "Get the status of a file with some features",
|
||||
"license": "MIT",
|
||||
"repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat",
|
||||
"keywords": [
|
||||
"NodeLib",
|
||||
"fs",
|
||||
"FileSystem",
|
||||
"file system",
|
||||
"stat"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
},
|
||||
"files": [
|
||||
"out/**",
|
||||
"!out/**/*.map",
|
||||
"!out/**/*.spec.*"
|
||||
],
|
||||
"main": "out/index.js",
|
||||
"typings": "out/index.d.ts",
|
||||
"scripts": {
|
||||
"clean": "rimraf {tsconfig.tsbuildinfo,out}",
|
||||
"lint": "eslint \"src/**/*.ts\" --cache",
|
||||
"compile": "tsc -b .",
|
||||
"compile:watch": "tsc -p . --watch --sourceMap",
|
||||
"test": "mocha \"out/**/*.spec.js\" -s 0",
|
||||
"build": "npm run clean && npm run compile && npm run lint && npm test",
|
||||
"watch": "npm run clean && npm run compile:watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nodelib/fs.macchiato": "1.0.4"
|
||||
},
|
||||
"gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Denis Malinochkin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
# @nodelib/fs.walk
|
||||
|
||||
> A library for efficiently walking a directory recursively.
|
||||
|
||||
## :bulb: Highlights
|
||||
|
||||
* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional).
|
||||
* :rocket: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type for performance reasons. See [`old` and `modern` mode](https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode).
|
||||
* :gear: Built-in directories/files and error filtering system.
|
||||
* :link: Can safely work with broken symbolic links.
|
||||
|
||||
## Install
|
||||
|
||||
```console
|
||||
npm install @nodelib/fs.walk
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import * as fsWalk from '@nodelib/fs.walk';
|
||||
|
||||
fsWalk.walk('path', (error, entries) => { /* … */ });
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### .walk(path, [optionsOrSettings], callback)
|
||||
|
||||
Reads the directory recursively and asynchronously. Requires a callback function.
|
||||
|
||||
> :book: If you want to use the Promise API, use `util.promisify`.
|
||||
|
||||
```ts
|
||||
fsWalk.walk('path', (error, entries) => { /* … */ });
|
||||
fsWalk.walk('path', {}, (error, entries) => { /* … */ });
|
||||
fsWalk.walk('path', new fsWalk.Settings(), (error, entries) => { /* … */ });
|
||||
```
|
||||
|
||||
### .walkStream(path, [optionsOrSettings])
|
||||
|
||||
Reads the directory recursively and asynchronously. [Readable Stream](https://nodejs.org/dist/latest-v12.x/docs/api/stream.html#stream_readable_streams) is used as a provider.
|
||||
|
||||
```ts
|
||||
const stream = fsWalk.walkStream('path');
|
||||
const stream = fsWalk.walkStream('path', {});
|
||||
const stream = fsWalk.walkStream('path', new fsWalk.Settings());
|
||||
```
|
||||
|
||||
### .walkSync(path, [optionsOrSettings])
|
||||
|
||||
Reads the directory recursively and synchronously. Returns an array of entries.
|
||||
|
||||
```ts
|
||||
const entries = fsWalk.walkSync('path');
|
||||
const entries = fsWalk.walkSync('path', {});
|
||||
const entries = fsWalk.walkSync('path', new fsWalk.Settings());
|
||||
```
|
||||
|
||||
#### path
|
||||
|
||||
* Required: `true`
|
||||
* Type: `string | Buffer | URL`
|
||||
|
||||
A path to a file. If a URL is provided, it must use the `file:` protocol.
|
||||
|
||||
#### optionsOrSettings
|
||||
|
||||
* Required: `false`
|
||||
* Type: `Options | Settings`
|
||||
* Default: An instance of `Settings` class
|
||||
|
||||
An [`Options`](#options) object or an instance of [`Settings`](#settings) class.
|
||||
|
||||
> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class.
|
||||
|
||||
### Settings([options])
|
||||
|
||||
A class of full settings of the package.
|
||||
|
||||
```ts
|
||||
const settings = new fsWalk.Settings({ followSymbolicLinks: true });
|
||||
|
||||
const entries = fsWalk.walkSync('path', settings);
|
||||
```
|
||||
|
||||
## Entry
|
||||
|
||||
* `name` — The name of the entry (`unknown.txt`).
|
||||
* `path` — The path of the entry relative to call directory (`root/unknown.txt`).
|
||||
* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class.
|
||||
* [`stats`] — An instance of `fs.Stats` class.
|
||||
|
||||
## Options
|
||||
|
||||
### basePath
|
||||
|
||||
* Type: `string`
|
||||
* Default: `undefined`
|
||||
|
||||
By default, all paths are built relative to the root path. You can use this option to set custom root path.
|
||||
|
||||
In the example below we read the files from the `root` directory, but in the results the root path will be `custom`.
|
||||
|
||||
```ts
|
||||
fsWalk.walkSync('root'); // → ['root/file.txt']
|
||||
fsWalk.walkSync('root', { basePath: 'custom' }); // → ['custom/file.txt']
|
||||
```
|
||||
|
||||
### concurrency
|
||||
|
||||
* Type: `number`
|
||||
* Default: `Infinity`
|
||||
|
||||
The maximum number of concurrent calls to `fs.readdir`.
|
||||
|
||||
> :book: The higher the number, the higher performance and the load on the File System. If you want to read in quiet mode, set the value to `4 * os.cpus().length` (4 is default size of [thread pool work scheduling](http://docs.libuv.org/en/v1.x/threadpool.html#thread-pool-work-scheduling)).
|
||||
|
||||
### deepFilter
|
||||
|
||||
* Type: [`DeepFilterFunction`](./src/settings.ts)
|
||||
* Default: `undefined`
|
||||
|
||||
A function that indicates whether the directory will be read deep or not.
|
||||
|
||||
```ts
|
||||
// Skip all directories that starts with `node_modules`
|
||||
const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules');
|
||||
```
|
||||
|
||||
### entryFilter
|
||||
|
||||
* Type: [`EntryFilterFunction`](./src/settings.ts)
|
||||
* Default: `undefined`
|
||||
|
||||
A function that indicates whether the entry will be included to results or not.
|
||||
|
||||
```ts
|
||||
// Exclude all `.js` files from results
|
||||
const filter: EntryFilterFunction = (entry) => !entry.name.endsWith('.js');
|
||||
```
|
||||
|
||||
### errorFilter
|
||||
|
||||
* Type: [`ErrorFilterFunction`](./src/settings.ts)
|
||||
* Default: `undefined`
|
||||
|
||||
A function that allows you to skip errors that occur when reading directories.
|
||||
|
||||
For example, you can skip `ENOENT` errors if required:
|
||||
|
||||
```ts
|
||||
// Skip all ENOENT errors
|
||||
const filter: ErrorFilterFunction = (error) => error.code == 'ENOENT';
|
||||
```
|
||||
|
||||
### stats
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `false`
|
||||
|
||||
Adds an instance of `fs.Stats` class to the [`Entry`](#entry).
|
||||
|
||||
> :book: Always use `fs.readdir` with additional `fs.lstat/fs.stat` calls to determine the entry type.
|
||||
|
||||
### followSymbolicLinks
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `false`
|
||||
|
||||
Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`.
|
||||
|
||||
### `throwErrorOnBrokenSymbolicLink`
|
||||
|
||||
* Type: `boolean`
|
||||
* Default: `true`
|
||||
|
||||
Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`.
|
||||
|
||||
### `pathSegmentSeparator`
|
||||
|
||||
* Type: `string`
|
||||
* Default: `path.sep`
|
||||
|
||||
By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead.
|
||||
|
||||
### `fs`
|
||||
|
||||
* Type: `FileSystemAdapter`
|
||||
* Default: A default FS methods
|
||||
|
||||
By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own.
|
||||
|
||||
```ts
|
||||
interface FileSystemAdapter {
|
||||
lstat: typeof fs.lstat;
|
||||
stat: typeof fs.stat;
|
||||
lstatSync: typeof fs.lstatSync;
|
||||
statSync: typeof fs.statSync;
|
||||
readdir: typeof fs.readdir;
|
||||
readdirSync: typeof fs.readdirSync;
|
||||
}
|
||||
|
||||
const settings = new fsWalk.Settings({
|
||||
fs: { lstat: fakeLstat }
|
||||
});
|
||||
```
|
||||
|
||||
## Changelog
|
||||
|
||||
See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version.
|
||||
|
||||
## License
|
||||
|
||||
This software is released under the terms of the MIT license.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/// <reference types="node" />
|
||||
import type { Readable } from 'stream';
|
||||
import type { Dirent, FileSystemAdapter } from '@nodelib/fs.scandir';
|
||||
import { AsyncCallback } from './providers/async';
|
||||
import Settings, { DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction, Options } from './settings';
|
||||
import type { Entry } from './types';
|
||||
declare function walk(directory: string, callback: AsyncCallback): void;
|
||||
declare function walk(directory: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void;
|
||||
declare namespace walk {
|
||||
function __promisify__(directory: string, optionsOrSettings?: Options | Settings): Promise<Entry[]>;
|
||||
}
|
||||
declare function walkSync(directory: string, optionsOrSettings?: Options | Settings): Entry[];
|
||||
declare function walkStream(directory: string, optionsOrSettings?: Options | Settings): Readable;
|
||||
export { walk, walkSync, walkStream, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, Options, DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction };
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0;
|
||||
const async_1 = require("./providers/async");
|
||||
const stream_1 = require("./providers/stream");
|
||||
const sync_1 = require("./providers/sync");
|
||||
const settings_1 = require("./settings");
|
||||
exports.Settings = settings_1.default;
|
||||
function walk(directory, optionsOrSettingsOrCallback, callback) {
|
||||
if (typeof optionsOrSettingsOrCallback === 'function') {
|
||||
new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
|
||||
return;
|
||||
}
|
||||
new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
|
||||
}
|
||||
exports.walk = walk;
|
||||
function walkSync(directory, optionsOrSettings) {
|
||||
const settings = getSettings(optionsOrSettings);
|
||||
const provider = new sync_1.default(directory, settings);
|
||||
return provider.read();
|
||||
}
|
||||
exports.walkSync = walkSync;
|
||||
function walkStream(directory, optionsOrSettings) {
|
||||
const settings = getSettings(optionsOrSettings);
|
||||
const provider = new stream_1.default(directory, settings);
|
||||
return provider.read();
|
||||
}
|
||||
exports.walkStream = walkStream;
|
||||
function getSettings(settingsOrOptions = {}) {
|
||||
if (settingsOrOptions instanceof settings_1.default) {
|
||||
return settingsOrOptions;
|
||||
}
|
||||
return new settings_1.default(settingsOrOptions);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import AsyncReader from '../readers/async';
|
||||
import type Settings from '../settings';
|
||||
import type { Entry, Errno } from '../types';
|
||||
export declare type AsyncCallback = (error: Errno, entries: Entry[]) => void;
|
||||
export default class AsyncProvider {
|
||||
private readonly _root;
|
||||
private readonly _settings;
|
||||
protected readonly _reader: AsyncReader;
|
||||
private readonly _storage;
|
||||
constructor(_root: string, _settings: Settings);
|
||||
read(callback: AsyncCallback): void;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const async_1 = require("../readers/async");
|
||||
class AsyncProvider {
|
||||
constructor(_root, _settings) {
|
||||
this._root = _root;
|
||||
this._settings = _settings;
|
||||
this._reader = new async_1.default(this._root, this._settings);
|
||||
this._storage = [];
|
||||
}
|
||||
read(callback) {
|
||||
this._reader.onError((error) => {
|
||||
callFailureCallback(callback, error);
|
||||
});
|
||||
this._reader.onEntry((entry) => {
|
||||
this._storage.push(entry);
|
||||
});
|
||||
this._reader.onEnd(() => {
|
||||
callSuccessCallback(callback, this._storage);
|
||||
});
|
||||
this._reader.read();
|
||||
}
|
||||
}
|
||||
exports.default = AsyncProvider;
|
||||
function callFailureCallback(callback, error) {
|
||||
callback(error);
|
||||
}
|
||||
function callSuccessCallback(callback, entries) {
|
||||
callback(null, entries);
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import AsyncProvider from './async';
|
||||
import StreamProvider from './stream';
|
||||
import SyncProvider from './sync';
|
||||
export { AsyncProvider, StreamProvider, SyncProvider };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0;
|
||||
const async_1 = require("./async");
|
||||
exports.AsyncProvider = async_1.default;
|
||||
const stream_1 = require("./stream");
|
||||
exports.StreamProvider = stream_1.default;
|
||||
const sync_1 = require("./sync");
|
||||
exports.SyncProvider = sync_1.default;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/// <reference types="node" />
|
||||
import { Readable } from 'stream';
|
||||
import AsyncReader from '../readers/async';
|
||||
import type Settings from '../settings';
|
||||
export default class StreamProvider {
|
||||
private readonly _root;
|
||||
private readonly _settings;
|
||||
protected readonly _reader: AsyncReader;
|
||||
protected readonly _stream: Readable;
|
||||
constructor(_root: string, _settings: Settings);
|
||||
read(): Readable;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const stream_1 = require("stream");
|
||||
const async_1 = require("../readers/async");
|
||||
class StreamProvider {
|
||||
constructor(_root, _settings) {
|
||||
this._root = _root;
|
||||
this._settings = _settings;
|
||||
this._reader = new async_1.default(this._root, this._settings);
|
||||
this._stream = new stream_1.Readable({
|
||||
objectMode: true,
|
||||
read: () => { },
|
||||
destroy: () => {
|
||||
if (!this._reader.isDestroyed) {
|
||||
this._reader.destroy();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
read() {
|
||||
this._reader.onError((error) => {
|
||||
this._stream.emit('error', error);
|
||||
});
|
||||
this._reader.onEntry((entry) => {
|
||||
this._stream.push(entry);
|
||||
});
|
||||
this._reader.onEnd(() => {
|
||||
this._stream.push(null);
|
||||
});
|
||||
this._reader.read();
|
||||
return this._stream;
|
||||
}
|
||||
}
|
||||
exports.default = StreamProvider;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import SyncReader from '../readers/sync';
|
||||
import type Settings from '../settings';
|
||||
import type { Entry } from '../types';
|
||||
export default class SyncProvider {
|
||||
private readonly _root;
|
||||
private readonly _settings;
|
||||
protected readonly _reader: SyncReader;
|
||||
constructor(_root: string, _settings: Settings);
|
||||
read(): Entry[];
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const sync_1 = require("../readers/sync");
|
||||
class SyncProvider {
|
||||
constructor(_root, _settings) {
|
||||
this._root = _root;
|
||||
this._settings = _settings;
|
||||
this._reader = new sync_1.default(this._root, this._settings);
|
||||
}
|
||||
read() {
|
||||
return this._reader.read();
|
||||
}
|
||||
}
|
||||
exports.default = SyncProvider;
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/// <reference types="node" />
|
||||
import { EventEmitter } from 'events';
|
||||
import * as fsScandir from '@nodelib/fs.scandir';
|
||||
import type Settings from '../settings';
|
||||
import type { Entry, Errno } from '../types';
|
||||
import Reader from './reader';
|
||||
declare type EntryEventCallback = (entry: Entry) => void;
|
||||
declare type ErrorEventCallback = (error: Errno) => void;
|
||||
declare type EndEventCallback = () => void;
|
||||
export default class AsyncReader extends Reader {
|
||||
protected readonly _settings: Settings;
|
||||
protected readonly _scandir: typeof fsScandir.scandir;
|
||||
protected readonly _emitter: EventEmitter;
|
||||
private readonly _queue;
|
||||
private _isFatalError;
|
||||
private _isDestroyed;
|
||||
constructor(_root: string, _settings: Settings);
|
||||
read(): EventEmitter;
|
||||
get isDestroyed(): boolean;
|
||||
destroy(): void;
|
||||
onEntry(callback: EntryEventCallback): void;
|
||||
onError(callback: ErrorEventCallback): void;
|
||||
onEnd(callback: EndEventCallback): void;
|
||||
private _pushToQueue;
|
||||
private _worker;
|
||||
private _handleError;
|
||||
private _handleEntry;
|
||||
private _emitEntry;
|
||||
}
|
||||
export {};
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const events_1 = require("events");
|
||||
const fsScandir = require("@nodelib/fs.scandir");
|
||||
const fastq = require("fastq");
|
||||
const common = require("./common");
|
||||
const reader_1 = require("./reader");
|
||||
class AsyncReader extends reader_1.default {
|
||||
constructor(_root, _settings) {
|
||||
super(_root, _settings);
|
||||
this._settings = _settings;
|
||||
this._scandir = fsScandir.scandir;
|
||||
this._emitter = new events_1.EventEmitter();
|
||||
this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
|
||||
this._isFatalError = false;
|
||||
this._isDestroyed = false;
|
||||
this._queue.drain = () => {
|
||||
if (!this._isFatalError) {
|
||||
this._emitter.emit('end');
|
||||
}
|
||||
};
|
||||
}
|
||||
read() {
|
||||
this._isFatalError = false;
|
||||
this._isDestroyed = false;
|
||||
setImmediate(() => {
|
||||
this._pushToQueue(this._root, this._settings.basePath);
|
||||
});
|
||||
return this._emitter;
|
||||
}
|
||||
get isDestroyed() {
|
||||
return this._isDestroyed;
|
||||
}
|
||||
destroy() {
|
||||
if (this._isDestroyed) {
|
||||
throw new Error('The reader is already destroyed');
|
||||
}
|
||||
this._isDestroyed = true;
|
||||
this._queue.killAndDrain();
|
||||
}
|
||||
onEntry(callback) {
|
||||
this._emitter.on('entry', callback);
|
||||
}
|
||||
onError(callback) {
|
||||
this._emitter.once('error', callback);
|
||||
}
|
||||
onEnd(callback) {
|
||||
this._emitter.once('end', callback);
|
||||
}
|
||||
_pushToQueue(directory, base) {
|
||||
const queueItem = { directory, base };
|
||||
this._queue.push(queueItem, (error) => {
|
||||
if (error !== null) {
|
||||
this._handleError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
_worker(item, done) {
|
||||
this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
|
||||
if (error !== null) {
|
||||
done(error, undefined);
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
this._handleEntry(entry, item.base);
|
||||
}
|
||||
done(null, undefined);
|
||||
});
|
||||
}
|
||||
_handleError(error) {
|
||||
if (this._isDestroyed || !common.isFatalError(this._settings, error)) {
|
||||
return;
|
||||
}
|
||||
this._isFatalError = true;
|
||||
this._isDestroyed = true;
|
||||
this._emitter.emit('error', error);
|
||||
}
|
||||
_handleEntry(entry, base) {
|
||||
if (this._isDestroyed || this._isFatalError) {
|
||||
return;
|
||||
}
|
||||
const fullpath = entry.path;
|
||||
if (base !== undefined) {
|
||||
entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
|
||||
}
|
||||
if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
|
||||
this._emitEntry(entry);
|
||||
}
|
||||
if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
|
||||
this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
|
||||
}
|
||||
}
|
||||
_emitEntry(entry) {
|
||||
this._emitter.emit('entry', entry);
|
||||
}
|
||||
}
|
||||
exports.default = AsyncReader;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { FilterFunction } from '../settings';
|
||||
import type Settings from '../settings';
|
||||
import type { Errno } from '../types';
|
||||
export declare function isFatalError(settings: Settings, error: Errno): boolean;
|
||||
export declare function isAppliedFilter<T>(filter: FilterFunction<T> | null, value: T): boolean;
|
||||
export declare function replacePathSegmentSeparator(filepath: string, separator: string): string;
|
||||
export declare function joinPathSegments(a: string, b: string, separator: string): string;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0;
|
||||
function isFatalError(settings, error) {
|
||||
if (settings.errorFilter === null) {
|
||||
return true;
|
||||
}
|
||||
return !settings.errorFilter(error);
|
||||
}
|
||||
exports.isFatalError = isFatalError;
|
||||
function isAppliedFilter(filter, value) {
|
||||
return filter === null || filter(value);
|
||||
}
|
||||
exports.isAppliedFilter = isAppliedFilter;
|
||||
function replacePathSegmentSeparator(filepath, separator) {
|
||||
return filepath.split(/[/\\]/).join(separator);
|
||||
}
|
||||
exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
|
||||
function joinPathSegments(a, b, separator) {
|
||||
if (a === '') {
|
||||
return b;
|
||||
}
|
||||
/**
|
||||
* The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
|
||||
*/
|
||||
if (a.endsWith(separator)) {
|
||||
return a + b;
|
||||
}
|
||||
return a + separator + b;
|
||||
}
|
||||
exports.joinPathSegments = joinPathSegments;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import type Settings from '../settings';
|
||||
export default class Reader {
|
||||
protected readonly _root: string;
|
||||
protected readonly _settings: Settings;
|
||||
constructor(_root: string, _settings: Settings);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const common = require("./common");
|
||||
class Reader {
|
||||
constructor(_root, _settings) {
|
||||
this._root = _root;
|
||||
this._settings = _settings;
|
||||
this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
|
||||
}
|
||||
}
|
||||
exports.default = Reader;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import * as fsScandir from '@nodelib/fs.scandir';
|
||||
import type { Entry } from '../types';
|
||||
import Reader from './reader';
|
||||
export default class SyncReader extends Reader {
|
||||
protected readonly _scandir: typeof fsScandir.scandirSync;
|
||||
private readonly _storage;
|
||||
private readonly _queue;
|
||||
read(): Entry[];
|
||||
private _pushToQueue;
|
||||
private _handleQueue;
|
||||
private _handleDirectory;
|
||||
private _handleError;
|
||||
private _handleEntry;
|
||||
private _pushToStorage;
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fsScandir = require("@nodelib/fs.scandir");
|
||||
const common = require("./common");
|
||||
const reader_1 = require("./reader");
|
||||
class SyncReader extends reader_1.default {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this._scandir = fsScandir.scandirSync;
|
||||
this._storage = [];
|
||||
this._queue = new Set();
|
||||
}
|
||||
read() {
|
||||
this._pushToQueue(this._root, this._settings.basePath);
|
||||
this._handleQueue();
|
||||
return this._storage;
|
||||
}
|
||||
_pushToQueue(directory, base) {
|
||||
this._queue.add({ directory, base });
|
||||
}
|
||||
_handleQueue() {
|
||||
for (const item of this._queue.values()) {
|
||||
this._handleDirectory(item.directory, item.base);
|
||||
}
|
||||
}
|
||||
_handleDirectory(directory, base) {
|
||||
try {
|
||||
const entries = this._scandir(directory, this._settings.fsScandirSettings);
|
||||
for (const entry of entries) {
|
||||
this._handleEntry(entry, base);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
this._handleError(error);
|
||||
}
|
||||
}
|
||||
_handleError(error) {
|
||||
if (!common.isFatalError(this._settings, error)) {
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
_handleEntry(entry, base) {
|
||||
const fullpath = entry.path;
|
||||
if (base !== undefined) {
|
||||
entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
|
||||
}
|
||||
if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
|
||||
this._pushToStorage(entry);
|
||||
}
|
||||
if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
|
||||
this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
|
||||
}
|
||||
}
|
||||
_pushToStorage(entry) {
|
||||
this._storage.push(entry);
|
||||
}
|
||||
}
|
||||
exports.default = SyncReader;
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import * as fsScandir from '@nodelib/fs.scandir';
|
||||
import type { Entry, Errno } from './types';
|
||||
export declare type FilterFunction<T> = (value: T) => boolean;
|
||||
export declare type DeepFilterFunction = FilterFunction<Entry>;
|
||||
export declare type EntryFilterFunction = FilterFunction<Entry>;
|
||||
export declare type ErrorFilterFunction = FilterFunction<Errno>;
|
||||
export interface Options {
|
||||
basePath?: string;
|
||||
concurrency?: number;
|
||||
deepFilter?: DeepFilterFunction;
|
||||
entryFilter?: EntryFilterFunction;
|
||||
errorFilter?: ErrorFilterFunction;
|
||||
followSymbolicLinks?: boolean;
|
||||
fs?: Partial<fsScandir.FileSystemAdapter>;
|
||||
pathSegmentSeparator?: string;
|
||||
stats?: boolean;
|
||||
throwErrorOnBrokenSymbolicLink?: boolean;
|
||||
}
|
||||
export default class Settings {
|
||||
private readonly _options;
|
||||
readonly basePath?: string;
|
||||
readonly concurrency: number;
|
||||
readonly deepFilter: DeepFilterFunction | null;
|
||||
readonly entryFilter: EntryFilterFunction | null;
|
||||
readonly errorFilter: ErrorFilterFunction | null;
|
||||
readonly pathSegmentSeparator: string;
|
||||
readonly fsScandirSettings: fsScandir.Settings;
|
||||
constructor(_options?: Options);
|
||||
private _getValue;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const fsScandir = require("@nodelib/fs.scandir");
|
||||
class Settings {
|
||||
constructor(_options = {}) {
|
||||
this._options = _options;
|
||||
this.basePath = this._getValue(this._options.basePath, undefined);
|
||||
this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
|
||||
this.deepFilter = this._getValue(this._options.deepFilter, null);
|
||||
this.entryFilter = this._getValue(this._options.entryFilter, null);
|
||||
this.errorFilter = this._getValue(this._options.errorFilter, null);
|
||||
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep);
|
||||
this.fsScandirSettings = new fsScandir.Settings({
|
||||
followSymbolicLinks: this._options.followSymbolicLinks,
|
||||
fs: this._options.fs,
|
||||
pathSegmentSeparator: this._options.pathSegmentSeparator,
|
||||
stats: this._options.stats,
|
||||
throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
|
||||
});
|
||||
}
|
||||
_getValue(option, value) {
|
||||
return option !== null && option !== void 0 ? option : value;
|
||||
}
|
||||
}
|
||||
exports.default = Settings;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/// <reference types="node" />
|
||||
import type * as scandir from '@nodelib/fs.scandir';
|
||||
export declare type Entry = scandir.Entry;
|
||||
export declare type Errno = NodeJS.ErrnoException;
|
||||
export interface QueueItem {
|
||||
directory: string;
|
||||
base?: string;
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@nodelib/fs.walk",
|
||||
"version": "1.2.8",
|
||||
"description": "A library for efficiently walking a directory recursively",
|
||||
"license": "MIT",
|
||||
"repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk",
|
||||
"keywords": [
|
||||
"NodeLib",
|
||||
"fs",
|
||||
"FileSystem",
|
||||
"file system",
|
||||
"walk",
|
||||
"scanner",
|
||||
"crawler"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
},
|
||||
"files": [
|
||||
"out/**",
|
||||
"!out/**/*.map",
|
||||
"!out/**/*.spec.*",
|
||||
"!out/**/tests/**"
|
||||
],
|
||||
"main": "out/index.js",
|
||||
"typings": "out/index.d.ts",
|
||||
"scripts": {
|
||||
"clean": "rimraf {tsconfig.tsbuildinfo,out}",
|
||||
"lint": "eslint \"src/**/*.ts\" --cache",
|
||||
"compile": "tsc -b .",
|
||||
"compile:watch": "tsc -p . --watch --sourceMap",
|
||||
"test": "mocha \"out/**/*.spec.js\" -s 0",
|
||||
"build": "npm run clean && npm run compile && npm run lint && npm test",
|
||||
"watch": "npm run clean && npm run compile:watch"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nodelib/fs.scandir": "2.1.5",
|
||||
"fastq": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nodelib/fs.macchiato": "1.0.4"
|
||||
},
|
||||
"gitHead": "1e5bad48565da2b06b8600e744324ea240bf49d8"
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
# `@rollup/rollup-linux-arm64-gnu`
|
||||
|
||||
This is the **aarch64-unknown-linux-gnu** binary for `rollup`
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "@rollup/rollup-linux-arm64-gnu",
|
||||
"version": "4.62.2",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"files": [
|
||||
"rollup.linux-arm64-gnu.node"
|
||||
],
|
||||
"description": "Native bindings for Rollup",
|
||||
"author": "Lukas Taegert-Atkinson",
|
||||
"homepage": "https://rollupjs.org/",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/rollup/rollup.git"
|
||||
},
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"main": "./rollup.linux-arm64-gnu.node"
|
||||
}
|
||||
Generated
Vendored
BIN
Binary file not shown.
+35
@@ -0,0 +1,35 @@
|
||||
import * as Types from '../typebox';
|
||||
import { ValueErrorIterator } from '../errors/index';
|
||||
export type CheckFunction = (value: unknown) => boolean;
|
||||
export declare class TypeCheck<T extends Types.TSchema> {
|
||||
private readonly schema;
|
||||
private readonly references;
|
||||
private readonly checkFunc;
|
||||
private readonly code;
|
||||
constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string);
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
Code(): string;
|
||||
/** Returns an iterator for each error in this value. */
|
||||
Errors(value: unknown): ValueErrorIterator;
|
||||
/** Returns true if the value matches the compiled type. */
|
||||
Check(value: unknown): value is Types.Static<T>;
|
||||
}
|
||||
export declare class TypeCompilerUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class TypeCompilerDereferenceError extends Error {
|
||||
readonly schema: Types.TRef;
|
||||
constructor(schema: Types.TRef);
|
||||
}
|
||||
export declare class TypeCompilerTypeGuardError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
/** Compiles Types for Runtime Type Checking */
|
||||
export declare namespace TypeCompiler {
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
function Code<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): string;
|
||||
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
||||
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
|
||||
}
|
||||
+577
@@ -0,0 +1,577 @@
|
||||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/compiler
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TypeCompiler = exports.TypeCompilerTypeGuardError = exports.TypeCompilerDereferenceError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
|
||||
const Types = require("../typebox");
|
||||
const index_1 = require("../errors/index");
|
||||
const index_2 = require("../system/index");
|
||||
const hash_1 = require("../value/hash");
|
||||
// -------------------------------------------------------------------
|
||||
// TypeCheck
|
||||
// -------------------------------------------------------------------
|
||||
class TypeCheck {
|
||||
constructor(schema, references, checkFunc, code) {
|
||||
this.schema = schema;
|
||||
this.references = references;
|
||||
this.checkFunc = checkFunc;
|
||||
this.code = code;
|
||||
}
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
Code() {
|
||||
return this.code;
|
||||
}
|
||||
/** Returns an iterator for each error in this value. */
|
||||
Errors(value) {
|
||||
return index_1.ValueErrors.Errors(this.schema, this.references, value);
|
||||
}
|
||||
/** Returns true if the value matches the compiled type. */
|
||||
Check(value) {
|
||||
return this.checkFunc(value);
|
||||
}
|
||||
}
|
||||
exports.TypeCheck = TypeCheck;
|
||||
// -------------------------------------------------------------------
|
||||
// Character
|
||||
// -------------------------------------------------------------------
|
||||
var Character;
|
||||
(function (Character) {
|
||||
function DollarSign(code) {
|
||||
return code === 36;
|
||||
}
|
||||
Character.DollarSign = DollarSign;
|
||||
function IsUnderscore(code) {
|
||||
return code === 95;
|
||||
}
|
||||
Character.IsUnderscore = IsUnderscore;
|
||||
function IsAlpha(code) {
|
||||
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
Character.IsAlpha = IsAlpha;
|
||||
function IsNumeric(code) {
|
||||
return code >= 48 && code <= 57;
|
||||
}
|
||||
Character.IsNumeric = IsNumeric;
|
||||
})(Character || (Character = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// MemberExpression
|
||||
// -------------------------------------------------------------------
|
||||
var MemberExpression;
|
||||
(function (MemberExpression) {
|
||||
function IsFirstCharacterNumeric(value) {
|
||||
if (value.length === 0)
|
||||
return false;
|
||||
return Character.IsNumeric(value.charCodeAt(0));
|
||||
}
|
||||
function IsAccessor(value) {
|
||||
if (IsFirstCharacterNumeric(value))
|
||||
return false;
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code);
|
||||
if (!check)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function EscapeHyphen(key) {
|
||||
return key.replace(/'/g, "\\'");
|
||||
}
|
||||
function Encode(object, key) {
|
||||
return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`;
|
||||
}
|
||||
MemberExpression.Encode = Encode;
|
||||
})(MemberExpression || (MemberExpression = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// Identifier
|
||||
// -------------------------------------------------------------------
|
||||
var Identifier;
|
||||
(function (Identifier) {
|
||||
function Encode($id) {
|
||||
const buffer = [];
|
||||
for (let i = 0; i < $id.length; i++) {
|
||||
const code = $id.charCodeAt(i);
|
||||
if (Character.IsNumeric(code) || Character.IsAlpha(code)) {
|
||||
buffer.push($id.charAt(i));
|
||||
}
|
||||
else {
|
||||
buffer.push(`_${code}_`);
|
||||
}
|
||||
}
|
||||
return buffer.join('').replace(/__/g, '_');
|
||||
}
|
||||
Identifier.Encode = Encode;
|
||||
})(Identifier || (Identifier = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// TypeCompiler
|
||||
// -------------------------------------------------------------------
|
||||
class TypeCompilerUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('TypeCompiler: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
|
||||
class TypeCompilerDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`TypeCompiler: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerDereferenceError = TypeCompilerDereferenceError;
|
||||
class TypeCompilerTypeGuardError extends Error {
|
||||
constructor(schema) {
|
||||
super('TypeCompiler: Preflight validation check failed to guard for the given schema');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
|
||||
/** Compiles Types for Runtime Type Checking */
|
||||
var TypeCompiler;
|
||||
(function (TypeCompiler) {
|
||||
// -------------------------------------------------------------------
|
||||
// Guards
|
||||
// -------------------------------------------------------------------
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsNumber(value) {
|
||||
return typeof value === 'number' && globalThis.Number.isFinite(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Polices
|
||||
// -------------------------------------------------------------------
|
||||
function IsExactOptionalProperty(value, key, expression) {
|
||||
return index_2.TypeSystem.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
|
||||
}
|
||||
function IsObjectCheck(value) {
|
||||
return !index_2.TypeSystem.AllowArrayObjects ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
|
||||
}
|
||||
function IsRecordCheck(value) {
|
||||
return !index_2.TypeSystem.AllowArrayObjects
|
||||
? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`
|
||||
: `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`;
|
||||
}
|
||||
function IsNumberCheck(value) {
|
||||
return !index_2.TypeSystem.AllowNaN ? `(typeof ${value} === 'number' && Number.isFinite(${value}))` : `typeof ${value} === 'number'`;
|
||||
}
|
||||
function IsVoidCheck(value) {
|
||||
return index_2.TypeSystem.AllowVoidNull ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Types
|
||||
// -------------------------------------------------------------------
|
||||
function* Any(schema, references, value) {
|
||||
yield 'true';
|
||||
}
|
||||
function* Array(schema, references, value) {
|
||||
const expression = CreateExpression(schema.items, references, 'value');
|
||||
yield `Array.isArray(${value}) && ${value}.every(value => ${expression})`;
|
||||
if (IsNumber(schema.minItems))
|
||||
yield `${value}.length >= ${schema.minItems}`;
|
||||
if (IsNumber(schema.maxItems))
|
||||
yield `${value}.length <= ${schema.maxItems}`;
|
||||
if (schema.uniqueItems === true)
|
||||
yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
|
||||
}
|
||||
function* BigInt(schema, references, value) {
|
||||
yield `(typeof ${value} === 'bigint')`;
|
||||
if (IsBigInt(schema.multipleOf))
|
||||
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
|
||||
if (IsBigInt(schema.exclusiveMinimum))
|
||||
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
|
||||
if (IsBigInt(schema.exclusiveMaximum))
|
||||
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
|
||||
if (IsBigInt(schema.minimum))
|
||||
yield `${value} >= BigInt(${schema.minimum})`;
|
||||
if (IsBigInt(schema.maximum))
|
||||
yield `${value} <= BigInt(${schema.maximum})`;
|
||||
}
|
||||
function* Boolean(schema, references, value) {
|
||||
yield `typeof ${value} === 'boolean'`;
|
||||
}
|
||||
function* Constructor(schema, references, value) {
|
||||
yield* Visit(schema.returns, references, `${value}.prototype`);
|
||||
}
|
||||
function* Date(schema, references, value) {
|
||||
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
|
||||
if (IsNumber(schema.exclusiveMinimumTimestamp))
|
||||
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
|
||||
if (IsNumber(schema.exclusiveMaximumTimestamp))
|
||||
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
|
||||
if (IsNumber(schema.minimumTimestamp))
|
||||
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
|
||||
if (IsNumber(schema.maximumTimestamp))
|
||||
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
|
||||
}
|
||||
function* Function(schema, references, value) {
|
||||
yield `typeof ${value} === 'function'`;
|
||||
}
|
||||
function* Integer(schema, references, value) {
|
||||
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
|
||||
if (IsNumber(schema.multipleOf))
|
||||
yield `(${value} % ${schema.multipleOf}) === 0`;
|
||||
if (IsNumber(schema.exclusiveMinimum))
|
||||
yield `${value} > ${schema.exclusiveMinimum}`;
|
||||
if (IsNumber(schema.exclusiveMaximum))
|
||||
yield `${value} < ${schema.exclusiveMaximum}`;
|
||||
if (IsNumber(schema.minimum))
|
||||
yield `${value} >= ${schema.minimum}`;
|
||||
if (IsNumber(schema.maximum))
|
||||
yield `${value} <= ${schema.maximum}`;
|
||||
}
|
||||
function* Intersect(schema, references, value) {
|
||||
if (schema.unevaluatedProperties === undefined) {
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
yield `${expressions.join(' && ')}`;
|
||||
}
|
||||
else if (schema.unevaluatedProperties === false) {
|
||||
// prettier-ignore
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
const expression1 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key))`;
|
||||
yield `${expressions.join(' && ')} && ${expression1}`;
|
||||
}
|
||||
else if (typeof schema.unevaluatedProperties === 'object') {
|
||||
// prettier-ignore
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
const expression1 = CreateExpression(schema.unevaluatedProperties, references, 'value[key]');
|
||||
const expression2 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key) || ${expression1})`;
|
||||
yield `${expressions.join(' && ')} && ${expression2}`;
|
||||
}
|
||||
}
|
||||
function* Literal(schema, references, value) {
|
||||
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
|
||||
yield `${value} === ${schema.const}`;
|
||||
}
|
||||
else {
|
||||
yield `${value} === '${schema.const}'`;
|
||||
}
|
||||
}
|
||||
function* Never(schema, references, value) {
|
||||
yield `false`;
|
||||
}
|
||||
function* Not(schema, references, value) {
|
||||
const left = CreateExpression(schema.allOf[0].not, references, value);
|
||||
const right = CreateExpression(schema.allOf[1], references, value);
|
||||
yield `!${left} && ${right}`;
|
||||
}
|
||||
function* Null(schema, references, value) {
|
||||
yield `${value} === null`;
|
||||
}
|
||||
function* Number(schema, references, value) {
|
||||
yield IsNumberCheck(value);
|
||||
if (IsNumber(schema.multipleOf))
|
||||
yield `(${value} % ${schema.multipleOf}) === 0`;
|
||||
if (IsNumber(schema.exclusiveMinimum))
|
||||
yield `${value} > ${schema.exclusiveMinimum}`;
|
||||
if (IsNumber(schema.exclusiveMaximum))
|
||||
yield `${value} < ${schema.exclusiveMaximum}`;
|
||||
if (IsNumber(schema.minimum))
|
||||
yield `${value} >= ${schema.minimum}`;
|
||||
if (IsNumber(schema.maximum))
|
||||
yield `${value} <= ${schema.maximum}`;
|
||||
}
|
||||
function* Object(schema, references, value) {
|
||||
yield IsObjectCheck(value);
|
||||
if (IsNumber(schema.minProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
|
||||
if (IsNumber(schema.maxProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
|
||||
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
for (const knownKey of knownKeys) {
|
||||
const memberExpression = MemberExpression.Encode(value, knownKey);
|
||||
const property = schema.properties[knownKey];
|
||||
if (schema.required && schema.required.includes(knownKey)) {
|
||||
yield* Visit(property, references, memberExpression);
|
||||
if (Types.ExtendsUndefined.Check(property))
|
||||
yield `('${knownKey}' in ${value})`;
|
||||
}
|
||||
else {
|
||||
const expression = CreateExpression(property, references, memberExpression);
|
||||
yield IsExactOptionalProperty(value, knownKey, expression);
|
||||
}
|
||||
}
|
||||
if (schema.additionalProperties === false) {
|
||||
if (schema.required && schema.required.length === knownKeys.length) {
|
||||
yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`;
|
||||
}
|
||||
else {
|
||||
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
|
||||
yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`;
|
||||
}
|
||||
}
|
||||
if (typeof schema.additionalProperties === 'object') {
|
||||
const expression = CreateExpression(schema.additionalProperties, references, 'value[key]');
|
||||
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
|
||||
yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
|
||||
}
|
||||
}
|
||||
function* Promise(schema, references, value) {
|
||||
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
|
||||
}
|
||||
function* Record(schema, references, value) {
|
||||
yield IsRecordCheck(value);
|
||||
if (IsNumber(schema.minProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
|
||||
if (IsNumber(schema.maxProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
|
||||
yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
|
||||
const expression = CreateExpression(valueSchema, references, 'value');
|
||||
yield `Object.values(${value}).every(value => ${expression})`;
|
||||
}
|
||||
function* Ref(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new TypeCompilerDereferenceError(schema);
|
||||
const target = references[index];
|
||||
// Reference: If we have seen this reference before we can just yield and return
|
||||
// the function call. If this isn't the case we defer to visit to generate and
|
||||
// set the function for subsequent passes. Consider for refactor.
|
||||
if (state_local_function_names.has(schema.$ref))
|
||||
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
|
||||
yield* Visit(target, references, value);
|
||||
}
|
||||
function* String(schema, references, value) {
|
||||
yield `(typeof ${value} === 'string')`;
|
||||
if (IsNumber(schema.minLength))
|
||||
yield `${value}.length >= ${schema.minLength}`;
|
||||
if (IsNumber(schema.maxLength))
|
||||
yield `${value}.length <= ${schema.maxLength}`;
|
||||
if (schema.pattern !== undefined) {
|
||||
const local = PushLocal(`${new RegExp(schema.pattern)};`);
|
||||
yield `${local}.test(${value})`;
|
||||
}
|
||||
if (schema.format !== undefined) {
|
||||
yield `format('${schema.format}', ${value})`;
|
||||
}
|
||||
}
|
||||
function* Symbol(schema, references, value) {
|
||||
yield `(typeof ${value} === 'symbol')`;
|
||||
}
|
||||
function* TemplateLiteral(schema, references, value) {
|
||||
yield `(typeof ${value} === 'string')`;
|
||||
const local = PushLocal(`${new RegExp(schema.pattern)};`);
|
||||
yield `${local}.test(${value})`;
|
||||
}
|
||||
function* This(schema, references, value) {
|
||||
const func = CreateFunctionName(schema.$ref);
|
||||
yield `${func}(${value})`;
|
||||
}
|
||||
function* Tuple(schema, references, value) {
|
||||
yield `(Array.isArray(${value}))`;
|
||||
if (schema.items === undefined)
|
||||
return yield `${value}.length === 0`;
|
||||
yield `(${value}.length === ${schema.maxItems})`;
|
||||
for (let i = 0; i < schema.items.length; i++) {
|
||||
const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`);
|
||||
yield `${expression}`;
|
||||
}
|
||||
}
|
||||
function* Undefined(schema, references, value) {
|
||||
yield `${value} === undefined`;
|
||||
}
|
||||
function* Union(schema, references, value) {
|
||||
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
|
||||
yield `(${expressions.join(' || ')})`;
|
||||
}
|
||||
function* Uint8Array(schema, references, value) {
|
||||
yield `${value} instanceof Uint8Array`;
|
||||
if (IsNumber(schema.maxByteLength))
|
||||
yield `(${value}.length <= ${schema.maxByteLength})`;
|
||||
if (IsNumber(schema.minByteLength))
|
||||
yield `(${value}.length >= ${schema.minByteLength})`;
|
||||
}
|
||||
function* Unknown(schema, references, value) {
|
||||
yield 'true';
|
||||
}
|
||||
function* Void(schema, references, value) {
|
||||
yield IsVoidCheck(value);
|
||||
}
|
||||
function* UserDefined(schema, references, value) {
|
||||
const schema_key = `schema_key_${state_remote_custom_types.size}`;
|
||||
state_remote_custom_types.set(schema_key, schema);
|
||||
yield `custom('${schema[Types.Kind]}', '${schema_key}', ${value})`;
|
||||
}
|
||||
function* Visit(schema, references, value) {
|
||||
const references_ = IsString(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
// Reference: Referenced schemas can originate from either additional schemas
|
||||
// or inline in the schema itself. Ideally the recursive path should align to
|
||||
// reference path. Consider for refactor.
|
||||
if (IsString(schema.$id) && !state_local_function_names.has(schema.$id)) {
|
||||
state_local_function_names.add(schema.$id);
|
||||
const name = CreateFunctionName(schema.$id);
|
||||
const body = CreateFunction(name, schema, references, 'value');
|
||||
PushFunction(body);
|
||||
yield `${name}(${value})`;
|
||||
return;
|
||||
}
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return yield* Any(schema_, references_, value);
|
||||
case 'Array':
|
||||
return yield* Array(schema_, references_, value);
|
||||
case 'BigInt':
|
||||
return yield* BigInt(schema_, references_, value);
|
||||
case 'Boolean':
|
||||
return yield* Boolean(schema_, references_, value);
|
||||
case 'Constructor':
|
||||
return yield* Constructor(schema_, references_, value);
|
||||
case 'Date':
|
||||
return yield* Date(schema_, references_, value);
|
||||
case 'Function':
|
||||
return yield* Function(schema_, references_, value);
|
||||
case 'Integer':
|
||||
return yield* Integer(schema_, references_, value);
|
||||
case 'Intersect':
|
||||
return yield* Intersect(schema_, references_, value);
|
||||
case 'Literal':
|
||||
return yield* Literal(schema_, references_, value);
|
||||
case 'Never':
|
||||
return yield* Never(schema_, references_, value);
|
||||
case 'Not':
|
||||
return yield* Not(schema_, references_, value);
|
||||
case 'Null':
|
||||
return yield* Null(schema_, references_, value);
|
||||
case 'Number':
|
||||
return yield* Number(schema_, references_, value);
|
||||
case 'Object':
|
||||
return yield* Object(schema_, references_, value);
|
||||
case 'Promise':
|
||||
return yield* Promise(schema_, references_, value);
|
||||
case 'Record':
|
||||
return yield* Record(schema_, references_, value);
|
||||
case 'Ref':
|
||||
return yield* Ref(schema_, references_, value);
|
||||
case 'String':
|
||||
return yield* String(schema_, references_, value);
|
||||
case 'Symbol':
|
||||
return yield* Symbol(schema_, references_, value);
|
||||
case 'TemplateLiteral':
|
||||
return yield* TemplateLiteral(schema_, references_, value);
|
||||
case 'This':
|
||||
return yield* This(schema_, references_, value);
|
||||
case 'Tuple':
|
||||
return yield* Tuple(schema_, references_, value);
|
||||
case 'Undefined':
|
||||
return yield* Undefined(schema_, references_, value);
|
||||
case 'Union':
|
||||
return yield* Union(schema_, references_, value);
|
||||
case 'Uint8Array':
|
||||
return yield* Uint8Array(schema_, references_, value);
|
||||
case 'Unknown':
|
||||
return yield* Unknown(schema_, references_, value);
|
||||
case 'Void':
|
||||
return yield* Void(schema_, references_, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new TypeCompilerUnknownTypeError(schema);
|
||||
return yield* UserDefined(schema_, references_, value);
|
||||
}
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Compiler State
|
||||
// -------------------------------------------------------------------
|
||||
const state_local_variables = new Set(); // local variables and functions
|
||||
const state_local_function_names = new Set(); // local function names used call ref validators
|
||||
const state_remote_custom_types = new Map(); // remote custom types used during compilation
|
||||
function ResetCompiler() {
|
||||
state_local_variables.clear();
|
||||
state_local_function_names.clear();
|
||||
state_remote_custom_types.clear();
|
||||
}
|
||||
function CreateExpression(schema, references, value) {
|
||||
return `(${[...Visit(schema, references, value)].join(' && ')})`;
|
||||
}
|
||||
function CreateFunctionName($id) {
|
||||
return `check_${Identifier.Encode($id)}`;
|
||||
}
|
||||
function CreateFunction(name, schema, references, value) {
|
||||
const expression = [...Visit(schema, references, value)].map((condition) => ` ${condition}`).join(' &&\n');
|
||||
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
|
||||
}
|
||||
function PushFunction(functionBody) {
|
||||
state_local_variables.add(functionBody);
|
||||
}
|
||||
function PushLocal(expression) {
|
||||
const local = `local_${state_local_variables.size}`;
|
||||
state_local_variables.add(`const ${local} = ${expression}`);
|
||||
return local;
|
||||
}
|
||||
function GetLocals() {
|
||||
return [...state_local_variables.values()];
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Compile
|
||||
// -------------------------------------------------------------------
|
||||
function Build(schema, references) {
|
||||
ResetCompiler();
|
||||
const check = CreateFunction('check', schema, references, 'value');
|
||||
const locals = GetLocals();
|
||||
return `${locals.join('\n')}\nreturn ${check}`;
|
||||
}
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
function Code(schema, references = []) {
|
||||
if (!Types.TypeGuard.TSchema(schema))
|
||||
throw new TypeCompilerTypeGuardError(schema);
|
||||
for (const schema of references)
|
||||
if (!Types.TypeGuard.TSchema(schema))
|
||||
throw new TypeCompilerTypeGuardError(schema);
|
||||
return Build(schema, references);
|
||||
}
|
||||
TypeCompiler.Code = Code;
|
||||
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
||||
function Compile(schema, references = []) {
|
||||
const code = Code(schema, references);
|
||||
const custom_schemas = new Map(state_remote_custom_types);
|
||||
const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
|
||||
const checkFunction = compiledFunction((kind, schema_key, value) => {
|
||||
if (!Types.TypeRegistry.Has(kind) || !custom_schemas.has(schema_key))
|
||||
return false;
|
||||
const schema = custom_schemas.get(schema_key);
|
||||
const func = Types.TypeRegistry.Get(kind);
|
||||
return func(schema, value);
|
||||
}, (format, value) => {
|
||||
if (!Types.FormatRegistry.Has(format))
|
||||
return false;
|
||||
const func = Types.FormatRegistry.Get(format);
|
||||
return func(value);
|
||||
}, (value) => {
|
||||
return hash_1.ValueHash.Create(value);
|
||||
});
|
||||
return new TypeCheck(schema, references, checkFunction, code);
|
||||
}
|
||||
TypeCompiler.Compile = Compile;
|
||||
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export { ValueError, ValueErrorType } from '../errors/index';
|
||||
export * from './compiler';
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/compiler
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueErrorType = void 0;
|
||||
var index_1 = require("../errors/index");
|
||||
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
|
||||
__exportStar(require("./compiler"), exports);
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import * as Types from '../typebox';
|
||||
export declare enum ValueErrorType {
|
||||
Array = 0,
|
||||
ArrayMinItems = 1,
|
||||
ArrayMaxItems = 2,
|
||||
ArrayUniqueItems = 3,
|
||||
BigInt = 4,
|
||||
BigIntMultipleOf = 5,
|
||||
BigIntExclusiveMinimum = 6,
|
||||
BigIntExclusiveMaximum = 7,
|
||||
BigIntMinimum = 8,
|
||||
BigIntMaximum = 9,
|
||||
Boolean = 10,
|
||||
Date = 11,
|
||||
DateExclusiveMinimumTimestamp = 12,
|
||||
DateExclusiveMaximumTimestamp = 13,
|
||||
DateMinimumTimestamp = 14,
|
||||
DateMaximumTimestamp = 15,
|
||||
Function = 16,
|
||||
Integer = 17,
|
||||
IntegerMultipleOf = 18,
|
||||
IntegerExclusiveMinimum = 19,
|
||||
IntegerExclusiveMaximum = 20,
|
||||
IntegerMinimum = 21,
|
||||
IntegerMaximum = 22,
|
||||
Intersect = 23,
|
||||
IntersectUnevaluatedProperties = 24,
|
||||
Literal = 25,
|
||||
Never = 26,
|
||||
Not = 27,
|
||||
Null = 28,
|
||||
Number = 29,
|
||||
NumberMultipleOf = 30,
|
||||
NumberExclusiveMinimum = 31,
|
||||
NumberExclusiveMaximum = 32,
|
||||
NumberMinumum = 33,
|
||||
NumberMaximum = 34,
|
||||
Object = 35,
|
||||
ObjectMinProperties = 36,
|
||||
ObjectMaxProperties = 37,
|
||||
ObjectAdditionalProperties = 38,
|
||||
ObjectRequiredProperties = 39,
|
||||
Promise = 40,
|
||||
RecordKeyNumeric = 41,
|
||||
RecordKeyString = 42,
|
||||
String = 43,
|
||||
StringMinLength = 44,
|
||||
StringMaxLength = 45,
|
||||
StringPattern = 46,
|
||||
StringFormatUnknown = 47,
|
||||
StringFormat = 48,
|
||||
Symbol = 49,
|
||||
TupleZeroLength = 50,
|
||||
TupleLength = 51,
|
||||
Undefined = 52,
|
||||
Union = 53,
|
||||
Uint8Array = 54,
|
||||
Uint8ArrayMinByteLength = 55,
|
||||
Uint8ArrayMaxByteLength = 56,
|
||||
Void = 57,
|
||||
Custom = 58
|
||||
}
|
||||
export interface ValueError {
|
||||
type: ValueErrorType;
|
||||
schema: Types.TSchema;
|
||||
path: string;
|
||||
value: unknown;
|
||||
message: string;
|
||||
}
|
||||
export declare class ValueErrorIterator {
|
||||
private readonly iterator;
|
||||
constructor(iterator: IterableIterator<ValueError>);
|
||||
[Symbol.iterator](): IterableIterator<ValueError>;
|
||||
/** Returns the first value error or undefined if no errors */
|
||||
First(): ValueError | undefined;
|
||||
}
|
||||
export declare class ValueErrorsUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueErrorsDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
|
||||
export declare namespace ValueErrors {
|
||||
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): ValueErrorIterator;
|
||||
}
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueErrors = exports.ValueErrorsDereferenceError = exports.ValueErrorsUnknownTypeError = exports.ValueErrorIterator = exports.ValueErrorType = void 0;
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/errors
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
const Types = require("../typebox");
|
||||
const index_1 = require("../system/index");
|
||||
const hash_1 = require("../value/hash");
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrorType
|
||||
// -------------------------------------------------------------------
|
||||
var ValueErrorType;
|
||||
(function (ValueErrorType) {
|
||||
ValueErrorType[ValueErrorType["Array"] = 0] = "Array";
|
||||
ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems";
|
||||
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
|
||||
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems";
|
||||
ValueErrorType[ValueErrorType["BigInt"] = 4] = "BigInt";
|
||||
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 5] = "BigIntMultipleOf";
|
||||
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 6] = "BigIntExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 7] = "BigIntExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["BigIntMinimum"] = 8] = "BigIntMinimum";
|
||||
ValueErrorType[ValueErrorType["BigIntMaximum"] = 9] = "BigIntMaximum";
|
||||
ValueErrorType[ValueErrorType["Boolean"] = 10] = "Boolean";
|
||||
ValueErrorType[ValueErrorType["Date"] = 11] = "Date";
|
||||
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 12] = "DateExclusiveMinimumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 13] = "DateExclusiveMaximumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 14] = "DateMinimumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 15] = "DateMaximumTimestamp";
|
||||
ValueErrorType[ValueErrorType["Function"] = 16] = "Function";
|
||||
ValueErrorType[ValueErrorType["Integer"] = 17] = "Integer";
|
||||
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 18] = "IntegerMultipleOf";
|
||||
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 19] = "IntegerExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 20] = "IntegerExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["IntegerMinimum"] = 21] = "IntegerMinimum";
|
||||
ValueErrorType[ValueErrorType["IntegerMaximum"] = 22] = "IntegerMaximum";
|
||||
ValueErrorType[ValueErrorType["Intersect"] = 23] = "Intersect";
|
||||
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 24] = "IntersectUnevaluatedProperties";
|
||||
ValueErrorType[ValueErrorType["Literal"] = 25] = "Literal";
|
||||
ValueErrorType[ValueErrorType["Never"] = 26] = "Never";
|
||||
ValueErrorType[ValueErrorType["Not"] = 27] = "Not";
|
||||
ValueErrorType[ValueErrorType["Null"] = 28] = "Null";
|
||||
ValueErrorType[ValueErrorType["Number"] = 29] = "Number";
|
||||
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 30] = "NumberMultipleOf";
|
||||
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 31] = "NumberExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 32] = "NumberExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["NumberMinumum"] = 33] = "NumberMinumum";
|
||||
ValueErrorType[ValueErrorType["NumberMaximum"] = 34] = "NumberMaximum";
|
||||
ValueErrorType[ValueErrorType["Object"] = 35] = "Object";
|
||||
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 36] = "ObjectMinProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 37] = "ObjectMaxProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 38] = "ObjectAdditionalProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 39] = "ObjectRequiredProperties";
|
||||
ValueErrorType[ValueErrorType["Promise"] = 40] = "Promise";
|
||||
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 41] = "RecordKeyNumeric";
|
||||
ValueErrorType[ValueErrorType["RecordKeyString"] = 42] = "RecordKeyString";
|
||||
ValueErrorType[ValueErrorType["String"] = 43] = "String";
|
||||
ValueErrorType[ValueErrorType["StringMinLength"] = 44] = "StringMinLength";
|
||||
ValueErrorType[ValueErrorType["StringMaxLength"] = 45] = "StringMaxLength";
|
||||
ValueErrorType[ValueErrorType["StringPattern"] = 46] = "StringPattern";
|
||||
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 47] = "StringFormatUnknown";
|
||||
ValueErrorType[ValueErrorType["StringFormat"] = 48] = "StringFormat";
|
||||
ValueErrorType[ValueErrorType["Symbol"] = 49] = "Symbol";
|
||||
ValueErrorType[ValueErrorType["TupleZeroLength"] = 50] = "TupleZeroLength";
|
||||
ValueErrorType[ValueErrorType["TupleLength"] = 51] = "TupleLength";
|
||||
ValueErrorType[ValueErrorType["Undefined"] = 52] = "Undefined";
|
||||
ValueErrorType[ValueErrorType["Union"] = 53] = "Union";
|
||||
ValueErrorType[ValueErrorType["Uint8Array"] = 54] = "Uint8Array";
|
||||
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 55] = "Uint8ArrayMinByteLength";
|
||||
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 56] = "Uint8ArrayMaxByteLength";
|
||||
ValueErrorType[ValueErrorType["Void"] = 57] = "Void";
|
||||
ValueErrorType[ValueErrorType["Custom"] = 58] = "Custom";
|
||||
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrorIterator
|
||||
// -------------------------------------------------------------------
|
||||
class ValueErrorIterator {
|
||||
constructor(iterator) {
|
||||
this.iterator = iterator;
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this.iterator;
|
||||
}
|
||||
/** Returns the first value error or undefined if no errors */
|
||||
First() {
|
||||
const next = this.iterator.next();
|
||||
return next.done ? undefined : next.value;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorIterator = ValueErrorIterator;
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrors
|
||||
// -------------------------------------------------------------------
|
||||
class ValueErrorsUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueErrors: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
|
||||
class ValueErrorsDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueErrors: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorsDereferenceError = ValueErrorsDereferenceError;
|
||||
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
|
||||
var ValueErrors;
|
||||
(function (ValueErrors) {
|
||||
// ----------------------------------------------------------------------
|
||||
// Guards
|
||||
// ----------------------------------------------------------------------
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsInteger(value) {
|
||||
return globalThis.Number.isInteger(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
function IsDefined(value) {
|
||||
return value !== undefined;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Policies
|
||||
// ----------------------------------------------------------------------
|
||||
function IsExactOptionalProperty(value, key) {
|
||||
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
|
||||
}
|
||||
function IsObject(value) {
|
||||
const result = typeof value === 'object' && value !== null;
|
||||
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsRecordObject(value) {
|
||||
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
|
||||
}
|
||||
function IsNumber(value) {
|
||||
const result = typeof value === 'number';
|
||||
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
|
||||
}
|
||||
function IsVoid(value) {
|
||||
const result = value === undefined;
|
||||
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Types
|
||||
// ----------------------------------------------------------------------
|
||||
function* Any(schema, references, path, value) { }
|
||||
function* Array(schema, references, path, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` };
|
||||
}
|
||||
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
|
||||
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
|
||||
}
|
||||
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
|
||||
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
|
||||
}
|
||||
// prettier-ignore
|
||||
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
|
||||
const hashed = hash_1.ValueHash.Create(element);
|
||||
if (set.has(hashed)) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
set.add(hashed);
|
||||
}
|
||||
} return true; })())) {
|
||||
yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` };
|
||||
}
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
|
||||
}
|
||||
}
|
||||
function* BigInt(schema, references, path, value) {
|
||||
if (!IsBigInt(value)) {
|
||||
return yield { type: ValueErrorType.BigInt, schema, path, value, message: `Expected bigint` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
|
||||
yield { type: ValueErrorType.BigIntMultipleOf, schema, path, value, message: `Expected bigint to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.BigIntExclusiveMinimum, schema, path, value, message: `Expected bigint to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.BigIntExclusiveMaximum, schema, path, value, message: `Expected bigint to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.BigIntMinimum, schema, path, value, message: `Expected bigint to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.BigIntMaximum, schema, path, value, message: `Expected bigint to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Boolean(schema, references, path, value) {
|
||||
if (!(typeof value === 'boolean')) {
|
||||
return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` };
|
||||
}
|
||||
}
|
||||
function* Constructor(schema, references, path, value) {
|
||||
yield* Visit(schema.returns, references, path, value.prototype);
|
||||
}
|
||||
function* Date(schema, references, path, value) {
|
||||
if (!(value instanceof globalThis.Date)) {
|
||||
return yield { type: ValueErrorType.Date, schema, path, value, message: `Expected Date object` };
|
||||
}
|
||||
if (!globalThis.isFinite(value.getTime())) {
|
||||
return yield { type: ValueErrorType.Date, schema, path, value, message: `Invalid Date` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Function(schema, references, path, value) {
|
||||
if (!(typeof value === 'function')) {
|
||||
return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` };
|
||||
}
|
||||
}
|
||||
function* Integer(schema, references, path, value) {
|
||||
if (!IsInteger(value)) {
|
||||
return yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Intersect(schema, references, path, value) {
|
||||
for (const subschema of schema.allOf) {
|
||||
const next = Visit(subschema, references, path, value).next();
|
||||
if (!next.done) {
|
||||
yield next.value;
|
||||
yield { type: ValueErrorType.Intersect, schema, path, value, message: `Expected all sub schemas to be valid` };
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (schema.unevaluatedProperties === false) {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const valueKey of valueKeys) {
|
||||
if (!schemaKeys.includes(valueKey)) {
|
||||
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Unexpected property` };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof schema.unevaluatedProperties === 'object') {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const valueKey of valueKeys) {
|
||||
if (!schemaKeys.includes(valueKey)) {
|
||||
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
|
||||
if (!next.done) {
|
||||
yield next.value;
|
||||
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Invalid additional property` };
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Literal(schema, references, path, value) {
|
||||
if (!(value === schema.const)) {
|
||||
const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const;
|
||||
return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` };
|
||||
}
|
||||
}
|
||||
function* Never(schema, references, path, value) {
|
||||
yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` };
|
||||
}
|
||||
function* Not(schema, references, path, value) {
|
||||
if (Visit(schema.allOf[0].not, references, path, value).next().done === true) {
|
||||
yield { type: ValueErrorType.Not, schema, path, value, message: `Value should not validate` };
|
||||
}
|
||||
yield* Visit(schema.allOf[1], references, path, value);
|
||||
}
|
||||
function* Null(schema, references, path, value) {
|
||||
if (!(value === null)) {
|
||||
return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` };
|
||||
}
|
||||
}
|
||||
function* Number(schema, references, path, value) {
|
||||
if (!IsNumber(value)) {
|
||||
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Object(schema, references, path, value) {
|
||||
if (!IsObject(value)) {
|
||||
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
|
||||
}
|
||||
const requiredKeys = globalThis.Array.isArray(schema.required) ? schema.required : [];
|
||||
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
const unknownKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const knownKey of knownKeys) {
|
||||
const property = schema.properties[knownKey];
|
||||
if (schema.required && schema.required.includes(knownKey)) {
|
||||
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
|
||||
if (Types.ExtendsUndefined.Check(schema) && !(knownKey in value)) {
|
||||
yield { type: ValueErrorType.ObjectRequiredProperties, schema: property, path: `${path}/${knownKey}`, value: undefined, message: `Expected required property` };
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (IsExactOptionalProperty(value, knownKey)) {
|
||||
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const requiredKey of requiredKeys) {
|
||||
if (unknownKeys.includes(requiredKey))
|
||||
continue;
|
||||
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
|
||||
}
|
||||
if (schema.additionalProperties === false) {
|
||||
for (const valueKey of unknownKeys) {
|
||||
if (!knownKeys.includes(valueKey)) {
|
||||
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${valueKey}`, value: value[valueKey], message: `Unexpected property` };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof schema.additionalProperties === 'object') {
|
||||
for (const valueKey of unknownKeys) {
|
||||
if (knownKeys.includes(valueKey))
|
||||
continue;
|
||||
yield* Visit(schema.additionalProperties, references, `${path}/${valueKey}`, value[valueKey]);
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Promise(schema, references, path, value) {
|
||||
if (!(typeof value === 'object' && typeof value.then === 'function')) {
|
||||
yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` };
|
||||
}
|
||||
}
|
||||
function* Record(schema, references, path, value) {
|
||||
if (!IsRecordObject(value)) {
|
||||
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected record object` };
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
|
||||
}
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
const regex = new RegExp(keyPattern);
|
||||
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
|
||||
const numeric = keyPattern === Types.PatternNumberExact;
|
||||
const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString;
|
||||
const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings';
|
||||
return yield { type, schema, path, value, message };
|
||||
}
|
||||
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
|
||||
yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue);
|
||||
}
|
||||
}
|
||||
function* Ref(schema, references, path, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueErrorsDereferenceError(schema);
|
||||
const target = references[index];
|
||||
yield* Visit(target, references, path, value);
|
||||
}
|
||||
function* String(schema, references, path, value) {
|
||||
if (!IsString(value)) {
|
||||
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
|
||||
}
|
||||
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
|
||||
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
|
||||
}
|
||||
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
|
||||
yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` };
|
||||
}
|
||||
if (schema.pattern !== undefined) {
|
||||
const regex = new RegExp(schema.pattern);
|
||||
if (!regex.test(value)) {
|
||||
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
|
||||
}
|
||||
}
|
||||
if (schema.format !== undefined) {
|
||||
if (!Types.FormatRegistry.Has(schema.format)) {
|
||||
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
|
||||
}
|
||||
else {
|
||||
const format = Types.FormatRegistry.Get(schema.format);
|
||||
if (!format(value)) {
|
||||
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Symbol(schema, references, path, value) {
|
||||
if (!(typeof value === 'symbol')) {
|
||||
return yield { type: ValueErrorType.Symbol, schema, path, value, message: 'Expected symbol' };
|
||||
}
|
||||
}
|
||||
function* TemplateLiteral(schema, references, path, value) {
|
||||
if (!IsString(value)) {
|
||||
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
|
||||
}
|
||||
const regex = new RegExp(schema.pattern);
|
||||
if (!regex.test(value)) {
|
||||
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
|
||||
}
|
||||
}
|
||||
function* This(schema, references, path, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueErrorsDereferenceError(schema);
|
||||
const target = references[index];
|
||||
yield* Visit(target, references, path, value);
|
||||
}
|
||||
function* Tuple(schema, references, path, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' };
|
||||
}
|
||||
if (schema.items === undefined && !(value.length === 0)) {
|
||||
return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' };
|
||||
}
|
||||
if (!(value.length === schema.maxItems)) {
|
||||
yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` };
|
||||
}
|
||||
if (!schema.items) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < schema.items.length; i++) {
|
||||
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
|
||||
}
|
||||
}
|
||||
function* Undefined(schema, references, path, value) {
|
||||
if (!(value === undefined)) {
|
||||
yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` };
|
||||
}
|
||||
}
|
||||
function* Union(schema, references, path, value) {
|
||||
const errors = [];
|
||||
for (const inner of schema.anyOf) {
|
||||
const variantErrors = [...Visit(inner, references, path, value)];
|
||||
if (variantErrors.length === 0)
|
||||
return;
|
||||
errors.push(...variantErrors);
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
|
||||
}
|
||||
for (const error of errors) {
|
||||
yield error;
|
||||
}
|
||||
}
|
||||
function* Uint8Array(schema, references, path, value) {
|
||||
if (!(value instanceof globalThis.Uint8Array)) {
|
||||
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
|
||||
}
|
||||
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
|
||||
yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` };
|
||||
}
|
||||
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
|
||||
yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` };
|
||||
}
|
||||
}
|
||||
function* Unknown(schema, references, path, value) { }
|
||||
function* Void(schema, references, path, value) {
|
||||
if (!IsVoid(value)) {
|
||||
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected void` };
|
||||
}
|
||||
}
|
||||
function* UserDefined(schema, references, path, value) {
|
||||
const check = Types.TypeRegistry.Get(schema[Types.Kind]);
|
||||
if (!check(schema, value)) {
|
||||
return yield { type: ValueErrorType.Custom, schema, path, value, message: `Expected kind ${schema[Types.Kind]}` };
|
||||
}
|
||||
}
|
||||
function* Visit(schema, references, path, value) {
|
||||
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return yield* Any(schema_, references_, path, value);
|
||||
case 'Array':
|
||||
return yield* Array(schema_, references_, path, value);
|
||||
case 'BigInt':
|
||||
return yield* BigInt(schema_, references_, path, value);
|
||||
case 'Boolean':
|
||||
return yield* Boolean(schema_, references_, path, value);
|
||||
case 'Constructor':
|
||||
return yield* Constructor(schema_, references_, path, value);
|
||||
case 'Date':
|
||||
return yield* Date(schema_, references_, path, value);
|
||||
case 'Function':
|
||||
return yield* Function(schema_, references_, path, value);
|
||||
case 'Integer':
|
||||
return yield* Integer(schema_, references_, path, value);
|
||||
case 'Intersect':
|
||||
return yield* Intersect(schema_, references_, path, value);
|
||||
case 'Literal':
|
||||
return yield* Literal(schema_, references_, path, value);
|
||||
case 'Never':
|
||||
return yield* Never(schema_, references_, path, value);
|
||||
case 'Not':
|
||||
return yield* Not(schema_, references_, path, value);
|
||||
case 'Null':
|
||||
return yield* Null(schema_, references_, path, value);
|
||||
case 'Number':
|
||||
return yield* Number(schema_, references_, path, value);
|
||||
case 'Object':
|
||||
return yield* Object(schema_, references_, path, value);
|
||||
case 'Promise':
|
||||
return yield* Promise(schema_, references_, path, value);
|
||||
case 'Record':
|
||||
return yield* Record(schema_, references_, path, value);
|
||||
case 'Ref':
|
||||
return yield* Ref(schema_, references_, path, value);
|
||||
case 'String':
|
||||
return yield* String(schema_, references_, path, value);
|
||||
case 'Symbol':
|
||||
return yield* Symbol(schema_, references_, path, value);
|
||||
case 'TemplateLiteral':
|
||||
return yield* TemplateLiteral(schema_, references_, path, value);
|
||||
case 'This':
|
||||
return yield* This(schema_, references_, path, value);
|
||||
case 'Tuple':
|
||||
return yield* Tuple(schema_, references_, path, value);
|
||||
case 'Undefined':
|
||||
return yield* Undefined(schema_, references_, path, value);
|
||||
case 'Union':
|
||||
return yield* Union(schema_, references_, path, value);
|
||||
case 'Uint8Array':
|
||||
return yield* Uint8Array(schema_, references_, path, value);
|
||||
case 'Unknown':
|
||||
return yield* Unknown(schema_, references_, path, value);
|
||||
case 'Void':
|
||||
return yield* Void(schema_, references_, path, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueErrorsUnknownTypeError(schema);
|
||||
return yield* UserDefined(schema_, references_, path, value);
|
||||
}
|
||||
}
|
||||
function Errors(schema, references, value) {
|
||||
const iterator = Visit(schema, references, '', value);
|
||||
return new ValueErrorIterator(iterator);
|
||||
}
|
||||
ValueErrors.Errors = Errors;
|
||||
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from './errors';
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/errors
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./errors"), exports);
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user